PackageManagerService.java revision d589c185c5b9c81c67c68f28c4c08c2c434db64e
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75import static android.content.pm.PackageManager.PERMISSION_DENIED;
76import static android.content.pm.PackageManager.PERMISSION_GRANTED;
77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78import static android.content.pm.PackageParser.isApkFile;
79import static android.os.Process.PACKAGE_INFO_GID;
80import static android.os.Process.SYSTEM_UID;
81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
82import static android.system.OsConstants.O_CREAT;
83import static android.system.OsConstants.O_RDWR;
84
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
89import static com.android.internal.util.ArrayUtils.appendInt;
90import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
101
102import android.Manifest;
103import android.annotation.NonNull;
104import android.annotation.Nullable;
105import android.annotation.UserIdInt;
106import android.app.ActivityManager;
107import android.app.ActivityManagerNative;
108import android.app.IActivityManager;
109import android.app.ResourcesManager;
110import android.app.admin.IDevicePolicyManager;
111import android.app.admin.SecurityLog;
112import android.app.backup.IBackupManager;
113import android.content.BroadcastReceiver;
114import android.content.ComponentName;
115import android.content.Context;
116import android.content.IIntentReceiver;
117import android.content.Intent;
118import android.content.IntentFilter;
119import android.content.IntentSender;
120import android.content.IntentSender.SendIntentException;
121import android.content.ServiceConnection;
122import android.content.pm.ActivityInfo;
123import android.content.pm.ApplicationInfo;
124import android.content.pm.AppsQueryHelper;
125import android.content.pm.ComponentInfo;
126import android.content.pm.EphemeralApplicationInfo;
127import android.content.pm.EphemeralResolveInfo;
128import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
129import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
130import android.content.pm.FeatureInfo;
131import android.content.pm.IOnPermissionsChangeListener;
132import android.content.pm.IPackageDataObserver;
133import android.content.pm.IPackageDeleteObserver;
134import android.content.pm.IPackageDeleteObserver2;
135import android.content.pm.IPackageInstallObserver2;
136import android.content.pm.IPackageInstaller;
137import android.content.pm.IPackageManager;
138import android.content.pm.IPackageMoveObserver;
139import android.content.pm.IPackageStatsObserver;
140import android.content.pm.InstrumentationInfo;
141import android.content.pm.IntentFilterVerificationInfo;
142import android.content.pm.KeySet;
143import android.content.pm.PackageCleanItem;
144import android.content.pm.PackageInfo;
145import android.content.pm.PackageInfoLite;
146import android.content.pm.PackageInstaller;
147import android.content.pm.PackageManager;
148import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
149import android.content.pm.PackageManagerInternal;
150import android.content.pm.PackageParser;
151import android.content.pm.PackageParser.ActivityIntentInfo;
152import android.content.pm.PackageParser.PackageLite;
153import android.content.pm.PackageParser.PackageParserException;
154import android.content.pm.PackageStats;
155import android.content.pm.PackageUserState;
156import android.content.pm.ParceledListSlice;
157import android.content.pm.PermissionGroupInfo;
158import android.content.pm.PermissionInfo;
159import android.content.pm.ProviderInfo;
160import android.content.pm.ResolveInfo;
161import android.content.pm.ServiceInfo;
162import android.content.pm.Signature;
163import android.content.pm.UserInfo;
164import android.content.pm.VerifierDeviceIdentity;
165import android.content.pm.VerifierInfo;
166import android.content.res.Resources;
167import android.graphics.Bitmap;
168import android.hardware.display.DisplayManager;
169import android.net.Uri;
170import android.os.Binder;
171import android.os.Build;
172import android.os.Bundle;
173import android.os.Debug;
174import android.os.Environment;
175import android.os.Environment.UserEnvironment;
176import android.os.FileUtils;
177import android.os.Handler;
178import android.os.IBinder;
179import android.os.Looper;
180import android.os.Message;
181import android.os.Parcel;
182import android.os.ParcelFileDescriptor;
183import android.os.Process;
184import android.os.RemoteCallbackList;
185import android.os.RemoteException;
186import android.os.ResultReceiver;
187import android.os.SELinux;
188import android.os.ServiceManager;
189import android.os.SystemClock;
190import android.os.SystemProperties;
191import android.os.Trace;
192import android.os.UserHandle;
193import android.os.UserManager;
194import android.os.UserManagerInternal;
195import android.os.storage.IMountService;
196import android.os.storage.MountServiceInternal;
197import android.os.storage.StorageEventListener;
198import android.os.storage.StorageManager;
199import android.os.storage.VolumeInfo;
200import android.os.storage.VolumeRecord;
201import android.provider.Settings.Global;
202import android.security.KeyStore;
203import android.security.SystemKeyStore;
204import android.system.ErrnoException;
205import android.system.Os;
206import android.text.TextUtils;
207import android.text.format.DateUtils;
208import android.util.ArrayMap;
209import android.util.ArraySet;
210import android.util.AtomicFile;
211import android.util.DisplayMetrics;
212import android.util.EventLog;
213import android.util.ExceptionUtils;
214import android.util.Log;
215import android.util.LogPrinter;
216import android.util.MathUtils;
217import android.util.PrintStreamPrinter;
218import android.util.Slog;
219import android.util.SparseArray;
220import android.util.SparseBooleanArray;
221import android.util.SparseIntArray;
222import android.util.Xml;
223import android.util.jar.StrictJarFile;
224import android.view.Display;
225
226import com.android.internal.R;
227import com.android.internal.annotations.GuardedBy;
228import com.android.internal.app.IMediaContainerService;
229import com.android.internal.app.ResolverActivity;
230import com.android.internal.content.NativeLibraryHelper;
231import com.android.internal.content.PackageHelper;
232import com.android.internal.logging.MetricsLogger;
233import com.android.internal.os.IParcelFileDescriptorFactory;
234import com.android.internal.os.InstallerConnection.InstallerException;
235import com.android.internal.os.SomeArgs;
236import com.android.internal.os.Zygote;
237import com.android.internal.telephony.CarrierAppUtils;
238import com.android.internal.util.ArrayUtils;
239import com.android.internal.util.FastPrintWriter;
240import com.android.internal.util.FastXmlSerializer;
241import com.android.internal.util.IndentingPrintWriter;
242import com.android.internal.util.Preconditions;
243import com.android.internal.util.XmlUtils;
244import com.android.server.AttributeCache;
245import com.android.server.EventLogTags;
246import com.android.server.FgThread;
247import com.android.server.IntentResolver;
248import com.android.server.LocalServices;
249import com.android.server.ServiceThread;
250import com.android.server.SystemConfig;
251import com.android.server.Watchdog;
252import com.android.server.net.NetworkPolicyManagerInternal;
253import com.android.server.pm.PermissionsState.PermissionState;
254import com.android.server.pm.Settings.DatabaseVersion;
255import com.android.server.pm.Settings.VersionInfo;
256import com.android.server.storage.DeviceStorageMonitorInternal;
257
258import dalvik.system.CloseGuard;
259import dalvik.system.DexFile;
260import dalvik.system.VMRuntime;
261
262import libcore.io.IoUtils;
263import libcore.util.EmptyArray;
264
265import org.xmlpull.v1.XmlPullParser;
266import org.xmlpull.v1.XmlPullParserException;
267import org.xmlpull.v1.XmlSerializer;
268
269import java.io.BufferedInputStream;
270import java.io.BufferedOutputStream;
271import java.io.BufferedReader;
272import java.io.ByteArrayInputStream;
273import java.io.ByteArrayOutputStream;
274import java.io.File;
275import java.io.FileDescriptor;
276import java.io.FileInputStream;
277import java.io.FileNotFoundException;
278import java.io.FileOutputStream;
279import java.io.FileReader;
280import java.io.FilenameFilter;
281import java.io.IOException;
282import java.io.InputStream;
283import java.io.PrintWriter;
284import java.nio.charset.StandardCharsets;
285import java.security.DigestInputStream;
286import java.security.MessageDigest;
287import java.security.NoSuchAlgorithmException;
288import java.security.PublicKey;
289import java.security.cert.Certificate;
290import java.security.cert.CertificateEncodingException;
291import java.security.cert.CertificateException;
292import java.text.SimpleDateFormat;
293import java.util.ArrayList;
294import java.util.Arrays;
295import java.util.Collection;
296import java.util.Collections;
297import java.util.Comparator;
298import java.util.Date;
299import java.util.HashSet;
300import java.util.Iterator;
301import java.util.List;
302import java.util.Map;
303import java.util.Objects;
304import java.util.Set;
305import java.util.concurrent.CountDownLatch;
306import java.util.concurrent.TimeUnit;
307import java.util.concurrent.atomic.AtomicBoolean;
308import java.util.concurrent.atomic.AtomicInteger;
309import java.util.concurrent.atomic.AtomicLong;
310
311/**
312 * Keep track of all those APKs everywhere.
313 * <p>
314 * Internally there are two important locks:
315 * <ul>
316 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
317 * and other related state. It is a fine-grained lock that should only be held
318 * momentarily, as it's one of the most contended locks in the system.
319 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
320 * operations typically involve heavy lifting of application data on disk. Since
321 * {@code installd} is single-threaded, and it's operations can often be slow,
322 * this lock should never be acquired while already holding {@link #mPackages}.
323 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
324 * holding {@link #mInstallLock}.
325 * </ul>
326 * Many internal methods rely on the caller to hold the appropriate locks, and
327 * this contract is expressed through method name suffixes:
328 * <ul>
329 * <li>fooLI(): the caller must hold {@link #mInstallLock}
330 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
331 * being modified must be frozen
332 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
333 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
334 * </ul>
335 * <p>
336 * Because this class is very central to the platform's security; please run all
337 * CTS and unit tests whenever making modifications:
338 *
339 * <pre>
340 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
341 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
342 * </pre>
343 */
344public class PackageManagerService extends IPackageManager.Stub {
345    static final String TAG = "PackageManager";
346    static final boolean DEBUG_SETTINGS = false;
347    static final boolean DEBUG_PREFERRED = false;
348    static final boolean DEBUG_UPGRADE = false;
349    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
350    private static final boolean DEBUG_BACKUP = false;
351    private static final boolean DEBUG_INSTALL = false;
352    private static final boolean DEBUG_REMOVE = false;
353    private static final boolean DEBUG_BROADCASTS = false;
354    private static final boolean DEBUG_SHOW_INFO = false;
355    private static final boolean DEBUG_PACKAGE_INFO = false;
356    private static final boolean DEBUG_INTENT_MATCHING = false;
357    private static final boolean DEBUG_PACKAGE_SCANNING = false;
358    private static final boolean DEBUG_VERIFY = false;
359    private static final boolean DEBUG_FILTERS = false;
360
361    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
362    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
363    // user, but by default initialize to this.
364    static final boolean DEBUG_DEXOPT = false;
365
366    private static final boolean DEBUG_ABI_SELECTION = false;
367    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
368    private static final boolean DEBUG_TRIAGED_MISSING = false;
369    private static final boolean DEBUG_APP_DATA = false;
370
371    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
372
373    private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE;
374
375    private static final int RADIO_UID = Process.PHONE_UID;
376    private static final int LOG_UID = Process.LOG_UID;
377    private static final int NFC_UID = Process.NFC_UID;
378    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
379    private static final int SHELL_UID = Process.SHELL_UID;
380
381    // Cap the size of permission trees that 3rd party apps can define
382    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
383
384    // Suffix used during package installation when copying/moving
385    // package apks to install directory.
386    private static final String INSTALL_PACKAGE_SUFFIX = "-";
387
388    static final int SCAN_NO_DEX = 1<<1;
389    static final int SCAN_FORCE_DEX = 1<<2;
390    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
391    static final int SCAN_NEW_INSTALL = 1<<4;
392    static final int SCAN_NO_PATHS = 1<<5;
393    static final int SCAN_UPDATE_TIME = 1<<6;
394    static final int SCAN_DEFER_DEX = 1<<7;
395    static final int SCAN_BOOTING = 1<<8;
396    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
397    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
398    static final int SCAN_REPLACING = 1<<11;
399    static final int SCAN_REQUIRE_KNOWN = 1<<12;
400    static final int SCAN_MOVE = 1<<13;
401    static final int SCAN_INITIAL = 1<<14;
402    static final int SCAN_CHECK_ONLY = 1<<15;
403    static final int SCAN_DONT_KILL_APP = 1<<17;
404    static final int SCAN_IGNORE_FROZEN = 1<<18;
405
406    static final int REMOVE_CHATTY = 1<<16;
407
408    private static final int[] EMPTY_INT_ARRAY = new int[0];
409
410    /**
411     * Timeout (in milliseconds) after which the watchdog should declare that
412     * our handler thread is wedged.  The usual default for such things is one
413     * minute but we sometimes do very lengthy I/O operations on this thread,
414     * such as installing multi-gigabyte applications, so ours needs to be longer.
415     */
416    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
417
418    /**
419     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
420     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
421     * settings entry if available, otherwise we use the hardcoded default.  If it's been
422     * more than this long since the last fstrim, we force one during the boot sequence.
423     *
424     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
425     * one gets run at the next available charging+idle time.  This final mandatory
426     * no-fstrim check kicks in only of the other scheduling criteria is never met.
427     */
428    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
429
430    /**
431     * Whether verification is enabled by default.
432     */
433    private static final boolean DEFAULT_VERIFY_ENABLE = true;
434
435    /**
436     * The default maximum time to wait for the verification agent to return in
437     * milliseconds.
438     */
439    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
440
441    /**
442     * The default response for package verification timeout.
443     *
444     * This can be either PackageManager.VERIFICATION_ALLOW or
445     * PackageManager.VERIFICATION_REJECT.
446     */
447    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
448
449    static final String PLATFORM_PACKAGE_NAME = "android";
450
451    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
452
453    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
454            DEFAULT_CONTAINER_PACKAGE,
455            "com.android.defcontainer.DefaultContainerService");
456
457    private static final String KILL_APP_REASON_GIDS_CHANGED =
458            "permission grant or revoke changed gids";
459
460    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
461            "permissions revoked";
462
463    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
464
465    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
466
467    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
468    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
469
470    /** Permission grant: not grant the permission. */
471    private static final int GRANT_DENIED = 1;
472
473    /** Permission grant: grant the permission as an install permission. */
474    private static final int GRANT_INSTALL = 2;
475
476    /** Permission grant: grant the permission as a runtime one. */
477    private static final int GRANT_RUNTIME = 3;
478
479    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
480    private static final int GRANT_UPGRADE = 4;
481
482    /** Canonical intent used to identify what counts as a "web browser" app */
483    private static final Intent sBrowserIntent;
484    static {
485        sBrowserIntent = new Intent();
486        sBrowserIntent.setAction(Intent.ACTION_VIEW);
487        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
488        sBrowserIntent.setData(Uri.parse("http:"));
489    }
490
491    /**
492     * The set of all protected actions [i.e. those actions for which a high priority
493     * intent filter is disallowed].
494     */
495    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
496    static {
497        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
498        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
499        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
500        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
501    }
502
503    // Compilation reasons.
504    public static final int REASON_FIRST_BOOT = 0;
505    public static final int REASON_BOOT = 1;
506    public static final int REASON_INSTALL = 2;
507    public static final int REASON_BACKGROUND_DEXOPT = 3;
508    public static final int REASON_AB_OTA = 4;
509    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
510    public static final int REASON_SHARED_APK = 6;
511    public static final int REASON_FORCED_DEXOPT = 7;
512    public static final int REASON_CORE_APP = 8;
513
514    public static final int REASON_LAST = REASON_CORE_APP;
515
516    /** Special library name that skips shared libraries check during compilation. */
517    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
518
519    final ServiceThread mHandlerThread;
520
521    final PackageHandler mHandler;
522
523    private final ProcessLoggingHandler mProcessLoggingHandler;
524
525    /**
526     * Messages for {@link #mHandler} that need to wait for system ready before
527     * being dispatched.
528     */
529    private ArrayList<Message> mPostSystemReadyMessages;
530
531    final int mSdkVersion = Build.VERSION.SDK_INT;
532
533    final Context mContext;
534    final boolean mFactoryTest;
535    final boolean mOnlyCore;
536    final DisplayMetrics mMetrics;
537    final int mDefParseFlags;
538    final String[] mSeparateProcesses;
539    final boolean mIsUpgrade;
540    final boolean mIsPreNUpgrade;
541
542    /** The location for ASEC container files on internal storage. */
543    final String mAsecInternalPath;
544
545    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
546    // LOCK HELD.  Can be called with mInstallLock held.
547    @GuardedBy("mInstallLock")
548    final Installer mInstaller;
549
550    /** Directory where installed third-party apps stored */
551    final File mAppInstallDir;
552    final File mEphemeralInstallDir;
553
554    /**
555     * Directory to which applications installed internally have their
556     * 32 bit native libraries copied.
557     */
558    private File mAppLib32InstallDir;
559
560    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
561    // apps.
562    final File mDrmAppPrivateInstallDir;
563
564    // ----------------------------------------------------------------
565
566    // Lock for state used when installing and doing other long running
567    // operations.  Methods that must be called with this lock held have
568    // the suffix "LI".
569    final Object mInstallLock = new Object();
570
571    // ----------------------------------------------------------------
572
573    // Keys are String (package name), values are Package.  This also serves
574    // as the lock for the global state.  Methods that must be called with
575    // this lock held have the prefix "LP".
576    @GuardedBy("mPackages")
577    final ArrayMap<String, PackageParser.Package> mPackages =
578            new ArrayMap<String, PackageParser.Package>();
579
580    final ArrayMap<String, Set<String>> mKnownCodebase =
581            new ArrayMap<String, Set<String>>();
582
583    // Tracks available target package names -> overlay package paths.
584    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
585        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
586
587    /**
588     * Tracks new system packages [received in an OTA] that we expect to
589     * find updated user-installed versions. Keys are package name, values
590     * are package location.
591     */
592    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
593    /**
594     * Tracks high priority intent filters for protected actions. During boot, certain
595     * filter actions are protected and should never be allowed to have a high priority
596     * intent filter for them. However, there is one, and only one exception -- the
597     * setup wizard. It must be able to define a high priority intent filter for these
598     * actions to ensure there are no escapes from the wizard. We need to delay processing
599     * of these during boot as we need to look at all of the system packages in order
600     * to know which component is the setup wizard.
601     */
602    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
603    /**
604     * Whether or not processing protected filters should be deferred.
605     */
606    private boolean mDeferProtectedFilters = true;
607
608    /**
609     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
610     */
611    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
612    /**
613     * Whether or not system app permissions should be promoted from install to runtime.
614     */
615    boolean mPromoteSystemApps;
616
617    @GuardedBy("mPackages")
618    final Settings mSettings;
619
620    /**
621     * Set of package names that are currently "frozen", which means active
622     * surgery is being done on the code/data for that package. The platform
623     * will refuse to launch frozen packages to avoid race conditions.
624     *
625     * @see PackageFreezer
626     */
627    @GuardedBy("mPackages")
628    final ArraySet<String> mFrozenPackages = new ArraySet<>();
629
630    final ProtectedPackages mProtectedPackages;
631
632    boolean mFirstBoot;
633
634    // System configuration read by SystemConfig.
635    final int[] mGlobalGids;
636    final SparseArray<ArraySet<String>> mSystemPermissions;
637    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
638
639    // If mac_permissions.xml was found for seinfo labeling.
640    boolean mFoundPolicyFile;
641
642    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
643
644    public static final class SharedLibraryEntry {
645        public final String path;
646        public final String apk;
647
648        SharedLibraryEntry(String _path, String _apk) {
649            path = _path;
650            apk = _apk;
651        }
652    }
653
654    // Currently known shared libraries.
655    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
656            new ArrayMap<String, SharedLibraryEntry>();
657
658    // All available activities, for your resolving pleasure.
659    final ActivityIntentResolver mActivities =
660            new ActivityIntentResolver();
661
662    // All available receivers, for your resolving pleasure.
663    final ActivityIntentResolver mReceivers =
664            new ActivityIntentResolver();
665
666    // All available services, for your resolving pleasure.
667    final ServiceIntentResolver mServices = new ServiceIntentResolver();
668
669    // All available providers, for your resolving pleasure.
670    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
671
672    // Mapping from provider base names (first directory in content URI codePath)
673    // to the provider information.
674    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
675            new ArrayMap<String, PackageParser.Provider>();
676
677    // Mapping from instrumentation class names to info about them.
678    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
679            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
680
681    // Mapping from permission names to info about them.
682    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
683            new ArrayMap<String, PackageParser.PermissionGroup>();
684
685    // Packages whose data we have transfered into another package, thus
686    // should no longer exist.
687    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
688
689    // Broadcast actions that are only available to the system.
690    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
691
692    /** List of packages waiting for verification. */
693    final SparseArray<PackageVerificationState> mPendingVerification
694            = new SparseArray<PackageVerificationState>();
695
696    /** Set of packages associated with each app op permission. */
697    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
698
699    final PackageInstallerService mInstallerService;
700
701    private final PackageDexOptimizer mPackageDexOptimizer;
702
703    private AtomicInteger mNextMoveId = new AtomicInteger();
704    private final MoveCallbacks mMoveCallbacks;
705
706    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
707
708    // Cache of users who need badging.
709    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
710
711    /** Token for keys in mPendingVerification. */
712    private int mPendingVerificationToken = 0;
713
714    volatile boolean mSystemReady;
715    volatile boolean mSafeMode;
716    volatile boolean mHasSystemUidErrors;
717
718    ApplicationInfo mAndroidApplication;
719    final ActivityInfo mResolveActivity = new ActivityInfo();
720    final ResolveInfo mResolveInfo = new ResolveInfo();
721    ComponentName mResolveComponentName;
722    PackageParser.Package mPlatformPackage;
723    ComponentName mCustomResolverComponentName;
724
725    boolean mResolverReplaced = false;
726
727    private final @Nullable ComponentName mIntentFilterVerifierComponent;
728    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
729
730    private int mIntentFilterVerificationToken = 0;
731
732    /** Component that knows whether or not an ephemeral application exists */
733    final ComponentName mEphemeralResolverComponent;
734    /** The service connection to the ephemeral resolver */
735    final EphemeralResolverConnection mEphemeralResolverConnection;
736
737    /** Component used to install ephemeral applications */
738    final ComponentName mEphemeralInstallerComponent;
739    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
740    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
741
742    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
743            = new SparseArray<IntentFilterVerificationState>();
744
745    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
746            new DefaultPermissionGrantPolicy(this);
747
748    // List of packages names to keep cached, even if they are uninstalled for all users
749    private List<String> mKeepUninstalledPackages;
750
751    private UserManagerInternal mUserManagerInternal;
752
753    private static class IFVerificationParams {
754        PackageParser.Package pkg;
755        boolean replacing;
756        int userId;
757        int verifierUid;
758
759        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
760                int _userId, int _verifierUid) {
761            pkg = _pkg;
762            replacing = _replacing;
763            userId = _userId;
764            replacing = _replacing;
765            verifierUid = _verifierUid;
766        }
767    }
768
769    private interface IntentFilterVerifier<T extends IntentFilter> {
770        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
771                                               T filter, String packageName);
772        void startVerifications(int userId);
773        void receiveVerificationResponse(int verificationId);
774    }
775
776    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
777        private Context mContext;
778        private ComponentName mIntentFilterVerifierComponent;
779        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
780
781        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
782            mContext = context;
783            mIntentFilterVerifierComponent = verifierComponent;
784        }
785
786        private String getDefaultScheme() {
787            return IntentFilter.SCHEME_HTTPS;
788        }
789
790        @Override
791        public void startVerifications(int userId) {
792            // Launch verifications requests
793            int count = mCurrentIntentFilterVerifications.size();
794            for (int n=0; n<count; n++) {
795                int verificationId = mCurrentIntentFilterVerifications.get(n);
796                final IntentFilterVerificationState ivs =
797                        mIntentFilterVerificationStates.get(verificationId);
798
799                String packageName = ivs.getPackageName();
800
801                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
802                final int filterCount = filters.size();
803                ArraySet<String> domainsSet = new ArraySet<>();
804                for (int m=0; m<filterCount; m++) {
805                    PackageParser.ActivityIntentInfo filter = filters.get(m);
806                    domainsSet.addAll(filter.getHostsList());
807                }
808                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
809                synchronized (mPackages) {
810                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
811                            packageName, domainsList) != null) {
812                        scheduleWriteSettingsLocked();
813                    }
814                }
815                sendVerificationRequest(userId, verificationId, ivs);
816            }
817            mCurrentIntentFilterVerifications.clear();
818        }
819
820        private void sendVerificationRequest(int userId, int verificationId,
821                IntentFilterVerificationState ivs) {
822
823            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
824            verificationIntent.putExtra(
825                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
826                    verificationId);
827            verificationIntent.putExtra(
828                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
829                    getDefaultScheme());
830            verificationIntent.putExtra(
831                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
832                    ivs.getHostsString());
833            verificationIntent.putExtra(
834                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
835                    ivs.getPackageName());
836            verificationIntent.setComponent(mIntentFilterVerifierComponent);
837            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
838
839            UserHandle user = new UserHandle(userId);
840            mContext.sendBroadcastAsUser(verificationIntent, user);
841            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
842                    "Sending IntentFilter verification broadcast");
843        }
844
845        public void receiveVerificationResponse(int verificationId) {
846            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
847
848            final boolean verified = ivs.isVerified();
849
850            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
851            final int count = filters.size();
852            if (DEBUG_DOMAIN_VERIFICATION) {
853                Slog.i(TAG, "Received verification response " + verificationId
854                        + " for " + count + " filters, verified=" + verified);
855            }
856            for (int n=0; n<count; n++) {
857                PackageParser.ActivityIntentInfo filter = filters.get(n);
858                filter.setVerified(verified);
859
860                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
861                        + " verified with result:" + verified + " and hosts:"
862                        + ivs.getHostsString());
863            }
864
865            mIntentFilterVerificationStates.remove(verificationId);
866
867            final String packageName = ivs.getPackageName();
868            IntentFilterVerificationInfo ivi = null;
869
870            synchronized (mPackages) {
871                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
872            }
873            if (ivi == null) {
874                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
875                        + verificationId + " packageName:" + packageName);
876                return;
877            }
878            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
879                    "Updating IntentFilterVerificationInfo for package " + packageName
880                            +" verificationId:" + verificationId);
881
882            synchronized (mPackages) {
883                if (verified) {
884                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
885                } else {
886                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
887                }
888                scheduleWriteSettingsLocked();
889
890                final int userId = ivs.getUserId();
891                if (userId != UserHandle.USER_ALL) {
892                    final int userStatus =
893                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
894
895                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
896                    boolean needUpdate = false;
897
898                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
899                    // already been set by the User thru the Disambiguation dialog
900                    switch (userStatus) {
901                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
902                            if (verified) {
903                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
904                            } else {
905                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
906                            }
907                            needUpdate = true;
908                            break;
909
910                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
911                            if (verified) {
912                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
913                                needUpdate = true;
914                            }
915                            break;
916
917                        default:
918                            // Nothing to do
919                    }
920
921                    if (needUpdate) {
922                        mSettings.updateIntentFilterVerificationStatusLPw(
923                                packageName, updatedStatus, userId);
924                        scheduleWritePackageRestrictionsLocked(userId);
925                    }
926                }
927            }
928        }
929
930        @Override
931        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
932                    ActivityIntentInfo filter, String packageName) {
933            if (!hasValidDomains(filter)) {
934                return false;
935            }
936            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
937            if (ivs == null) {
938                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
939                        packageName);
940            }
941            if (DEBUG_DOMAIN_VERIFICATION) {
942                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
943            }
944            ivs.addFilter(filter);
945            return true;
946        }
947
948        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
949                int userId, int verificationId, String packageName) {
950            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
951                    verifierUid, userId, packageName);
952            ivs.setPendingState();
953            synchronized (mPackages) {
954                mIntentFilterVerificationStates.append(verificationId, ivs);
955                mCurrentIntentFilterVerifications.add(verificationId);
956            }
957            return ivs;
958        }
959    }
960
961    private static boolean hasValidDomains(ActivityIntentInfo filter) {
962        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
963                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
964                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
965    }
966
967    // Set of pending broadcasts for aggregating enable/disable of components.
968    static class PendingPackageBroadcasts {
969        // for each user id, a map of <package name -> components within that package>
970        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
971
972        public PendingPackageBroadcasts() {
973            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
974        }
975
976        public ArrayList<String> get(int userId, String packageName) {
977            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
978            return packages.get(packageName);
979        }
980
981        public void put(int userId, String packageName, ArrayList<String> components) {
982            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
983            packages.put(packageName, components);
984        }
985
986        public void remove(int userId, String packageName) {
987            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
988            if (packages != null) {
989                packages.remove(packageName);
990            }
991        }
992
993        public void remove(int userId) {
994            mUidMap.remove(userId);
995        }
996
997        public int userIdCount() {
998            return mUidMap.size();
999        }
1000
1001        public int userIdAt(int n) {
1002            return mUidMap.keyAt(n);
1003        }
1004
1005        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1006            return mUidMap.get(userId);
1007        }
1008
1009        public int size() {
1010            // total number of pending broadcast entries across all userIds
1011            int num = 0;
1012            for (int i = 0; i< mUidMap.size(); i++) {
1013                num += mUidMap.valueAt(i).size();
1014            }
1015            return num;
1016        }
1017
1018        public void clear() {
1019            mUidMap.clear();
1020        }
1021
1022        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1023            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1024            if (map == null) {
1025                map = new ArrayMap<String, ArrayList<String>>();
1026                mUidMap.put(userId, map);
1027            }
1028            return map;
1029        }
1030    }
1031    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1032
1033    // Service Connection to remote media container service to copy
1034    // package uri's from external media onto secure containers
1035    // or internal storage.
1036    private IMediaContainerService mContainerService = null;
1037
1038    static final int SEND_PENDING_BROADCAST = 1;
1039    static final int MCS_BOUND = 3;
1040    static final int END_COPY = 4;
1041    static final int INIT_COPY = 5;
1042    static final int MCS_UNBIND = 6;
1043    static final int START_CLEANING_PACKAGE = 7;
1044    static final int FIND_INSTALL_LOC = 8;
1045    static final int POST_INSTALL = 9;
1046    static final int MCS_RECONNECT = 10;
1047    static final int MCS_GIVE_UP = 11;
1048    static final int UPDATED_MEDIA_STATUS = 12;
1049    static final int WRITE_SETTINGS = 13;
1050    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1051    static final int PACKAGE_VERIFIED = 15;
1052    static final int CHECK_PENDING_VERIFICATION = 16;
1053    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1054    static final int INTENT_FILTER_VERIFIED = 18;
1055    static final int WRITE_PACKAGE_LIST = 19;
1056
1057    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1058
1059    // Delay time in millisecs
1060    static final int BROADCAST_DELAY = 10 * 1000;
1061
1062    static UserManagerService sUserManager;
1063
1064    // Stores a list of users whose package restrictions file needs to be updated
1065    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1066
1067    final private DefaultContainerConnection mDefContainerConn =
1068            new DefaultContainerConnection();
1069    class DefaultContainerConnection implements ServiceConnection {
1070        public void onServiceConnected(ComponentName name, IBinder service) {
1071            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1072            IMediaContainerService imcs =
1073                IMediaContainerService.Stub.asInterface(service);
1074            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1075        }
1076
1077        public void onServiceDisconnected(ComponentName name) {
1078            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1079        }
1080    }
1081
1082    // Recordkeeping of restore-after-install operations that are currently in flight
1083    // between the Package Manager and the Backup Manager
1084    static class PostInstallData {
1085        public InstallArgs args;
1086        public PackageInstalledInfo res;
1087
1088        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1089            args = _a;
1090            res = _r;
1091        }
1092    }
1093
1094    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1095    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1096
1097    // XML tags for backup/restore of various bits of state
1098    private static final String TAG_PREFERRED_BACKUP = "pa";
1099    private static final String TAG_DEFAULT_APPS = "da";
1100    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1101
1102    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1103    private static final String TAG_ALL_GRANTS = "rt-grants";
1104    private static final String TAG_GRANT = "grant";
1105    private static final String ATTR_PACKAGE_NAME = "pkg";
1106
1107    private static final String TAG_PERMISSION = "perm";
1108    private static final String ATTR_PERMISSION_NAME = "name";
1109    private static final String ATTR_IS_GRANTED = "g";
1110    private static final String ATTR_USER_SET = "set";
1111    private static final String ATTR_USER_FIXED = "fixed";
1112    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1113
1114    // System/policy permission grants are not backed up
1115    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1116            FLAG_PERMISSION_POLICY_FIXED
1117            | FLAG_PERMISSION_SYSTEM_FIXED
1118            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1119
1120    // And we back up these user-adjusted states
1121    private static final int USER_RUNTIME_GRANT_MASK =
1122            FLAG_PERMISSION_USER_SET
1123            | FLAG_PERMISSION_USER_FIXED
1124            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1125
1126    final @Nullable String mRequiredVerifierPackage;
1127    final @NonNull String mRequiredInstallerPackage;
1128    final @Nullable String mSetupWizardPackage;
1129    final @NonNull String mServicesSystemSharedLibraryPackageName;
1130    final @NonNull String mSharedSystemSharedLibraryPackageName;
1131
1132    private final PackageUsage mPackageUsage = new PackageUsage();
1133
1134    private class PackageUsage {
1135        private static final int WRITE_INTERVAL
1136            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1137
1138        private final Object mFileLock = new Object();
1139        private final AtomicLong mLastWritten = new AtomicLong(0);
1140        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1141
1142        private boolean mIsHistoricalPackageUsageAvailable = true;
1143
1144        boolean isHistoricalPackageUsageAvailable() {
1145            return mIsHistoricalPackageUsageAvailable;
1146        }
1147
1148        void write(boolean force) {
1149            if (force) {
1150                writeInternal();
1151                return;
1152            }
1153            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1154                && !DEBUG_DEXOPT) {
1155                return;
1156            }
1157            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1158                new Thread("PackageUsage_DiskWriter") {
1159                    @Override
1160                    public void run() {
1161                        try {
1162                            writeInternal();
1163                        } finally {
1164                            mBackgroundWriteRunning.set(false);
1165                        }
1166                    }
1167                }.start();
1168            }
1169        }
1170
1171        private void writeInternal() {
1172            synchronized (mPackages) {
1173                synchronized (mFileLock) {
1174                    AtomicFile file = getFile();
1175                    FileOutputStream f = null;
1176                    try {
1177                        f = file.startWrite();
1178                        BufferedOutputStream out = new BufferedOutputStream(f);
1179                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1180                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1181                        StringBuilder sb = new StringBuilder();
1182
1183                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1184                        sb.append('\n');
1185                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1186
1187                        for (PackageParser.Package pkg : mPackages.values()) {
1188                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1189                                continue;
1190                            }
1191                            sb.setLength(0);
1192                            sb.append(pkg.packageName);
1193                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1194                                sb.append(' ');
1195                                sb.append(usageTimeInMillis);
1196                            }
1197                            sb.append('\n');
1198                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1199                        }
1200                        out.flush();
1201                        file.finishWrite(f);
1202                    } catch (IOException e) {
1203                        if (f != null) {
1204                            file.failWrite(f);
1205                        }
1206                        Log.e(TAG, "Failed to write package usage times", e);
1207                    }
1208                }
1209            }
1210            mLastWritten.set(SystemClock.elapsedRealtime());
1211        }
1212
1213        void readLP() {
1214            synchronized (mFileLock) {
1215                AtomicFile file = getFile();
1216                BufferedInputStream in = null;
1217                try {
1218                    in = new BufferedInputStream(file.openRead());
1219                    StringBuffer sb = new StringBuffer();
1220
1221                    String firstLine = readLine(in, sb);
1222                    if (firstLine == null) {
1223                        // Empty file. Do nothing.
1224                    } else if (USAGE_FILE_MAGIC_VERSION_1.equals(firstLine)) {
1225                        readVersion1LP(in, sb);
1226                    } else {
1227                        readVersion0LP(in, sb, firstLine);
1228                    }
1229                } catch (FileNotFoundException expected) {
1230                    mIsHistoricalPackageUsageAvailable = false;
1231                } catch (IOException e) {
1232                    Log.w(TAG, "Failed to read package usage times", e);
1233                } finally {
1234                    IoUtils.closeQuietly(in);
1235                }
1236            }
1237            mLastWritten.set(SystemClock.elapsedRealtime());
1238        }
1239
1240        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1241                throws IOException {
1242            // Initial version of the file had no version number and stored one
1243            // package-timestamp pair per line.
1244            // Note that the first line has already been read from the InputStream.
1245            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1246                String[] tokens = line.split(" ");
1247                if (tokens.length != 2) {
1248                    throw new IOException("Failed to parse " + line +
1249                            " as package-timestamp pair.");
1250                }
1251
1252                String packageName = tokens[0];
1253                PackageParser.Package pkg = mPackages.get(packageName);
1254                if (pkg == null) {
1255                    continue;
1256                }
1257
1258                long timestamp = parseAsLong(tokens[1]);
1259                for (int reason = 0;
1260                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1261                        reason++) {
1262                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1263                }
1264            }
1265        }
1266
1267        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1268            // Version 1 of the file started with the corresponding version
1269            // number and then stored a package name and eight timestamps per line.
1270            String line;
1271            while ((line = readLine(in, sb)) != null) {
1272                String[] tokens = line.split(" ");
1273                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1274                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1275                }
1276
1277                String packageName = tokens[0];
1278                PackageParser.Package pkg = mPackages.get(packageName);
1279                if (pkg == null) {
1280                    continue;
1281                }
1282
1283                for (int reason = 0;
1284                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1285                        reason++) {
1286                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1287                }
1288            }
1289        }
1290
1291        private long parseAsLong(String token) throws IOException {
1292            try {
1293                return Long.parseLong(token);
1294            } catch (NumberFormatException e) {
1295                throw new IOException("Failed to parse " + token + " as a long.", e);
1296            }
1297        }
1298
1299        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1300            return readToken(in, sb, '\n');
1301        }
1302
1303        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1304                throws IOException {
1305            sb.setLength(0);
1306            while (true) {
1307                int ch = in.read();
1308                if (ch == -1) {
1309                    if (sb.length() == 0) {
1310                        return null;
1311                    }
1312                    throw new IOException("Unexpected EOF");
1313                }
1314                if (ch == endOfToken) {
1315                    return sb.toString();
1316                }
1317                sb.append((char)ch);
1318            }
1319        }
1320
1321        private AtomicFile getFile() {
1322            File dataDir = Environment.getDataDirectory();
1323            File systemDir = new File(dataDir, "system");
1324            File fname = new File(systemDir, "package-usage.list");
1325            return new AtomicFile(fname);
1326        }
1327
1328        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1329        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1330    }
1331
1332    class PackageHandler extends Handler {
1333        private boolean mBound = false;
1334        final ArrayList<HandlerParams> mPendingInstalls =
1335            new ArrayList<HandlerParams>();
1336
1337        private boolean connectToService() {
1338            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1339                    " DefaultContainerService");
1340            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1341            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1342            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1343                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1344                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1345                mBound = true;
1346                return true;
1347            }
1348            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1349            return false;
1350        }
1351
1352        private void disconnectService() {
1353            mContainerService = null;
1354            mBound = false;
1355            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1356            mContext.unbindService(mDefContainerConn);
1357            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1358        }
1359
1360        PackageHandler(Looper looper) {
1361            super(looper);
1362        }
1363
1364        public void handleMessage(Message msg) {
1365            try {
1366                doHandleMessage(msg);
1367            } finally {
1368                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1369            }
1370        }
1371
1372        void doHandleMessage(Message msg) {
1373            switch (msg.what) {
1374                case INIT_COPY: {
1375                    HandlerParams params = (HandlerParams) msg.obj;
1376                    int idx = mPendingInstalls.size();
1377                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1378                    // If a bind was already initiated we dont really
1379                    // need to do anything. The pending install
1380                    // will be processed later on.
1381                    if (!mBound) {
1382                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1383                                System.identityHashCode(mHandler));
1384                        // If this is the only one pending we might
1385                        // have to bind to the service again.
1386                        if (!connectToService()) {
1387                            Slog.e(TAG, "Failed to bind to media container service");
1388                            params.serviceError();
1389                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1390                                    System.identityHashCode(mHandler));
1391                            if (params.traceMethod != null) {
1392                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1393                                        params.traceCookie);
1394                            }
1395                            return;
1396                        } else {
1397                            // Once we bind to the service, the first
1398                            // pending request will be processed.
1399                            mPendingInstalls.add(idx, params);
1400                        }
1401                    } else {
1402                        mPendingInstalls.add(idx, params);
1403                        // Already bound to the service. Just make
1404                        // sure we trigger off processing the first request.
1405                        if (idx == 0) {
1406                            mHandler.sendEmptyMessage(MCS_BOUND);
1407                        }
1408                    }
1409                    break;
1410                }
1411                case MCS_BOUND: {
1412                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1413                    if (msg.obj != null) {
1414                        mContainerService = (IMediaContainerService) msg.obj;
1415                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1416                                System.identityHashCode(mHandler));
1417                    }
1418                    if (mContainerService == null) {
1419                        if (!mBound) {
1420                            // Something seriously wrong since we are not bound and we are not
1421                            // waiting for connection. Bail out.
1422                            Slog.e(TAG, "Cannot bind to media container service");
1423                            for (HandlerParams params : mPendingInstalls) {
1424                                // Indicate service bind error
1425                                params.serviceError();
1426                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1427                                        System.identityHashCode(params));
1428                                if (params.traceMethod != null) {
1429                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1430                                            params.traceMethod, params.traceCookie);
1431                                }
1432                                return;
1433                            }
1434                            mPendingInstalls.clear();
1435                        } else {
1436                            Slog.w(TAG, "Waiting to connect to media container service");
1437                        }
1438                    } else if (mPendingInstalls.size() > 0) {
1439                        HandlerParams params = mPendingInstalls.get(0);
1440                        if (params != null) {
1441                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1442                                    System.identityHashCode(params));
1443                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1444                            if (params.startCopy()) {
1445                                // We are done...  look for more work or to
1446                                // go idle.
1447                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1448                                        "Checking for more work or unbind...");
1449                                // Delete pending install
1450                                if (mPendingInstalls.size() > 0) {
1451                                    mPendingInstalls.remove(0);
1452                                }
1453                                if (mPendingInstalls.size() == 0) {
1454                                    if (mBound) {
1455                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1456                                                "Posting delayed MCS_UNBIND");
1457                                        removeMessages(MCS_UNBIND);
1458                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1459                                        // Unbind after a little delay, to avoid
1460                                        // continual thrashing.
1461                                        sendMessageDelayed(ubmsg, 10000);
1462                                    }
1463                                } else {
1464                                    // There are more pending requests in queue.
1465                                    // Just post MCS_BOUND message to trigger processing
1466                                    // of next pending install.
1467                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1468                                            "Posting MCS_BOUND for next work");
1469                                    mHandler.sendEmptyMessage(MCS_BOUND);
1470                                }
1471                            }
1472                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1473                        }
1474                    } else {
1475                        // Should never happen ideally.
1476                        Slog.w(TAG, "Empty queue");
1477                    }
1478                    break;
1479                }
1480                case MCS_RECONNECT: {
1481                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1482                    if (mPendingInstalls.size() > 0) {
1483                        if (mBound) {
1484                            disconnectService();
1485                        }
1486                        if (!connectToService()) {
1487                            Slog.e(TAG, "Failed to bind to media container service");
1488                            for (HandlerParams params : mPendingInstalls) {
1489                                // Indicate service bind error
1490                                params.serviceError();
1491                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1492                                        System.identityHashCode(params));
1493                            }
1494                            mPendingInstalls.clear();
1495                        }
1496                    }
1497                    break;
1498                }
1499                case MCS_UNBIND: {
1500                    // If there is no actual work left, then time to unbind.
1501                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1502
1503                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1504                        if (mBound) {
1505                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1506
1507                            disconnectService();
1508                        }
1509                    } else if (mPendingInstalls.size() > 0) {
1510                        // There are more pending requests in queue.
1511                        // Just post MCS_BOUND message to trigger processing
1512                        // of next pending install.
1513                        mHandler.sendEmptyMessage(MCS_BOUND);
1514                    }
1515
1516                    break;
1517                }
1518                case MCS_GIVE_UP: {
1519                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1520                    HandlerParams params = mPendingInstalls.remove(0);
1521                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1522                            System.identityHashCode(params));
1523                    break;
1524                }
1525                case SEND_PENDING_BROADCAST: {
1526                    String packages[];
1527                    ArrayList<String> components[];
1528                    int size = 0;
1529                    int uids[];
1530                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1531                    synchronized (mPackages) {
1532                        if (mPendingBroadcasts == null) {
1533                            return;
1534                        }
1535                        size = mPendingBroadcasts.size();
1536                        if (size <= 0) {
1537                            // Nothing to be done. Just return
1538                            return;
1539                        }
1540                        packages = new String[size];
1541                        components = new ArrayList[size];
1542                        uids = new int[size];
1543                        int i = 0;  // filling out the above arrays
1544
1545                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1546                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1547                            Iterator<Map.Entry<String, ArrayList<String>>> it
1548                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1549                                            .entrySet().iterator();
1550                            while (it.hasNext() && i < size) {
1551                                Map.Entry<String, ArrayList<String>> ent = it.next();
1552                                packages[i] = ent.getKey();
1553                                components[i] = ent.getValue();
1554                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1555                                uids[i] = (ps != null)
1556                                        ? UserHandle.getUid(packageUserId, ps.appId)
1557                                        : -1;
1558                                i++;
1559                            }
1560                        }
1561                        size = i;
1562                        mPendingBroadcasts.clear();
1563                    }
1564                    // Send broadcasts
1565                    for (int i = 0; i < size; i++) {
1566                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1567                    }
1568                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1569                    break;
1570                }
1571                case START_CLEANING_PACKAGE: {
1572                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1573                    final String packageName = (String)msg.obj;
1574                    final int userId = msg.arg1;
1575                    final boolean andCode = msg.arg2 != 0;
1576                    synchronized (mPackages) {
1577                        if (userId == UserHandle.USER_ALL) {
1578                            int[] users = sUserManager.getUserIds();
1579                            for (int user : users) {
1580                                mSettings.addPackageToCleanLPw(
1581                                        new PackageCleanItem(user, packageName, andCode));
1582                            }
1583                        } else {
1584                            mSettings.addPackageToCleanLPw(
1585                                    new PackageCleanItem(userId, packageName, andCode));
1586                        }
1587                    }
1588                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1589                    startCleaningPackages();
1590                } break;
1591                case POST_INSTALL: {
1592                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1593
1594                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1595                    final boolean didRestore = (msg.arg2 != 0);
1596                    mRunningInstalls.delete(msg.arg1);
1597
1598                    if (data != null) {
1599                        InstallArgs args = data.args;
1600                        PackageInstalledInfo parentRes = data.res;
1601
1602                        final boolean grantPermissions = (args.installFlags
1603                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1604                        final boolean killApp = (args.installFlags
1605                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1606                        final String[] grantedPermissions = args.installGrantPermissions;
1607
1608                        // Handle the parent package
1609                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1610                                grantedPermissions, didRestore, args.installerPackageName,
1611                                args.observer);
1612
1613                        // Handle the child packages
1614                        final int childCount = (parentRes.addedChildPackages != null)
1615                                ? parentRes.addedChildPackages.size() : 0;
1616                        for (int i = 0; i < childCount; i++) {
1617                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1618                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1619                                    grantedPermissions, false, args.installerPackageName,
1620                                    args.observer);
1621                        }
1622
1623                        // Log tracing if needed
1624                        if (args.traceMethod != null) {
1625                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1626                                    args.traceCookie);
1627                        }
1628                    } else {
1629                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1630                    }
1631
1632                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1633                } break;
1634                case UPDATED_MEDIA_STATUS: {
1635                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1636                    boolean reportStatus = msg.arg1 == 1;
1637                    boolean doGc = msg.arg2 == 1;
1638                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1639                    if (doGc) {
1640                        // Force a gc to clear up stale containers.
1641                        Runtime.getRuntime().gc();
1642                    }
1643                    if (msg.obj != null) {
1644                        @SuppressWarnings("unchecked")
1645                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1646                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1647                        // Unload containers
1648                        unloadAllContainers(args);
1649                    }
1650                    if (reportStatus) {
1651                        try {
1652                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1653                            PackageHelper.getMountService().finishMediaUpdate();
1654                        } catch (RemoteException e) {
1655                            Log.e(TAG, "MountService not running?");
1656                        }
1657                    }
1658                } break;
1659                case WRITE_SETTINGS: {
1660                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1661                    synchronized (mPackages) {
1662                        removeMessages(WRITE_SETTINGS);
1663                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1664                        mSettings.writeLPr();
1665                        mDirtyUsers.clear();
1666                    }
1667                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1668                } break;
1669                case WRITE_PACKAGE_RESTRICTIONS: {
1670                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1671                    synchronized (mPackages) {
1672                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1673                        for (int userId : mDirtyUsers) {
1674                            mSettings.writePackageRestrictionsLPr(userId);
1675                        }
1676                        mDirtyUsers.clear();
1677                    }
1678                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1679                } break;
1680                case WRITE_PACKAGE_LIST: {
1681                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1682                    synchronized (mPackages) {
1683                        removeMessages(WRITE_PACKAGE_LIST);
1684                        mSettings.writePackageListLPr(msg.arg1);
1685                    }
1686                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1687                } break;
1688                case CHECK_PENDING_VERIFICATION: {
1689                    final int verificationId = msg.arg1;
1690                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1691
1692                    if ((state != null) && !state.timeoutExtended()) {
1693                        final InstallArgs args = state.getInstallArgs();
1694                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1695
1696                        Slog.i(TAG, "Verification timed out for " + originUri);
1697                        mPendingVerification.remove(verificationId);
1698
1699                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1700
1701                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1702                            Slog.i(TAG, "Continuing with installation of " + originUri);
1703                            state.setVerifierResponse(Binder.getCallingUid(),
1704                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1705                            broadcastPackageVerified(verificationId, originUri,
1706                                    PackageManager.VERIFICATION_ALLOW,
1707                                    state.getInstallArgs().getUser());
1708                            try {
1709                                ret = args.copyApk(mContainerService, true);
1710                            } catch (RemoteException e) {
1711                                Slog.e(TAG, "Could not contact the ContainerService");
1712                            }
1713                        } else {
1714                            broadcastPackageVerified(verificationId, originUri,
1715                                    PackageManager.VERIFICATION_REJECT,
1716                                    state.getInstallArgs().getUser());
1717                        }
1718
1719                        Trace.asyncTraceEnd(
1720                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1721
1722                        processPendingInstall(args, ret);
1723                        mHandler.sendEmptyMessage(MCS_UNBIND);
1724                    }
1725                    break;
1726                }
1727                case PACKAGE_VERIFIED: {
1728                    final int verificationId = msg.arg1;
1729
1730                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1731                    if (state == null) {
1732                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1733                        break;
1734                    }
1735
1736                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1737
1738                    state.setVerifierResponse(response.callerUid, response.code);
1739
1740                    if (state.isVerificationComplete()) {
1741                        mPendingVerification.remove(verificationId);
1742
1743                        final InstallArgs args = state.getInstallArgs();
1744                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1745
1746                        int ret;
1747                        if (state.isInstallAllowed()) {
1748                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1749                            broadcastPackageVerified(verificationId, originUri,
1750                                    response.code, state.getInstallArgs().getUser());
1751                            try {
1752                                ret = args.copyApk(mContainerService, true);
1753                            } catch (RemoteException e) {
1754                                Slog.e(TAG, "Could not contact the ContainerService");
1755                            }
1756                        } else {
1757                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1758                        }
1759
1760                        Trace.asyncTraceEnd(
1761                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1762
1763                        processPendingInstall(args, ret);
1764                        mHandler.sendEmptyMessage(MCS_UNBIND);
1765                    }
1766
1767                    break;
1768                }
1769                case START_INTENT_FILTER_VERIFICATIONS: {
1770                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1771                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1772                            params.replacing, params.pkg);
1773                    break;
1774                }
1775                case INTENT_FILTER_VERIFIED: {
1776                    final int verificationId = msg.arg1;
1777
1778                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1779                            verificationId);
1780                    if (state == null) {
1781                        Slog.w(TAG, "Invalid IntentFilter verification token "
1782                                + verificationId + " received");
1783                        break;
1784                    }
1785
1786                    final int userId = state.getUserId();
1787
1788                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1789                            "Processing IntentFilter verification with token:"
1790                            + verificationId + " and userId:" + userId);
1791
1792                    final IntentFilterVerificationResponse response =
1793                            (IntentFilterVerificationResponse) msg.obj;
1794
1795                    state.setVerifierResponse(response.callerUid, response.code);
1796
1797                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1798                            "IntentFilter verification with token:" + verificationId
1799                            + " and userId:" + userId
1800                            + " is settings verifier response with response code:"
1801                            + response.code);
1802
1803                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1804                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1805                                + response.getFailedDomainsString());
1806                    }
1807
1808                    if (state.isVerificationComplete()) {
1809                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1810                    } else {
1811                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1812                                "IntentFilter verification with token:" + verificationId
1813                                + " was not said to be complete");
1814                    }
1815
1816                    break;
1817                }
1818            }
1819        }
1820    }
1821
1822    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1823            boolean killApp, String[] grantedPermissions,
1824            boolean launchedForRestore, String installerPackage,
1825            IPackageInstallObserver2 installObserver) {
1826        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1827            // Send the removed broadcasts
1828            if (res.removedInfo != null) {
1829                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1830            }
1831
1832            // Now that we successfully installed the package, grant runtime
1833            // permissions if requested before broadcasting the install.
1834            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1835                    >= Build.VERSION_CODES.M) {
1836                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1837            }
1838
1839            final boolean update = res.removedInfo != null
1840                    && res.removedInfo.removedPackage != null;
1841
1842            // If this is the first time we have child packages for a disabled privileged
1843            // app that had no children, we grant requested runtime permissions to the new
1844            // children if the parent on the system image had them already granted.
1845            if (res.pkg.parentPackage != null) {
1846                synchronized (mPackages) {
1847                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1848                }
1849            }
1850
1851            synchronized (mPackages) {
1852                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1853            }
1854
1855            final String packageName = res.pkg.applicationInfo.packageName;
1856            Bundle extras = new Bundle(1);
1857            extras.putInt(Intent.EXTRA_UID, res.uid);
1858
1859            // Determine the set of users who are adding this package for
1860            // the first time vs. those who are seeing an update.
1861            int[] firstUsers = EMPTY_INT_ARRAY;
1862            int[] updateUsers = EMPTY_INT_ARRAY;
1863            if (res.origUsers == null || res.origUsers.length == 0) {
1864                firstUsers = res.newUsers;
1865            } else {
1866                for (int newUser : res.newUsers) {
1867                    boolean isNew = true;
1868                    for (int origUser : res.origUsers) {
1869                        if (origUser == newUser) {
1870                            isNew = false;
1871                            break;
1872                        }
1873                    }
1874                    if (isNew) {
1875                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1876                    } else {
1877                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1878                    }
1879                }
1880            }
1881
1882            // Send installed broadcasts if the install/update is not ephemeral
1883            if (!isEphemeral(res.pkg)) {
1884                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1885
1886                // Send added for users that see the package for the first time
1887                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1888                        extras, 0 /*flags*/, null /*targetPackage*/,
1889                        null /*finishedReceiver*/, firstUsers);
1890
1891                // Send added for users that don't see the package for the first time
1892                if (update) {
1893                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1894                }
1895                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1896                        extras, 0 /*flags*/, null /*targetPackage*/,
1897                        null /*finishedReceiver*/, updateUsers);
1898
1899                // Send replaced for users that don't see the package for the first time
1900                if (update) {
1901                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1902                            packageName, extras, 0 /*flags*/,
1903                            null /*targetPackage*/, null /*finishedReceiver*/,
1904                            updateUsers);
1905                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1906                            null /*package*/, null /*extras*/, 0 /*flags*/,
1907                            packageName /*targetPackage*/,
1908                            null /*finishedReceiver*/, updateUsers);
1909                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1910                    // First-install and we did a restore, so we're responsible for the
1911                    // first-launch broadcast.
1912                    if (DEBUG_BACKUP) {
1913                        Slog.i(TAG, "Post-restore of " + packageName
1914                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1915                    }
1916                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1917                }
1918
1919                // Send broadcast package appeared if forward locked/external for all users
1920                // treat asec-hosted packages like removable media on upgrade
1921                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1922                    if (DEBUG_INSTALL) {
1923                        Slog.i(TAG, "upgrading pkg " + res.pkg
1924                                + " is ASEC-hosted -> AVAILABLE");
1925                    }
1926                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1927                    ArrayList<String> pkgList = new ArrayList<>(1);
1928                    pkgList.add(packageName);
1929                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1930                }
1931            }
1932
1933            // Work that needs to happen on first install within each user
1934            if (firstUsers != null && firstUsers.length > 0) {
1935                synchronized (mPackages) {
1936                    for (int userId : firstUsers) {
1937                        // If this app is a browser and it's newly-installed for some
1938                        // users, clear any default-browser state in those users. The
1939                        // app's nature doesn't depend on the user, so we can just check
1940                        // its browser nature in any user and generalize.
1941                        if (packageIsBrowser(packageName, userId)) {
1942                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1943                        }
1944
1945                        // We may also need to apply pending (restored) runtime
1946                        // permission grants within these users.
1947                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1948                    }
1949                }
1950            }
1951
1952            // Log current value of "unknown sources" setting
1953            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1954                    getUnknownSourcesSettings());
1955
1956            // Force a gc to clear up things
1957            Runtime.getRuntime().gc();
1958
1959            // Remove the replaced package's older resources safely now
1960            // We delete after a gc for applications  on sdcard.
1961            if (res.removedInfo != null && res.removedInfo.args != null) {
1962                synchronized (mInstallLock) {
1963                    res.removedInfo.args.doPostDeleteLI(true);
1964                }
1965            }
1966        }
1967
1968        // If someone is watching installs - notify them
1969        if (installObserver != null) {
1970            try {
1971                Bundle extras = extrasForInstallResult(res);
1972                installObserver.onPackageInstalled(res.name, res.returnCode,
1973                        res.returnMsg, extras);
1974            } catch (RemoteException e) {
1975                Slog.i(TAG, "Observer no longer exists.");
1976            }
1977        }
1978    }
1979
1980    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1981            PackageParser.Package pkg) {
1982        if (pkg.parentPackage == null) {
1983            return;
1984        }
1985        if (pkg.requestedPermissions == null) {
1986            return;
1987        }
1988        final PackageSetting disabledSysParentPs = mSettings
1989                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1990        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1991                || !disabledSysParentPs.isPrivileged()
1992                || (disabledSysParentPs.childPackageNames != null
1993                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1994            return;
1995        }
1996        final int[] allUserIds = sUserManager.getUserIds();
1997        final int permCount = pkg.requestedPermissions.size();
1998        for (int i = 0; i < permCount; i++) {
1999            String permission = pkg.requestedPermissions.get(i);
2000            BasePermission bp = mSettings.mPermissions.get(permission);
2001            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2002                continue;
2003            }
2004            for (int userId : allUserIds) {
2005                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2006                        permission, userId)) {
2007                    grantRuntimePermission(pkg.packageName, permission, userId);
2008                }
2009            }
2010        }
2011    }
2012
2013    private StorageEventListener mStorageListener = new StorageEventListener() {
2014        @Override
2015        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2016            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2017                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2018                    final String volumeUuid = vol.getFsUuid();
2019
2020                    // Clean up any users or apps that were removed or recreated
2021                    // while this volume was missing
2022                    reconcileUsers(volumeUuid);
2023                    reconcileApps(volumeUuid);
2024
2025                    // Clean up any install sessions that expired or were
2026                    // cancelled while this volume was missing
2027                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2028
2029                    loadPrivatePackages(vol);
2030
2031                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2032                    unloadPrivatePackages(vol);
2033                }
2034            }
2035
2036            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2037                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2038                    updateExternalMediaStatus(true, false);
2039                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2040                    updateExternalMediaStatus(false, false);
2041                }
2042            }
2043        }
2044
2045        @Override
2046        public void onVolumeForgotten(String fsUuid) {
2047            if (TextUtils.isEmpty(fsUuid)) {
2048                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2049                return;
2050            }
2051
2052            // Remove any apps installed on the forgotten volume
2053            synchronized (mPackages) {
2054                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2055                for (PackageSetting ps : packages) {
2056                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2057                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2058                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2059                }
2060
2061                mSettings.onVolumeForgotten(fsUuid);
2062                mSettings.writeLPr();
2063            }
2064        }
2065    };
2066
2067    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2068            String[] grantedPermissions) {
2069        for (int userId : userIds) {
2070            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2071        }
2072
2073        // We could have touched GID membership, so flush out packages.list
2074        synchronized (mPackages) {
2075            mSettings.writePackageListLPr();
2076        }
2077    }
2078
2079    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2080            String[] grantedPermissions) {
2081        SettingBase sb = (SettingBase) pkg.mExtras;
2082        if (sb == null) {
2083            return;
2084        }
2085
2086        PermissionsState permissionsState = sb.getPermissionsState();
2087
2088        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2089                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2090
2091        for (String permission : pkg.requestedPermissions) {
2092            final BasePermission bp;
2093            synchronized (mPackages) {
2094                bp = mSettings.mPermissions.get(permission);
2095            }
2096            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2097                    && (grantedPermissions == null
2098                           || ArrayUtils.contains(grantedPermissions, permission))) {
2099                final int flags = permissionsState.getPermissionFlags(permission, userId);
2100                // Installer cannot change immutable permissions.
2101                if ((flags & immutableFlags) == 0) {
2102                    grantRuntimePermission(pkg.packageName, permission, userId);
2103                }
2104            }
2105        }
2106    }
2107
2108    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2109        Bundle extras = null;
2110        switch (res.returnCode) {
2111            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2112                extras = new Bundle();
2113                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2114                        res.origPermission);
2115                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2116                        res.origPackage);
2117                break;
2118            }
2119            case PackageManager.INSTALL_SUCCEEDED: {
2120                extras = new Bundle();
2121                extras.putBoolean(Intent.EXTRA_REPLACING,
2122                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2123                break;
2124            }
2125        }
2126        return extras;
2127    }
2128
2129    void scheduleWriteSettingsLocked() {
2130        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2131            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2132        }
2133    }
2134
2135    void scheduleWritePackageListLocked(int userId) {
2136        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2137            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2138            msg.arg1 = userId;
2139            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2140        }
2141    }
2142
2143    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2144        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2145        scheduleWritePackageRestrictionsLocked(userId);
2146    }
2147
2148    void scheduleWritePackageRestrictionsLocked(int userId) {
2149        final int[] userIds = (userId == UserHandle.USER_ALL)
2150                ? sUserManager.getUserIds() : new int[]{userId};
2151        for (int nextUserId : userIds) {
2152            if (!sUserManager.exists(nextUserId)) return;
2153            mDirtyUsers.add(nextUserId);
2154            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2155                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2156            }
2157        }
2158    }
2159
2160    public static PackageManagerService main(Context context, Installer installer,
2161            boolean factoryTest, boolean onlyCore) {
2162        // Self-check for initial settings.
2163        PackageManagerServiceCompilerMapping.checkProperties();
2164
2165        PackageManagerService m = new PackageManagerService(context, installer,
2166                factoryTest, onlyCore);
2167        m.enableSystemUserPackages();
2168        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2169        // disabled after already being started.
2170        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2171                UserHandle.USER_SYSTEM);
2172        ServiceManager.addService("package", m);
2173        return m;
2174    }
2175
2176    private void enableSystemUserPackages() {
2177        if (!UserManager.isSplitSystemUser()) {
2178            return;
2179        }
2180        // For system user, enable apps based on the following conditions:
2181        // - app is whitelisted or belong to one of these groups:
2182        //   -- system app which has no launcher icons
2183        //   -- system app which has INTERACT_ACROSS_USERS permission
2184        //   -- system IME app
2185        // - app is not in the blacklist
2186        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2187        Set<String> enableApps = new ArraySet<>();
2188        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2189                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2190                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2191        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2192        enableApps.addAll(wlApps);
2193        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2194                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2195        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2196        enableApps.removeAll(blApps);
2197        Log.i(TAG, "Applications installed for system user: " + enableApps);
2198        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2199                UserHandle.SYSTEM);
2200        final int allAppsSize = allAps.size();
2201        synchronized (mPackages) {
2202            for (int i = 0; i < allAppsSize; i++) {
2203                String pName = allAps.get(i);
2204                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2205                // Should not happen, but we shouldn't be failing if it does
2206                if (pkgSetting == null) {
2207                    continue;
2208                }
2209                boolean install = enableApps.contains(pName);
2210                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2211                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2212                            + " for system user");
2213                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2214                }
2215            }
2216        }
2217    }
2218
2219    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2220        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2221                Context.DISPLAY_SERVICE);
2222        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2223    }
2224
2225    /**
2226     * Requests that files preopted on a secondary system partition be copied to the data partition
2227     * if possible.  Note that the actual copying of the files is accomplished by init for security
2228     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2229     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2230     */
2231    private static void requestCopyPreoptedFiles() {
2232        final int WAIT_TIME_MS = 100;
2233        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2234        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2235            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2236            // We will wait for up to 100 seconds.
2237            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2238            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2239                try {
2240                    Thread.sleep(WAIT_TIME_MS);
2241                } catch (InterruptedException e) {
2242                    // Do nothing
2243                }
2244                if (SystemClock.uptimeMillis() > timeEnd) {
2245                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2246                    Slog.wtf(TAG, "cppreopt did not finish!");
2247                    break;
2248                }
2249            }
2250        }
2251    }
2252
2253    public PackageManagerService(Context context, Installer installer,
2254            boolean factoryTest, boolean onlyCore) {
2255        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2256                SystemClock.uptimeMillis());
2257
2258        if (mSdkVersion <= 0) {
2259            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2260        }
2261
2262        mContext = context;
2263        mFactoryTest = factoryTest;
2264        mOnlyCore = onlyCore;
2265        mMetrics = new DisplayMetrics();
2266        mSettings = new Settings(mPackages);
2267        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2268                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2269        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2270                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2271        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2272                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2273        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2274                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2275        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2276                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2277        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2278                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2279
2280        String separateProcesses = SystemProperties.get("debug.separate_processes");
2281        if (separateProcesses != null && separateProcesses.length() > 0) {
2282            if ("*".equals(separateProcesses)) {
2283                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2284                mSeparateProcesses = null;
2285                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2286            } else {
2287                mDefParseFlags = 0;
2288                mSeparateProcesses = separateProcesses.split(",");
2289                Slog.w(TAG, "Running with debug.separate_processes: "
2290                        + separateProcesses);
2291            }
2292        } else {
2293            mDefParseFlags = 0;
2294            mSeparateProcesses = null;
2295        }
2296
2297        mInstaller = installer;
2298        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2299                "*dexopt*");
2300        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2301
2302        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2303                FgThread.get().getLooper());
2304
2305        getDefaultDisplayMetrics(context, mMetrics);
2306
2307        SystemConfig systemConfig = SystemConfig.getInstance();
2308        mGlobalGids = systemConfig.getGlobalGids();
2309        mSystemPermissions = systemConfig.getSystemPermissions();
2310        mAvailableFeatures = systemConfig.getAvailableFeatures();
2311
2312        mProtectedPackages = new ProtectedPackages(mContext);
2313
2314        synchronized (mInstallLock) {
2315        // writer
2316        synchronized (mPackages) {
2317            mHandlerThread = new ServiceThread(TAG,
2318                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2319            mHandlerThread.start();
2320            mHandler = new PackageHandler(mHandlerThread.getLooper());
2321            mProcessLoggingHandler = new ProcessLoggingHandler();
2322            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2323
2324            File dataDir = Environment.getDataDirectory();
2325            mAppInstallDir = new File(dataDir, "app");
2326            mAppLib32InstallDir = new File(dataDir, "app-lib");
2327            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2328            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2329            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2330
2331            sUserManager = new UserManagerService(context, this, mPackages);
2332
2333            // Propagate permission configuration in to package manager.
2334            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2335                    = systemConfig.getPermissions();
2336            for (int i=0; i<permConfig.size(); i++) {
2337                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2338                BasePermission bp = mSettings.mPermissions.get(perm.name);
2339                if (bp == null) {
2340                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2341                    mSettings.mPermissions.put(perm.name, bp);
2342                }
2343                if (perm.gids != null) {
2344                    bp.setGids(perm.gids, perm.perUser);
2345                }
2346            }
2347
2348            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2349            for (int i=0; i<libConfig.size(); i++) {
2350                mSharedLibraries.put(libConfig.keyAt(i),
2351                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2352            }
2353
2354            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2355
2356            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2357
2358            if (mFirstBoot) {
2359                requestCopyPreoptedFiles();
2360            }
2361
2362            String customResolverActivity = Resources.getSystem().getString(
2363                    R.string.config_customResolverActivity);
2364            if (TextUtils.isEmpty(customResolverActivity)) {
2365                customResolverActivity = null;
2366            } else {
2367                mCustomResolverComponentName = ComponentName.unflattenFromString(
2368                        customResolverActivity);
2369            }
2370
2371            long startTime = SystemClock.uptimeMillis();
2372
2373            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2374                    startTime);
2375
2376            // Set flag to monitor and not change apk file paths when
2377            // scanning install directories.
2378            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2379
2380            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2381            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2382
2383            if (bootClassPath == null) {
2384                Slog.w(TAG, "No BOOTCLASSPATH found!");
2385            }
2386
2387            if (systemServerClassPath == null) {
2388                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2389            }
2390
2391            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2392            final String[] dexCodeInstructionSets =
2393                    getDexCodeInstructionSets(
2394                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2395
2396            /**
2397             * Ensure all external libraries have had dexopt run on them.
2398             */
2399            if (mSharedLibraries.size() > 0) {
2400                // NOTE: For now, we're compiling these system "shared libraries"
2401                // (and framework jars) into all available architectures. It's possible
2402                // to compile them only when we come across an app that uses them (there's
2403                // already logic for that in scanPackageLI) but that adds some complexity.
2404                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2405                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2406                        final String lib = libEntry.path;
2407                        if (lib == null) {
2408                            continue;
2409                        }
2410
2411                        try {
2412                            // Shared libraries do not have profiles so we perform a full
2413                            // AOT compilation (if needed).
2414                            int dexoptNeeded = DexFile.getDexOptNeeded(
2415                                    lib, dexCodeInstructionSet,
2416                                    getCompilerFilterForReason(REASON_SHARED_APK),
2417                                    false /* newProfile */);
2418                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2419                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2420                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2421                                        getCompilerFilterForReason(REASON_SHARED_APK),
2422                                        StorageManager.UUID_PRIVATE_INTERNAL,
2423                                        SKIP_SHARED_LIBRARY_CHECK);
2424                            }
2425                        } catch (FileNotFoundException e) {
2426                            Slog.w(TAG, "Library not found: " + lib);
2427                        } catch (IOException | InstallerException e) {
2428                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2429                                    + e.getMessage());
2430                        }
2431                    }
2432                }
2433            }
2434
2435            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2436
2437            final VersionInfo ver = mSettings.getInternalVersion();
2438            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2439
2440            // when upgrading from pre-M, promote system app permissions from install to runtime
2441            mPromoteSystemApps =
2442                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2443
2444            // When upgrading from pre-N, we need to handle package extraction like first boot,
2445            // as there is no profiling data available.
2446            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2447
2448            // save off the names of pre-existing system packages prior to scanning; we don't
2449            // want to automatically grant runtime permissions for new system apps
2450            if (mPromoteSystemApps) {
2451                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2452                while (pkgSettingIter.hasNext()) {
2453                    PackageSetting ps = pkgSettingIter.next();
2454                    if (isSystemApp(ps)) {
2455                        mExistingSystemPackages.add(ps.name);
2456                    }
2457                }
2458            }
2459
2460            // Collect vendor overlay packages.
2461            // (Do this before scanning any apps.)
2462            // For security and version matching reason, only consider
2463            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2464            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2465            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2466                    | PackageParser.PARSE_IS_SYSTEM
2467                    | PackageParser.PARSE_IS_SYSTEM_DIR
2468                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2469
2470            // Find base frameworks (resource packages without code).
2471            scanDirTracedLI(frameworkDir, mDefParseFlags
2472                    | PackageParser.PARSE_IS_SYSTEM
2473                    | PackageParser.PARSE_IS_SYSTEM_DIR
2474                    | PackageParser.PARSE_IS_PRIVILEGED,
2475                    scanFlags | SCAN_NO_DEX, 0);
2476
2477            // Collected privileged system packages.
2478            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2479            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2480                    | PackageParser.PARSE_IS_SYSTEM
2481                    | PackageParser.PARSE_IS_SYSTEM_DIR
2482                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2483
2484            // Collect ordinary system packages.
2485            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2486            scanDirTracedLI(systemAppDir, mDefParseFlags
2487                    | PackageParser.PARSE_IS_SYSTEM
2488                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2489
2490            // Collect all vendor packages.
2491            File vendorAppDir = new File("/vendor/app");
2492            try {
2493                vendorAppDir = vendorAppDir.getCanonicalFile();
2494            } catch (IOException e) {
2495                // failed to look up canonical path, continue with original one
2496            }
2497            scanDirTracedLI(vendorAppDir, mDefParseFlags
2498                    | PackageParser.PARSE_IS_SYSTEM
2499                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2500
2501            // Collect all OEM packages.
2502            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2503            scanDirTracedLI(oemAppDir, mDefParseFlags
2504                    | PackageParser.PARSE_IS_SYSTEM
2505                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2506
2507            // Prune any system packages that no longer exist.
2508            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2509            if (!mOnlyCore) {
2510                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2511                while (psit.hasNext()) {
2512                    PackageSetting ps = psit.next();
2513
2514                    /*
2515                     * If this is not a system app, it can't be a
2516                     * disable system app.
2517                     */
2518                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2519                        continue;
2520                    }
2521
2522                    /*
2523                     * If the package is scanned, it's not erased.
2524                     */
2525                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2526                    if (scannedPkg != null) {
2527                        /*
2528                         * If the system app is both scanned and in the
2529                         * disabled packages list, then it must have been
2530                         * added via OTA. Remove it from the currently
2531                         * scanned package so the previously user-installed
2532                         * application can be scanned.
2533                         */
2534                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2535                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2536                                    + ps.name + "; removing system app.  Last known codePath="
2537                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2538                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2539                                    + scannedPkg.mVersionCode);
2540                            removePackageLI(scannedPkg, true);
2541                            mExpectingBetter.put(ps.name, ps.codePath);
2542                        }
2543
2544                        continue;
2545                    }
2546
2547                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2548                        psit.remove();
2549                        logCriticalInfo(Log.WARN, "System package " + ps.name
2550                                + " no longer exists; it's data will be wiped");
2551                        // Actual deletion of code and data will be handled by later
2552                        // reconciliation step
2553                    } else {
2554                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2555                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2556                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2557                        }
2558                    }
2559                }
2560            }
2561
2562            //look for any incomplete package installations
2563            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2564            for (int i = 0; i < deletePkgsList.size(); i++) {
2565                // Actual deletion of code and data will be handled by later
2566                // reconciliation step
2567                final String packageName = deletePkgsList.get(i).name;
2568                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2569                synchronized (mPackages) {
2570                    mSettings.removePackageLPw(packageName);
2571                }
2572            }
2573
2574            //delete tmp files
2575            deleteTempPackageFiles();
2576
2577            // Remove any shared userIDs that have no associated packages
2578            mSettings.pruneSharedUsersLPw();
2579
2580            if (!mOnlyCore) {
2581                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2582                        SystemClock.uptimeMillis());
2583                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2584
2585                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2586                        | PackageParser.PARSE_FORWARD_LOCK,
2587                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2588
2589                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2590                        | PackageParser.PARSE_IS_EPHEMERAL,
2591                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2592
2593                /**
2594                 * Remove disable package settings for any updated system
2595                 * apps that were removed via an OTA. If they're not a
2596                 * previously-updated app, remove them completely.
2597                 * Otherwise, just revoke their system-level permissions.
2598                 */
2599                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2600                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2601                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2602
2603                    String msg;
2604                    if (deletedPkg == null) {
2605                        msg = "Updated system package " + deletedAppName
2606                                + " no longer exists; it's data will be wiped";
2607                        // Actual deletion of code and data will be handled by later
2608                        // reconciliation step
2609                    } else {
2610                        msg = "Updated system app + " + deletedAppName
2611                                + " no longer present; removing system privileges for "
2612                                + deletedAppName;
2613
2614                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2615
2616                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2617                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2618                    }
2619                    logCriticalInfo(Log.WARN, msg);
2620                }
2621
2622                /**
2623                 * Make sure all system apps that we expected to appear on
2624                 * the userdata partition actually showed up. If they never
2625                 * appeared, crawl back and revive the system version.
2626                 */
2627                for (int i = 0; i < mExpectingBetter.size(); i++) {
2628                    final String packageName = mExpectingBetter.keyAt(i);
2629                    if (!mPackages.containsKey(packageName)) {
2630                        final File scanFile = mExpectingBetter.valueAt(i);
2631
2632                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2633                                + " but never showed up; reverting to system");
2634
2635                        int reparseFlags = mDefParseFlags;
2636                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2637                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2638                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2639                                    | PackageParser.PARSE_IS_PRIVILEGED;
2640                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2641                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2642                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2643                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2644                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2645                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2646                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2647                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2648                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2649                        } else {
2650                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2651                            continue;
2652                        }
2653
2654                        mSettings.enableSystemPackageLPw(packageName);
2655
2656                        try {
2657                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2658                        } catch (PackageManagerException e) {
2659                            Slog.e(TAG, "Failed to parse original system package: "
2660                                    + e.getMessage());
2661                        }
2662                    }
2663                }
2664            }
2665            mExpectingBetter.clear();
2666
2667            // Resolve protected action filters. Only the setup wizard is allowed to
2668            // have a high priority filter for these actions.
2669            mSetupWizardPackage = getSetupWizardPackageName();
2670            if (mProtectedFilters.size() > 0) {
2671                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2672                    Slog.i(TAG, "No setup wizard;"
2673                        + " All protected intents capped to priority 0");
2674                }
2675                for (ActivityIntentInfo filter : mProtectedFilters) {
2676                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2677                        if (DEBUG_FILTERS) {
2678                            Slog.i(TAG, "Found setup wizard;"
2679                                + " allow priority " + filter.getPriority() + ";"
2680                                + " package: " + filter.activity.info.packageName
2681                                + " activity: " + filter.activity.className
2682                                + " priority: " + filter.getPriority());
2683                        }
2684                        // skip setup wizard; allow it to keep the high priority filter
2685                        continue;
2686                    }
2687                    Slog.w(TAG, "Protected action; cap priority to 0;"
2688                            + " package: " + filter.activity.info.packageName
2689                            + " activity: " + filter.activity.className
2690                            + " origPrio: " + filter.getPriority());
2691                    filter.setPriority(0);
2692                }
2693            }
2694            mDeferProtectedFilters = false;
2695            mProtectedFilters.clear();
2696
2697            // Now that we know all of the shared libraries, update all clients to have
2698            // the correct library paths.
2699            updateAllSharedLibrariesLPw();
2700
2701            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2702                // NOTE: We ignore potential failures here during a system scan (like
2703                // the rest of the commands above) because there's precious little we
2704                // can do about it. A settings error is reported, though.
2705                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2706                        false /* boot complete */);
2707            }
2708
2709            // Now that we know all the packages we are keeping,
2710            // read and update their last usage times.
2711            mPackageUsage.readLP();
2712
2713            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2714                    SystemClock.uptimeMillis());
2715            Slog.i(TAG, "Time to scan packages: "
2716                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2717                    + " seconds");
2718
2719            // If the platform SDK has changed since the last time we booted,
2720            // we need to re-grant app permission to catch any new ones that
2721            // appear.  This is really a hack, and means that apps can in some
2722            // cases get permissions that the user didn't initially explicitly
2723            // allow...  it would be nice to have some better way to handle
2724            // this situation.
2725            int updateFlags = UPDATE_PERMISSIONS_ALL;
2726            if (ver.sdkVersion != mSdkVersion) {
2727                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2728                        + mSdkVersion + "; regranting permissions for internal storage");
2729                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2730            }
2731            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2732            ver.sdkVersion = mSdkVersion;
2733
2734            // If this is the first boot or an update from pre-M, and it is a normal
2735            // boot, then we need to initialize the default preferred apps across
2736            // all defined users.
2737            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2738                for (UserInfo user : sUserManager.getUsers(true)) {
2739                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2740                    applyFactoryDefaultBrowserLPw(user.id);
2741                    primeDomainVerificationsLPw(user.id);
2742                }
2743            }
2744
2745            // Prepare storage for system user really early during boot,
2746            // since core system apps like SettingsProvider and SystemUI
2747            // can't wait for user to start
2748            final int storageFlags;
2749            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2750                storageFlags = StorageManager.FLAG_STORAGE_DE;
2751            } else {
2752                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2753            }
2754            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2755                    storageFlags);
2756
2757            // If this is first boot after an OTA, and a normal boot, then
2758            // we need to clear code cache directories.
2759            // Note that we do *not* clear the application profiles. These remain valid
2760            // across OTAs and are used to drive profile verification (post OTA) and
2761            // profile compilation (without waiting to collect a fresh set of profiles).
2762            if (mIsUpgrade && !onlyCore) {
2763                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2764                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2765                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2766                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2767                        // No apps are running this early, so no need to freeze
2768                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2769                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2770                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2771                    }
2772                }
2773                ver.fingerprint = Build.FINGERPRINT;
2774            }
2775
2776            checkDefaultBrowser();
2777
2778            // clear only after permissions and other defaults have been updated
2779            mExistingSystemPackages.clear();
2780            mPromoteSystemApps = false;
2781
2782            // All the changes are done during package scanning.
2783            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2784
2785            // can downgrade to reader
2786            mSettings.writeLPr();
2787
2788            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2789            // early on (before the package manager declares itself as early) because other
2790            // components in the system server might ask for package contexts for these apps.
2791            //
2792            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2793            // (i.e, that the data partition is unavailable).
2794            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2795                long start = System.nanoTime();
2796                List<PackageParser.Package> coreApps = new ArrayList<>();
2797                for (PackageParser.Package pkg : mPackages.values()) {
2798                    if (pkg.coreApp) {
2799                        coreApps.add(pkg);
2800                    }
2801                }
2802
2803                int[] stats = performDexOpt(coreApps, false,
2804                        getCompilerFilterForReason(REASON_CORE_APP));
2805
2806                final int elapsedTimeSeconds =
2807                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2808                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2809
2810                if (DEBUG_DEXOPT) {
2811                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2812                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2813                }
2814
2815
2816                // TODO: Should we log these stats to tron too ?
2817                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2818                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2819                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2820                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2821            }
2822
2823            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2824                    SystemClock.uptimeMillis());
2825
2826            if (!mOnlyCore) {
2827                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2828                mRequiredInstallerPackage = getRequiredInstallerLPr();
2829                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2830                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2831                        mIntentFilterVerifierComponent);
2832                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2833                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2834                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2835                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2836            } else {
2837                mRequiredVerifierPackage = null;
2838                mRequiredInstallerPackage = null;
2839                mIntentFilterVerifierComponent = null;
2840                mIntentFilterVerifier = null;
2841                mServicesSystemSharedLibraryPackageName = null;
2842                mSharedSystemSharedLibraryPackageName = null;
2843            }
2844
2845            mInstallerService = new PackageInstallerService(context, this);
2846
2847            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2848            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2849            // both the installer and resolver must be present to enable ephemeral
2850            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2851                if (DEBUG_EPHEMERAL) {
2852                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2853                            + " installer:" + ephemeralInstallerComponent);
2854                }
2855                mEphemeralResolverComponent = ephemeralResolverComponent;
2856                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2857                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2858                mEphemeralResolverConnection =
2859                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2860            } else {
2861                if (DEBUG_EPHEMERAL) {
2862                    final String missingComponent =
2863                            (ephemeralResolverComponent == null)
2864                            ? (ephemeralInstallerComponent == null)
2865                                    ? "resolver and installer"
2866                                    : "resolver"
2867                            : "installer";
2868                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2869                }
2870                mEphemeralResolverComponent = null;
2871                mEphemeralInstallerComponent = null;
2872                mEphemeralResolverConnection = null;
2873            }
2874
2875            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2876        } // synchronized (mPackages)
2877        } // synchronized (mInstallLock)
2878
2879        // Now after opening every single application zip, make sure they
2880        // are all flushed.  Not really needed, but keeps things nice and
2881        // tidy.
2882        Runtime.getRuntime().gc();
2883
2884        // The initial scanning above does many calls into installd while
2885        // holding the mPackages lock, but we're mostly interested in yelling
2886        // once we have a booted system.
2887        mInstaller.setWarnIfHeld(mPackages);
2888
2889        // Expose private service for system components to use.
2890        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2891    }
2892
2893    @Override
2894    public boolean isFirstBoot() {
2895        return mFirstBoot;
2896    }
2897
2898    @Override
2899    public boolean isOnlyCoreApps() {
2900        return mOnlyCore;
2901    }
2902
2903    @Override
2904    public boolean isUpgrade() {
2905        return mIsUpgrade;
2906    }
2907
2908    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2909        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2910
2911        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2912                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2913                UserHandle.USER_SYSTEM);
2914        if (matches.size() == 1) {
2915            return matches.get(0).getComponentInfo().packageName;
2916        } else {
2917            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2918            return null;
2919        }
2920    }
2921
2922    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2923        synchronized (mPackages) {
2924            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2925            if (libraryEntry == null) {
2926                throw new IllegalStateException("Missing required shared library:" + libraryName);
2927            }
2928            return libraryEntry.apk;
2929        }
2930    }
2931
2932    private @NonNull String getRequiredInstallerLPr() {
2933        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2934        intent.addCategory(Intent.CATEGORY_DEFAULT);
2935        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2936
2937        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2938                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2939                UserHandle.USER_SYSTEM);
2940        if (matches.size() == 1) {
2941            ResolveInfo resolveInfo = matches.get(0);
2942            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2943                throw new RuntimeException("The installer must be a privileged app");
2944            }
2945            return matches.get(0).getComponentInfo().packageName;
2946        } else {
2947            throw new RuntimeException("There must be exactly one installer; found " + matches);
2948        }
2949    }
2950
2951    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2952        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2953
2954        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2955                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2956                UserHandle.USER_SYSTEM);
2957        ResolveInfo best = null;
2958        final int N = matches.size();
2959        for (int i = 0; i < N; i++) {
2960            final ResolveInfo cur = matches.get(i);
2961            final String packageName = cur.getComponentInfo().packageName;
2962            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2963                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2964                continue;
2965            }
2966
2967            if (best == null || cur.priority > best.priority) {
2968                best = cur;
2969            }
2970        }
2971
2972        if (best != null) {
2973            return best.getComponentInfo().getComponentName();
2974        } else {
2975            throw new RuntimeException("There must be at least one intent filter verifier");
2976        }
2977    }
2978
2979    private @Nullable ComponentName getEphemeralResolverLPr() {
2980        final String[] packageArray =
2981                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2982        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2983            if (DEBUG_EPHEMERAL) {
2984                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2985            }
2986            return null;
2987        }
2988
2989        final int resolveFlags =
2990                MATCH_DIRECT_BOOT_AWARE
2991                | MATCH_DIRECT_BOOT_UNAWARE
2992                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2993        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2994        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2995                resolveFlags, UserHandle.USER_SYSTEM);
2996
2997        final int N = resolvers.size();
2998        if (N == 0) {
2999            if (DEBUG_EPHEMERAL) {
3000                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3001            }
3002            return null;
3003        }
3004
3005        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3006        for (int i = 0; i < N; i++) {
3007            final ResolveInfo info = resolvers.get(i);
3008
3009            if (info.serviceInfo == null) {
3010                continue;
3011            }
3012
3013            final String packageName = info.serviceInfo.packageName;
3014            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3015                if (DEBUG_EPHEMERAL) {
3016                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3017                            + " pkg: " + packageName + ", info:" + info);
3018                }
3019                continue;
3020            }
3021
3022            if (DEBUG_EPHEMERAL) {
3023                Slog.v(TAG, "Ephemeral resolver found;"
3024                        + " pkg: " + packageName + ", info:" + info);
3025            }
3026            return new ComponentName(packageName, info.serviceInfo.name);
3027        }
3028        if (DEBUG_EPHEMERAL) {
3029            Slog.v(TAG, "Ephemeral resolver NOT found");
3030        }
3031        return null;
3032    }
3033
3034    private @Nullable ComponentName getEphemeralInstallerLPr() {
3035        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3036        intent.addCategory(Intent.CATEGORY_DEFAULT);
3037        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3038
3039        final int resolveFlags =
3040                MATCH_DIRECT_BOOT_AWARE
3041                | MATCH_DIRECT_BOOT_UNAWARE
3042                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3043        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3044                resolveFlags, UserHandle.USER_SYSTEM);
3045        if (matches.size() == 0) {
3046            return null;
3047        } else if (matches.size() == 1) {
3048            return matches.get(0).getComponentInfo().getComponentName();
3049        } else {
3050            throw new RuntimeException(
3051                    "There must be at most one ephemeral installer; found " + matches);
3052        }
3053    }
3054
3055    private void primeDomainVerificationsLPw(int userId) {
3056        if (DEBUG_DOMAIN_VERIFICATION) {
3057            Slog.d(TAG, "Priming domain verifications in user " + userId);
3058        }
3059
3060        SystemConfig systemConfig = SystemConfig.getInstance();
3061        ArraySet<String> packages = systemConfig.getLinkedApps();
3062        ArraySet<String> domains = new ArraySet<String>();
3063
3064        for (String packageName : packages) {
3065            PackageParser.Package pkg = mPackages.get(packageName);
3066            if (pkg != null) {
3067                if (!pkg.isSystemApp()) {
3068                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3069                    continue;
3070                }
3071
3072                domains.clear();
3073                for (PackageParser.Activity a : pkg.activities) {
3074                    for (ActivityIntentInfo filter : a.intents) {
3075                        if (hasValidDomains(filter)) {
3076                            domains.addAll(filter.getHostsList());
3077                        }
3078                    }
3079                }
3080
3081                if (domains.size() > 0) {
3082                    if (DEBUG_DOMAIN_VERIFICATION) {
3083                        Slog.v(TAG, "      + " + packageName);
3084                    }
3085                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3086                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3087                    // and then 'always' in the per-user state actually used for intent resolution.
3088                    final IntentFilterVerificationInfo ivi;
3089                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
3090                            new ArrayList<String>(domains));
3091                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3092                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3093                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3094                } else {
3095                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3096                            + "' does not handle web links");
3097                }
3098            } else {
3099                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3100            }
3101        }
3102
3103        scheduleWritePackageRestrictionsLocked(userId);
3104        scheduleWriteSettingsLocked();
3105    }
3106
3107    private void applyFactoryDefaultBrowserLPw(int userId) {
3108        // The default browser app's package name is stored in a string resource,
3109        // with a product-specific overlay used for vendor customization.
3110        String browserPkg = mContext.getResources().getString(
3111                com.android.internal.R.string.default_browser);
3112        if (!TextUtils.isEmpty(browserPkg)) {
3113            // non-empty string => required to be a known package
3114            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3115            if (ps == null) {
3116                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3117                browserPkg = null;
3118            } else {
3119                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3120            }
3121        }
3122
3123        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3124        // default.  If there's more than one, just leave everything alone.
3125        if (browserPkg == null) {
3126            calculateDefaultBrowserLPw(userId);
3127        }
3128    }
3129
3130    private void calculateDefaultBrowserLPw(int userId) {
3131        List<String> allBrowsers = resolveAllBrowserApps(userId);
3132        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3133        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3134    }
3135
3136    private List<String> resolveAllBrowserApps(int userId) {
3137        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3138        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3139                PackageManager.MATCH_ALL, userId);
3140
3141        final int count = list.size();
3142        List<String> result = new ArrayList<String>(count);
3143        for (int i=0; i<count; i++) {
3144            ResolveInfo info = list.get(i);
3145            if (info.activityInfo == null
3146                    || !info.handleAllWebDataURI
3147                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3148                    || result.contains(info.activityInfo.packageName)) {
3149                continue;
3150            }
3151            result.add(info.activityInfo.packageName);
3152        }
3153
3154        return result;
3155    }
3156
3157    private boolean packageIsBrowser(String packageName, int userId) {
3158        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3159                PackageManager.MATCH_ALL, userId);
3160        final int N = list.size();
3161        for (int i = 0; i < N; i++) {
3162            ResolveInfo info = list.get(i);
3163            if (packageName.equals(info.activityInfo.packageName)) {
3164                return true;
3165            }
3166        }
3167        return false;
3168    }
3169
3170    private void checkDefaultBrowser() {
3171        final int myUserId = UserHandle.myUserId();
3172        final String packageName = getDefaultBrowserPackageName(myUserId);
3173        if (packageName != null) {
3174            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3175            if (info == null) {
3176                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3177                synchronized (mPackages) {
3178                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3179                }
3180            }
3181        }
3182    }
3183
3184    @Override
3185    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3186            throws RemoteException {
3187        try {
3188            return super.onTransact(code, data, reply, flags);
3189        } catch (RuntimeException e) {
3190            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3191                Slog.wtf(TAG, "Package Manager Crash", e);
3192            }
3193            throw e;
3194        }
3195    }
3196
3197    static int[] appendInts(int[] cur, int[] add) {
3198        if (add == null) return cur;
3199        if (cur == null) return add;
3200        final int N = add.length;
3201        for (int i=0; i<N; i++) {
3202            cur = appendInt(cur, add[i]);
3203        }
3204        return cur;
3205    }
3206
3207    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3208        if (!sUserManager.exists(userId)) return null;
3209        if (ps == null) {
3210            return null;
3211        }
3212        final PackageParser.Package p = ps.pkg;
3213        if (p == null) {
3214            return null;
3215        }
3216
3217        final PermissionsState permissionsState = ps.getPermissionsState();
3218
3219        // Compute GIDs only if requested
3220        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3221                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3222        // Compute granted permissions only if package has requested permissions
3223        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3224                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3225        final PackageUserState state = ps.readUserState(userId);
3226
3227        return PackageParser.generatePackageInfo(p, gids, flags,
3228                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3229    }
3230
3231    @Override
3232    public void checkPackageStartable(String packageName, int userId) {
3233        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3234
3235        synchronized (mPackages) {
3236            final PackageSetting ps = mSettings.mPackages.get(packageName);
3237            if (ps == null) {
3238                throw new SecurityException("Package " + packageName + " was not found!");
3239            }
3240
3241            if (!ps.getInstalled(userId)) {
3242                throw new SecurityException(
3243                        "Package " + packageName + " was not installed for user " + userId + "!");
3244            }
3245
3246            if (mSafeMode && !ps.isSystem()) {
3247                throw new SecurityException("Package " + packageName + " not a system app!");
3248            }
3249
3250            if (mFrozenPackages.contains(packageName)) {
3251                throw new SecurityException("Package " + packageName + " is currently frozen!");
3252            }
3253
3254            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3255                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3256                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3257            }
3258        }
3259    }
3260
3261    @Override
3262    public boolean isPackageAvailable(String packageName, int userId) {
3263        if (!sUserManager.exists(userId)) return false;
3264        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3265                false /* requireFullPermission */, false /* checkShell */, "is package available");
3266        synchronized (mPackages) {
3267            PackageParser.Package p = mPackages.get(packageName);
3268            if (p != null) {
3269                final PackageSetting ps = (PackageSetting) p.mExtras;
3270                if (ps != null) {
3271                    final PackageUserState state = ps.readUserState(userId);
3272                    if (state != null) {
3273                        return PackageParser.isAvailable(state);
3274                    }
3275                }
3276            }
3277        }
3278        return false;
3279    }
3280
3281    @Override
3282    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3283        if (!sUserManager.exists(userId)) return null;
3284        flags = updateFlagsForPackage(flags, userId, packageName);
3285        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3286                false /* requireFullPermission */, false /* checkShell */, "get package info");
3287        // reader
3288        synchronized (mPackages) {
3289            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3290            PackageParser.Package p = null;
3291            if (matchFactoryOnly) {
3292                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3293                if (ps != null) {
3294                    return generatePackageInfo(ps, flags, userId);
3295                }
3296            }
3297            if (p == null) {
3298                p = mPackages.get(packageName);
3299                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3300                    return null;
3301                }
3302            }
3303            if (DEBUG_PACKAGE_INFO)
3304                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3305            if (p != null) {
3306                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3307            }
3308            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3309                final PackageSetting ps = mSettings.mPackages.get(packageName);
3310                return generatePackageInfo(ps, flags, userId);
3311            }
3312        }
3313        return null;
3314    }
3315
3316    @Override
3317    public String[] currentToCanonicalPackageNames(String[] names) {
3318        String[] out = new String[names.length];
3319        // reader
3320        synchronized (mPackages) {
3321            for (int i=names.length-1; i>=0; i--) {
3322                PackageSetting ps = mSettings.mPackages.get(names[i]);
3323                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3324            }
3325        }
3326        return out;
3327    }
3328
3329    @Override
3330    public String[] canonicalToCurrentPackageNames(String[] names) {
3331        String[] out = new String[names.length];
3332        // reader
3333        synchronized (mPackages) {
3334            for (int i=names.length-1; i>=0; i--) {
3335                String cur = mSettings.mRenamedPackages.get(names[i]);
3336                out[i] = cur != null ? cur : names[i];
3337            }
3338        }
3339        return out;
3340    }
3341
3342    @Override
3343    public int getPackageUid(String packageName, int flags, int userId) {
3344        if (!sUserManager.exists(userId)) return -1;
3345        flags = updateFlagsForPackage(flags, userId, packageName);
3346        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3347                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3348
3349        // reader
3350        synchronized (mPackages) {
3351            final PackageParser.Package p = mPackages.get(packageName);
3352            if (p != null && p.isMatch(flags)) {
3353                return UserHandle.getUid(userId, p.applicationInfo.uid);
3354            }
3355            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3356                final PackageSetting ps = mSettings.mPackages.get(packageName);
3357                if (ps != null && ps.isMatch(flags)) {
3358                    return UserHandle.getUid(userId, ps.appId);
3359                }
3360            }
3361        }
3362
3363        return -1;
3364    }
3365
3366    @Override
3367    public int[] getPackageGids(String packageName, int flags, int userId) {
3368        if (!sUserManager.exists(userId)) return null;
3369        flags = updateFlagsForPackage(flags, userId, packageName);
3370        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3371                false /* requireFullPermission */, false /* checkShell */,
3372                "getPackageGids");
3373
3374        // reader
3375        synchronized (mPackages) {
3376            final PackageParser.Package p = mPackages.get(packageName);
3377            if (p != null && p.isMatch(flags)) {
3378                PackageSetting ps = (PackageSetting) p.mExtras;
3379                return ps.getPermissionsState().computeGids(userId);
3380            }
3381            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3382                final PackageSetting ps = mSettings.mPackages.get(packageName);
3383                if (ps != null && ps.isMatch(flags)) {
3384                    return ps.getPermissionsState().computeGids(userId);
3385                }
3386            }
3387        }
3388
3389        return null;
3390    }
3391
3392    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3393        if (bp.perm != null) {
3394            return PackageParser.generatePermissionInfo(bp.perm, flags);
3395        }
3396        PermissionInfo pi = new PermissionInfo();
3397        pi.name = bp.name;
3398        pi.packageName = bp.sourcePackage;
3399        pi.nonLocalizedLabel = bp.name;
3400        pi.protectionLevel = bp.protectionLevel;
3401        return pi;
3402    }
3403
3404    @Override
3405    public PermissionInfo getPermissionInfo(String name, int flags) {
3406        // reader
3407        synchronized (mPackages) {
3408            final BasePermission p = mSettings.mPermissions.get(name);
3409            if (p != null) {
3410                return generatePermissionInfo(p, flags);
3411            }
3412            return null;
3413        }
3414    }
3415
3416    @Override
3417    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3418            int flags) {
3419        // reader
3420        synchronized (mPackages) {
3421            if (group != null && !mPermissionGroups.containsKey(group)) {
3422                // This is thrown as NameNotFoundException
3423                return null;
3424            }
3425
3426            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3427            for (BasePermission p : mSettings.mPermissions.values()) {
3428                if (group == null) {
3429                    if (p.perm == null || p.perm.info.group == null) {
3430                        out.add(generatePermissionInfo(p, flags));
3431                    }
3432                } else {
3433                    if (p.perm != null && group.equals(p.perm.info.group)) {
3434                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3435                    }
3436                }
3437            }
3438            return new ParceledListSlice<>(out);
3439        }
3440    }
3441
3442    @Override
3443    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3444        // reader
3445        synchronized (mPackages) {
3446            return PackageParser.generatePermissionGroupInfo(
3447                    mPermissionGroups.get(name), flags);
3448        }
3449    }
3450
3451    @Override
3452    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3453        // reader
3454        synchronized (mPackages) {
3455            final int N = mPermissionGroups.size();
3456            ArrayList<PermissionGroupInfo> out
3457                    = new ArrayList<PermissionGroupInfo>(N);
3458            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3459                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3460            }
3461            return new ParceledListSlice<>(out);
3462        }
3463    }
3464
3465    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3466            int userId) {
3467        if (!sUserManager.exists(userId)) return null;
3468        PackageSetting ps = mSettings.mPackages.get(packageName);
3469        if (ps != null) {
3470            if (ps.pkg == null) {
3471                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3472                if (pInfo != null) {
3473                    return pInfo.applicationInfo;
3474                }
3475                return null;
3476            }
3477            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3478                    ps.readUserState(userId), userId);
3479        }
3480        return null;
3481    }
3482
3483    @Override
3484    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3485        if (!sUserManager.exists(userId)) return null;
3486        flags = updateFlagsForApplication(flags, userId, packageName);
3487        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3488                false /* requireFullPermission */, false /* checkShell */, "get application info");
3489        // writer
3490        synchronized (mPackages) {
3491            PackageParser.Package p = mPackages.get(packageName);
3492            if (DEBUG_PACKAGE_INFO) Log.v(
3493                    TAG, "getApplicationInfo " + packageName
3494                    + ": " + p);
3495            if (p != null) {
3496                PackageSetting ps = mSettings.mPackages.get(packageName);
3497                if (ps == null) return null;
3498                // Note: isEnabledLP() does not apply here - always return info
3499                return PackageParser.generateApplicationInfo(
3500                        p, flags, ps.readUserState(userId), userId);
3501            }
3502            if ("android".equals(packageName)||"system".equals(packageName)) {
3503                return mAndroidApplication;
3504            }
3505            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3506                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3507            }
3508        }
3509        return null;
3510    }
3511
3512    @Override
3513    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3514            final IPackageDataObserver observer) {
3515        mContext.enforceCallingOrSelfPermission(
3516                android.Manifest.permission.CLEAR_APP_CACHE, null);
3517        // Queue up an async operation since clearing cache may take a little while.
3518        mHandler.post(new Runnable() {
3519            public void run() {
3520                mHandler.removeCallbacks(this);
3521                boolean success = true;
3522                synchronized (mInstallLock) {
3523                    try {
3524                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3525                    } catch (InstallerException e) {
3526                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3527                        success = false;
3528                    }
3529                }
3530                if (observer != null) {
3531                    try {
3532                        observer.onRemoveCompleted(null, success);
3533                    } catch (RemoteException e) {
3534                        Slog.w(TAG, "RemoveException when invoking call back");
3535                    }
3536                }
3537            }
3538        });
3539    }
3540
3541    @Override
3542    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3543            final IntentSender pi) {
3544        mContext.enforceCallingOrSelfPermission(
3545                android.Manifest.permission.CLEAR_APP_CACHE, null);
3546        // Queue up an async operation since clearing cache may take a little while.
3547        mHandler.post(new Runnable() {
3548            public void run() {
3549                mHandler.removeCallbacks(this);
3550                boolean success = true;
3551                synchronized (mInstallLock) {
3552                    try {
3553                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3554                    } catch (InstallerException e) {
3555                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3556                        success = false;
3557                    }
3558                }
3559                if(pi != null) {
3560                    try {
3561                        // Callback via pending intent
3562                        int code = success ? 1 : 0;
3563                        pi.sendIntent(null, code, null,
3564                                null, null);
3565                    } catch (SendIntentException e1) {
3566                        Slog.i(TAG, "Failed to send pending intent");
3567                    }
3568                }
3569            }
3570        });
3571    }
3572
3573    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3574        synchronized (mInstallLock) {
3575            try {
3576                mInstaller.freeCache(volumeUuid, freeStorageSize);
3577            } catch (InstallerException e) {
3578                throw new IOException("Failed to free enough space", e);
3579            }
3580        }
3581    }
3582
3583    /**
3584     * Update given flags based on encryption status of current user.
3585     */
3586    private int updateFlags(int flags, int userId) {
3587        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3588                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3589            // Caller expressed an explicit opinion about what encryption
3590            // aware/unaware components they want to see, so fall through and
3591            // give them what they want
3592        } else {
3593            // Caller expressed no opinion, so match based on user state
3594            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3595                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3596            } else {
3597                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3598            }
3599        }
3600        return flags;
3601    }
3602
3603    private UserManagerInternal getUserManagerInternal() {
3604        if (mUserManagerInternal == null) {
3605            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3606        }
3607        return mUserManagerInternal;
3608    }
3609
3610    /**
3611     * Update given flags when being used to request {@link PackageInfo}.
3612     */
3613    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3614        boolean triaged = true;
3615        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3616                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3617            // Caller is asking for component details, so they'd better be
3618            // asking for specific encryption matching behavior, or be triaged
3619            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3620                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3621                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3622                triaged = false;
3623            }
3624        }
3625        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3626                | PackageManager.MATCH_SYSTEM_ONLY
3627                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3628            triaged = false;
3629        }
3630        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3631            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3632                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3633        }
3634        return updateFlags(flags, userId);
3635    }
3636
3637    /**
3638     * Update given flags when being used to request {@link ApplicationInfo}.
3639     */
3640    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3641        return updateFlagsForPackage(flags, userId, cookie);
3642    }
3643
3644    /**
3645     * Update given flags when being used to request {@link ComponentInfo}.
3646     */
3647    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3648        if (cookie instanceof Intent) {
3649            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3650                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3651            }
3652        }
3653
3654        boolean triaged = true;
3655        // Caller is asking for component details, so they'd better be
3656        // asking for specific encryption matching behavior, or be triaged
3657        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3658                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3659                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3660            triaged = false;
3661        }
3662        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3663            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3664                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3665        }
3666
3667        return updateFlags(flags, userId);
3668    }
3669
3670    /**
3671     * Update given flags when being used to request {@link ResolveInfo}.
3672     */
3673    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3674        // Safe mode means we shouldn't match any third-party components
3675        if (mSafeMode) {
3676            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3677        }
3678
3679        return updateFlagsForComponent(flags, userId, cookie);
3680    }
3681
3682    @Override
3683    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3684        if (!sUserManager.exists(userId)) return null;
3685        flags = updateFlagsForComponent(flags, userId, component);
3686        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3687                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3688        synchronized (mPackages) {
3689            PackageParser.Activity a = mActivities.mActivities.get(component);
3690
3691            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3692            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3693                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3694                if (ps == null) return null;
3695                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3696                        userId);
3697            }
3698            if (mResolveComponentName.equals(component)) {
3699                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3700                        new PackageUserState(), userId);
3701            }
3702        }
3703        return null;
3704    }
3705
3706    @Override
3707    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3708            String resolvedType) {
3709        synchronized (mPackages) {
3710            if (component.equals(mResolveComponentName)) {
3711                // The resolver supports EVERYTHING!
3712                return true;
3713            }
3714            PackageParser.Activity a = mActivities.mActivities.get(component);
3715            if (a == null) {
3716                return false;
3717            }
3718            for (int i=0; i<a.intents.size(); i++) {
3719                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3720                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3721                    return true;
3722                }
3723            }
3724            return false;
3725        }
3726    }
3727
3728    @Override
3729    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3730        if (!sUserManager.exists(userId)) return null;
3731        flags = updateFlagsForComponent(flags, userId, component);
3732        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3733                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3734        synchronized (mPackages) {
3735            PackageParser.Activity a = mReceivers.mActivities.get(component);
3736            if (DEBUG_PACKAGE_INFO) Log.v(
3737                TAG, "getReceiverInfo " + component + ": " + a);
3738            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3739                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3740                if (ps == null) return null;
3741                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3742                        userId);
3743            }
3744        }
3745        return null;
3746    }
3747
3748    @Override
3749    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3750        if (!sUserManager.exists(userId)) return null;
3751        flags = updateFlagsForComponent(flags, userId, component);
3752        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3753                false /* requireFullPermission */, false /* checkShell */, "get service info");
3754        synchronized (mPackages) {
3755            PackageParser.Service s = mServices.mServices.get(component);
3756            if (DEBUG_PACKAGE_INFO) Log.v(
3757                TAG, "getServiceInfo " + component + ": " + s);
3758            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3759                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3760                if (ps == null) return null;
3761                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3762                        userId);
3763            }
3764        }
3765        return null;
3766    }
3767
3768    @Override
3769    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3770        if (!sUserManager.exists(userId)) return null;
3771        flags = updateFlagsForComponent(flags, userId, component);
3772        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3773                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3774        synchronized (mPackages) {
3775            PackageParser.Provider p = mProviders.mProviders.get(component);
3776            if (DEBUG_PACKAGE_INFO) Log.v(
3777                TAG, "getProviderInfo " + component + ": " + p);
3778            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3779                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3780                if (ps == null) return null;
3781                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3782                        userId);
3783            }
3784        }
3785        return null;
3786    }
3787
3788    @Override
3789    public String[] getSystemSharedLibraryNames() {
3790        Set<String> libSet;
3791        synchronized (mPackages) {
3792            libSet = mSharedLibraries.keySet();
3793            int size = libSet.size();
3794            if (size > 0) {
3795                String[] libs = new String[size];
3796                libSet.toArray(libs);
3797                return libs;
3798            }
3799        }
3800        return null;
3801    }
3802
3803    @Override
3804    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3805        synchronized (mPackages) {
3806            return mServicesSystemSharedLibraryPackageName;
3807        }
3808    }
3809
3810    @Override
3811    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3812        synchronized (mPackages) {
3813            return mSharedSystemSharedLibraryPackageName;
3814        }
3815    }
3816
3817    @Override
3818    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3819        synchronized (mPackages) {
3820            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3821
3822            final FeatureInfo fi = new FeatureInfo();
3823            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3824                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3825            res.add(fi);
3826
3827            return new ParceledListSlice<>(res);
3828        }
3829    }
3830
3831    @Override
3832    public boolean hasSystemFeature(String name, int version) {
3833        synchronized (mPackages) {
3834            final FeatureInfo feat = mAvailableFeatures.get(name);
3835            if (feat == null) {
3836                return false;
3837            } else {
3838                return feat.version >= version;
3839            }
3840        }
3841    }
3842
3843    @Override
3844    public int checkPermission(String permName, String pkgName, int userId) {
3845        if (!sUserManager.exists(userId)) {
3846            return PackageManager.PERMISSION_DENIED;
3847        }
3848
3849        synchronized (mPackages) {
3850            final PackageParser.Package p = mPackages.get(pkgName);
3851            if (p != null && p.mExtras != null) {
3852                final PackageSetting ps = (PackageSetting) p.mExtras;
3853                final PermissionsState permissionsState = ps.getPermissionsState();
3854                if (permissionsState.hasPermission(permName, userId)) {
3855                    return PackageManager.PERMISSION_GRANTED;
3856                }
3857                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3858                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3859                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3860                    return PackageManager.PERMISSION_GRANTED;
3861                }
3862            }
3863        }
3864
3865        return PackageManager.PERMISSION_DENIED;
3866    }
3867
3868    @Override
3869    public int checkUidPermission(String permName, int uid) {
3870        final int userId = UserHandle.getUserId(uid);
3871
3872        if (!sUserManager.exists(userId)) {
3873            return PackageManager.PERMISSION_DENIED;
3874        }
3875
3876        synchronized (mPackages) {
3877            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3878            if (obj != null) {
3879                final SettingBase ps = (SettingBase) obj;
3880                final PermissionsState permissionsState = ps.getPermissionsState();
3881                if (permissionsState.hasPermission(permName, userId)) {
3882                    return PackageManager.PERMISSION_GRANTED;
3883                }
3884                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3885                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3886                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3887                    return PackageManager.PERMISSION_GRANTED;
3888                }
3889            } else {
3890                ArraySet<String> perms = mSystemPermissions.get(uid);
3891                if (perms != null) {
3892                    if (perms.contains(permName)) {
3893                        return PackageManager.PERMISSION_GRANTED;
3894                    }
3895                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3896                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3897                        return PackageManager.PERMISSION_GRANTED;
3898                    }
3899                }
3900            }
3901        }
3902
3903        return PackageManager.PERMISSION_DENIED;
3904    }
3905
3906    @Override
3907    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3908        if (UserHandle.getCallingUserId() != userId) {
3909            mContext.enforceCallingPermission(
3910                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3911                    "isPermissionRevokedByPolicy for user " + userId);
3912        }
3913
3914        if (checkPermission(permission, packageName, userId)
3915                == PackageManager.PERMISSION_GRANTED) {
3916            return false;
3917        }
3918
3919        final long identity = Binder.clearCallingIdentity();
3920        try {
3921            final int flags = getPermissionFlags(permission, packageName, userId);
3922            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3923        } finally {
3924            Binder.restoreCallingIdentity(identity);
3925        }
3926    }
3927
3928    @Override
3929    public String getPermissionControllerPackageName() {
3930        synchronized (mPackages) {
3931            return mRequiredInstallerPackage;
3932        }
3933    }
3934
3935    /**
3936     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3937     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3938     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3939     * @param message the message to log on security exception
3940     */
3941    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3942            boolean checkShell, String message) {
3943        if (userId < 0) {
3944            throw new IllegalArgumentException("Invalid userId " + userId);
3945        }
3946        if (checkShell) {
3947            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3948        }
3949        if (userId == UserHandle.getUserId(callingUid)) return;
3950        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3951            if (requireFullPermission) {
3952                mContext.enforceCallingOrSelfPermission(
3953                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3954            } else {
3955                try {
3956                    mContext.enforceCallingOrSelfPermission(
3957                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3958                } catch (SecurityException se) {
3959                    mContext.enforceCallingOrSelfPermission(
3960                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3961                }
3962            }
3963        }
3964    }
3965
3966    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3967        if (callingUid == Process.SHELL_UID) {
3968            if (userHandle >= 0
3969                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3970                throw new SecurityException("Shell does not have permission to access user "
3971                        + userHandle);
3972            } else if (userHandle < 0) {
3973                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3974                        + Debug.getCallers(3));
3975            }
3976        }
3977    }
3978
3979    private BasePermission findPermissionTreeLP(String permName) {
3980        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3981            if (permName.startsWith(bp.name) &&
3982                    permName.length() > bp.name.length() &&
3983                    permName.charAt(bp.name.length()) == '.') {
3984                return bp;
3985            }
3986        }
3987        return null;
3988    }
3989
3990    private BasePermission checkPermissionTreeLP(String permName) {
3991        if (permName != null) {
3992            BasePermission bp = findPermissionTreeLP(permName);
3993            if (bp != null) {
3994                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3995                    return bp;
3996                }
3997                throw new SecurityException("Calling uid "
3998                        + Binder.getCallingUid()
3999                        + " is not allowed to add to permission tree "
4000                        + bp.name + " owned by uid " + bp.uid);
4001            }
4002        }
4003        throw new SecurityException("No permission tree found for " + permName);
4004    }
4005
4006    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4007        if (s1 == null) {
4008            return s2 == null;
4009        }
4010        if (s2 == null) {
4011            return false;
4012        }
4013        if (s1.getClass() != s2.getClass()) {
4014            return false;
4015        }
4016        return s1.equals(s2);
4017    }
4018
4019    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4020        if (pi1.icon != pi2.icon) return false;
4021        if (pi1.logo != pi2.logo) return false;
4022        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4023        if (!compareStrings(pi1.name, pi2.name)) return false;
4024        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4025        // We'll take care of setting this one.
4026        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4027        // These are not currently stored in settings.
4028        //if (!compareStrings(pi1.group, pi2.group)) return false;
4029        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4030        //if (pi1.labelRes != pi2.labelRes) return false;
4031        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4032        return true;
4033    }
4034
4035    int permissionInfoFootprint(PermissionInfo info) {
4036        int size = info.name.length();
4037        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4038        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4039        return size;
4040    }
4041
4042    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4043        int size = 0;
4044        for (BasePermission perm : mSettings.mPermissions.values()) {
4045            if (perm.uid == tree.uid) {
4046                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4047            }
4048        }
4049        return size;
4050    }
4051
4052    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4053        // We calculate the max size of permissions defined by this uid and throw
4054        // if that plus the size of 'info' would exceed our stated maximum.
4055        if (tree.uid != Process.SYSTEM_UID) {
4056            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4057            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4058                throw new SecurityException("Permission tree size cap exceeded");
4059            }
4060        }
4061    }
4062
4063    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4064        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4065            throw new SecurityException("Label must be specified in permission");
4066        }
4067        BasePermission tree = checkPermissionTreeLP(info.name);
4068        BasePermission bp = mSettings.mPermissions.get(info.name);
4069        boolean added = bp == null;
4070        boolean changed = true;
4071        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4072        if (added) {
4073            enforcePermissionCapLocked(info, tree);
4074            bp = new BasePermission(info.name, tree.sourcePackage,
4075                    BasePermission.TYPE_DYNAMIC);
4076        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4077            throw new SecurityException(
4078                    "Not allowed to modify non-dynamic permission "
4079                    + info.name);
4080        } else {
4081            if (bp.protectionLevel == fixedLevel
4082                    && bp.perm.owner.equals(tree.perm.owner)
4083                    && bp.uid == tree.uid
4084                    && comparePermissionInfos(bp.perm.info, info)) {
4085                changed = false;
4086            }
4087        }
4088        bp.protectionLevel = fixedLevel;
4089        info = new PermissionInfo(info);
4090        info.protectionLevel = fixedLevel;
4091        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4092        bp.perm.info.packageName = tree.perm.info.packageName;
4093        bp.uid = tree.uid;
4094        if (added) {
4095            mSettings.mPermissions.put(info.name, bp);
4096        }
4097        if (changed) {
4098            if (!async) {
4099                mSettings.writeLPr();
4100            } else {
4101                scheduleWriteSettingsLocked();
4102            }
4103        }
4104        return added;
4105    }
4106
4107    @Override
4108    public boolean addPermission(PermissionInfo info) {
4109        synchronized (mPackages) {
4110            return addPermissionLocked(info, false);
4111        }
4112    }
4113
4114    @Override
4115    public boolean addPermissionAsync(PermissionInfo info) {
4116        synchronized (mPackages) {
4117            return addPermissionLocked(info, true);
4118        }
4119    }
4120
4121    @Override
4122    public void removePermission(String name) {
4123        synchronized (mPackages) {
4124            checkPermissionTreeLP(name);
4125            BasePermission bp = mSettings.mPermissions.get(name);
4126            if (bp != null) {
4127                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4128                    throw new SecurityException(
4129                            "Not allowed to modify non-dynamic permission "
4130                            + name);
4131                }
4132                mSettings.mPermissions.remove(name);
4133                mSettings.writeLPr();
4134            }
4135        }
4136    }
4137
4138    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4139            BasePermission bp) {
4140        int index = pkg.requestedPermissions.indexOf(bp.name);
4141        if (index == -1) {
4142            throw new SecurityException("Package " + pkg.packageName
4143                    + " has not requested permission " + bp.name);
4144        }
4145        if (!bp.isRuntime() && !bp.isDevelopment()) {
4146            throw new SecurityException("Permission " + bp.name
4147                    + " is not a changeable permission type");
4148        }
4149    }
4150
4151    @Override
4152    public void grantRuntimePermission(String packageName, String name, final int userId) {
4153        if (!sUserManager.exists(userId)) {
4154            Log.e(TAG, "No such user:" + userId);
4155            return;
4156        }
4157
4158        mContext.enforceCallingOrSelfPermission(
4159                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4160                "grantRuntimePermission");
4161
4162        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4163                true /* requireFullPermission */, true /* checkShell */,
4164                "grantRuntimePermission");
4165
4166        final int uid;
4167        final SettingBase sb;
4168
4169        synchronized (mPackages) {
4170            final PackageParser.Package pkg = mPackages.get(packageName);
4171            if (pkg == null) {
4172                throw new IllegalArgumentException("Unknown package: " + packageName);
4173            }
4174
4175            final BasePermission bp = mSettings.mPermissions.get(name);
4176            if (bp == null) {
4177                throw new IllegalArgumentException("Unknown permission: " + name);
4178            }
4179
4180            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4181
4182            // If a permission review is required for legacy apps we represent
4183            // their permissions as always granted runtime ones since we need
4184            // to keep the review required permission flag per user while an
4185            // install permission's state is shared across all users.
4186            if (Build.PERMISSIONS_REVIEW_REQUIRED
4187                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4188                    && bp.isRuntime()) {
4189                return;
4190            }
4191
4192            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4193            sb = (SettingBase) pkg.mExtras;
4194            if (sb == null) {
4195                throw new IllegalArgumentException("Unknown package: " + packageName);
4196            }
4197
4198            final PermissionsState permissionsState = sb.getPermissionsState();
4199
4200            final int flags = permissionsState.getPermissionFlags(name, userId);
4201            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4202                throw new SecurityException("Cannot grant system fixed permission "
4203                        + name + " for package " + packageName);
4204            }
4205
4206            if (bp.isDevelopment()) {
4207                // Development permissions must be handled specially, since they are not
4208                // normal runtime permissions.  For now they apply to all users.
4209                if (permissionsState.grantInstallPermission(bp) !=
4210                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4211                    scheduleWriteSettingsLocked();
4212                }
4213                return;
4214            }
4215
4216            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4217                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4218                return;
4219            }
4220
4221            final int result = permissionsState.grantRuntimePermission(bp, userId);
4222            switch (result) {
4223                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4224                    return;
4225                }
4226
4227                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4228                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4229                    mHandler.post(new Runnable() {
4230                        @Override
4231                        public void run() {
4232                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4233                        }
4234                    });
4235                }
4236                break;
4237            }
4238
4239            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4240
4241            // Not critical if that is lost - app has to request again.
4242            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4243        }
4244
4245        // Only need to do this if user is initialized. Otherwise it's a new user
4246        // and there are no processes running as the user yet and there's no need
4247        // to make an expensive call to remount processes for the changed permissions.
4248        if (READ_EXTERNAL_STORAGE.equals(name)
4249                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4250            final long token = Binder.clearCallingIdentity();
4251            try {
4252                if (sUserManager.isInitialized(userId)) {
4253                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4254                            MountServiceInternal.class);
4255                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4256                }
4257            } finally {
4258                Binder.restoreCallingIdentity(token);
4259            }
4260        }
4261    }
4262
4263    @Override
4264    public void revokeRuntimePermission(String packageName, String name, int userId) {
4265        if (!sUserManager.exists(userId)) {
4266            Log.e(TAG, "No such user:" + userId);
4267            return;
4268        }
4269
4270        mContext.enforceCallingOrSelfPermission(
4271                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4272                "revokeRuntimePermission");
4273
4274        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4275                true /* requireFullPermission */, true /* checkShell */,
4276                "revokeRuntimePermission");
4277
4278        final int appId;
4279
4280        synchronized (mPackages) {
4281            final PackageParser.Package pkg = mPackages.get(packageName);
4282            if (pkg == null) {
4283                throw new IllegalArgumentException("Unknown package: " + packageName);
4284            }
4285
4286            final BasePermission bp = mSettings.mPermissions.get(name);
4287            if (bp == null) {
4288                throw new IllegalArgumentException("Unknown permission: " + name);
4289            }
4290
4291            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4292
4293            // If a permission review is required for legacy apps we represent
4294            // their permissions as always granted runtime ones since we need
4295            // to keep the review required permission flag per user while an
4296            // install permission's state is shared across all users.
4297            if (Build.PERMISSIONS_REVIEW_REQUIRED
4298                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4299                    && bp.isRuntime()) {
4300                return;
4301            }
4302
4303            SettingBase sb = (SettingBase) pkg.mExtras;
4304            if (sb == null) {
4305                throw new IllegalArgumentException("Unknown package: " + packageName);
4306            }
4307
4308            final PermissionsState permissionsState = sb.getPermissionsState();
4309
4310            final int flags = permissionsState.getPermissionFlags(name, userId);
4311            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4312                throw new SecurityException("Cannot revoke system fixed permission "
4313                        + name + " for package " + packageName);
4314            }
4315
4316            if (bp.isDevelopment()) {
4317                // Development permissions must be handled specially, since they are not
4318                // normal runtime permissions.  For now they apply to all users.
4319                if (permissionsState.revokeInstallPermission(bp) !=
4320                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4321                    scheduleWriteSettingsLocked();
4322                }
4323                return;
4324            }
4325
4326            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4327                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4328                return;
4329            }
4330
4331            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4332
4333            // Critical, after this call app should never have the permission.
4334            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4335
4336            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4337        }
4338
4339        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4340    }
4341
4342    @Override
4343    public void resetRuntimePermissions() {
4344        mContext.enforceCallingOrSelfPermission(
4345                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4346                "revokeRuntimePermission");
4347
4348        int callingUid = Binder.getCallingUid();
4349        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4350            mContext.enforceCallingOrSelfPermission(
4351                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4352                    "resetRuntimePermissions");
4353        }
4354
4355        synchronized (mPackages) {
4356            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4357            for (int userId : UserManagerService.getInstance().getUserIds()) {
4358                final int packageCount = mPackages.size();
4359                for (int i = 0; i < packageCount; i++) {
4360                    PackageParser.Package pkg = mPackages.valueAt(i);
4361                    if (!(pkg.mExtras instanceof PackageSetting)) {
4362                        continue;
4363                    }
4364                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4365                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4366                }
4367            }
4368        }
4369    }
4370
4371    @Override
4372    public int getPermissionFlags(String name, String packageName, int userId) {
4373        if (!sUserManager.exists(userId)) {
4374            return 0;
4375        }
4376
4377        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4378
4379        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4380                true /* requireFullPermission */, false /* checkShell */,
4381                "getPermissionFlags");
4382
4383        synchronized (mPackages) {
4384            final PackageParser.Package pkg = mPackages.get(packageName);
4385            if (pkg == null) {
4386                return 0;
4387            }
4388
4389            final BasePermission bp = mSettings.mPermissions.get(name);
4390            if (bp == null) {
4391                return 0;
4392            }
4393
4394            SettingBase sb = (SettingBase) pkg.mExtras;
4395            if (sb == null) {
4396                return 0;
4397            }
4398
4399            PermissionsState permissionsState = sb.getPermissionsState();
4400            return permissionsState.getPermissionFlags(name, userId);
4401        }
4402    }
4403
4404    @Override
4405    public void updatePermissionFlags(String name, String packageName, int flagMask,
4406            int flagValues, int userId) {
4407        if (!sUserManager.exists(userId)) {
4408            return;
4409        }
4410
4411        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4412
4413        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4414                true /* requireFullPermission */, true /* checkShell */,
4415                "updatePermissionFlags");
4416
4417        // Only the system can change these flags and nothing else.
4418        if (getCallingUid() != Process.SYSTEM_UID) {
4419            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4420            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4421            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4422            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4423            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4424        }
4425
4426        synchronized (mPackages) {
4427            final PackageParser.Package pkg = mPackages.get(packageName);
4428            if (pkg == null) {
4429                throw new IllegalArgumentException("Unknown package: " + packageName);
4430            }
4431
4432            final BasePermission bp = mSettings.mPermissions.get(name);
4433            if (bp == null) {
4434                throw new IllegalArgumentException("Unknown permission: " + name);
4435            }
4436
4437            SettingBase sb = (SettingBase) pkg.mExtras;
4438            if (sb == null) {
4439                throw new IllegalArgumentException("Unknown package: " + packageName);
4440            }
4441
4442            PermissionsState permissionsState = sb.getPermissionsState();
4443
4444            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4445
4446            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4447                // Install and runtime permissions are stored in different places,
4448                // so figure out what permission changed and persist the change.
4449                if (permissionsState.getInstallPermissionState(name) != null) {
4450                    scheduleWriteSettingsLocked();
4451                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4452                        || hadState) {
4453                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4454                }
4455            }
4456        }
4457    }
4458
4459    /**
4460     * Update the permission flags for all packages and runtime permissions of a user in order
4461     * to allow device or profile owner to remove POLICY_FIXED.
4462     */
4463    @Override
4464    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4465        if (!sUserManager.exists(userId)) {
4466            return;
4467        }
4468
4469        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4470
4471        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4472                true /* requireFullPermission */, true /* checkShell */,
4473                "updatePermissionFlagsForAllApps");
4474
4475        // Only the system can change system fixed flags.
4476        if (getCallingUid() != Process.SYSTEM_UID) {
4477            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4478            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4479        }
4480
4481        synchronized (mPackages) {
4482            boolean changed = false;
4483            final int packageCount = mPackages.size();
4484            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4485                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4486                SettingBase sb = (SettingBase) pkg.mExtras;
4487                if (sb == null) {
4488                    continue;
4489                }
4490                PermissionsState permissionsState = sb.getPermissionsState();
4491                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4492                        userId, flagMask, flagValues);
4493            }
4494            if (changed) {
4495                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4496            }
4497        }
4498    }
4499
4500    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4501        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4502                != PackageManager.PERMISSION_GRANTED
4503            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4504                != PackageManager.PERMISSION_GRANTED) {
4505            throw new SecurityException(message + " requires "
4506                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4507                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4508        }
4509    }
4510
4511    @Override
4512    public boolean shouldShowRequestPermissionRationale(String permissionName,
4513            String packageName, int userId) {
4514        if (UserHandle.getCallingUserId() != userId) {
4515            mContext.enforceCallingPermission(
4516                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4517                    "canShowRequestPermissionRationale for user " + userId);
4518        }
4519
4520        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4521        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4522            return false;
4523        }
4524
4525        if (checkPermission(permissionName, packageName, userId)
4526                == PackageManager.PERMISSION_GRANTED) {
4527            return false;
4528        }
4529
4530        final int flags;
4531
4532        final long identity = Binder.clearCallingIdentity();
4533        try {
4534            flags = getPermissionFlags(permissionName,
4535                    packageName, userId);
4536        } finally {
4537            Binder.restoreCallingIdentity(identity);
4538        }
4539
4540        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4541                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4542                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4543
4544        if ((flags & fixedFlags) != 0) {
4545            return false;
4546        }
4547
4548        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4549    }
4550
4551    @Override
4552    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4553        mContext.enforceCallingOrSelfPermission(
4554                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4555                "addOnPermissionsChangeListener");
4556
4557        synchronized (mPackages) {
4558            mOnPermissionChangeListeners.addListenerLocked(listener);
4559        }
4560    }
4561
4562    @Override
4563    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4564        synchronized (mPackages) {
4565            mOnPermissionChangeListeners.removeListenerLocked(listener);
4566        }
4567    }
4568
4569    @Override
4570    public boolean isProtectedBroadcast(String actionName) {
4571        synchronized (mPackages) {
4572            if (mProtectedBroadcasts.contains(actionName)) {
4573                return true;
4574            } else if (actionName != null) {
4575                // TODO: remove these terrible hacks
4576                if (actionName.startsWith("android.net.netmon.lingerExpired")
4577                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4578                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4579                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4580                    return true;
4581                }
4582            }
4583        }
4584        return false;
4585    }
4586
4587    @Override
4588    public int checkSignatures(String pkg1, String pkg2) {
4589        synchronized (mPackages) {
4590            final PackageParser.Package p1 = mPackages.get(pkg1);
4591            final PackageParser.Package p2 = mPackages.get(pkg2);
4592            if (p1 == null || p1.mExtras == null
4593                    || p2 == null || p2.mExtras == null) {
4594                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4595            }
4596            return compareSignatures(p1.mSignatures, p2.mSignatures);
4597        }
4598    }
4599
4600    @Override
4601    public int checkUidSignatures(int uid1, int uid2) {
4602        // Map to base uids.
4603        uid1 = UserHandle.getAppId(uid1);
4604        uid2 = UserHandle.getAppId(uid2);
4605        // reader
4606        synchronized (mPackages) {
4607            Signature[] s1;
4608            Signature[] s2;
4609            Object obj = mSettings.getUserIdLPr(uid1);
4610            if (obj != null) {
4611                if (obj instanceof SharedUserSetting) {
4612                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4613                } else if (obj instanceof PackageSetting) {
4614                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4615                } else {
4616                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4617                }
4618            } else {
4619                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4620            }
4621            obj = mSettings.getUserIdLPr(uid2);
4622            if (obj != null) {
4623                if (obj instanceof SharedUserSetting) {
4624                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4625                } else if (obj instanceof PackageSetting) {
4626                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4627                } else {
4628                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4629                }
4630            } else {
4631                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4632            }
4633            return compareSignatures(s1, s2);
4634        }
4635    }
4636
4637    /**
4638     * This method should typically only be used when granting or revoking
4639     * permissions, since the app may immediately restart after this call.
4640     * <p>
4641     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4642     * guard your work against the app being relaunched.
4643     */
4644    private void killUid(int appId, int userId, String reason) {
4645        final long identity = Binder.clearCallingIdentity();
4646        try {
4647            IActivityManager am = ActivityManagerNative.getDefault();
4648            if (am != null) {
4649                try {
4650                    am.killUid(appId, userId, reason);
4651                } catch (RemoteException e) {
4652                    /* ignore - same process */
4653                }
4654            }
4655        } finally {
4656            Binder.restoreCallingIdentity(identity);
4657        }
4658    }
4659
4660    /**
4661     * Compares two sets of signatures. Returns:
4662     * <br />
4663     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4664     * <br />
4665     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4666     * <br />
4667     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4668     * <br />
4669     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4670     * <br />
4671     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4672     */
4673    static int compareSignatures(Signature[] s1, Signature[] s2) {
4674        if (s1 == null) {
4675            return s2 == null
4676                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4677                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4678        }
4679
4680        if (s2 == null) {
4681            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4682        }
4683
4684        if (s1.length != s2.length) {
4685            return PackageManager.SIGNATURE_NO_MATCH;
4686        }
4687
4688        // Since both signature sets are of size 1, we can compare without HashSets.
4689        if (s1.length == 1) {
4690            return s1[0].equals(s2[0]) ?
4691                    PackageManager.SIGNATURE_MATCH :
4692                    PackageManager.SIGNATURE_NO_MATCH;
4693        }
4694
4695        ArraySet<Signature> set1 = new ArraySet<Signature>();
4696        for (Signature sig : s1) {
4697            set1.add(sig);
4698        }
4699        ArraySet<Signature> set2 = new ArraySet<Signature>();
4700        for (Signature sig : s2) {
4701            set2.add(sig);
4702        }
4703        // Make sure s2 contains all signatures in s1.
4704        if (set1.equals(set2)) {
4705            return PackageManager.SIGNATURE_MATCH;
4706        }
4707        return PackageManager.SIGNATURE_NO_MATCH;
4708    }
4709
4710    /**
4711     * If the database version for this type of package (internal storage or
4712     * external storage) is less than the version where package signatures
4713     * were updated, return true.
4714     */
4715    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4716        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4717        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4718    }
4719
4720    /**
4721     * Used for backward compatibility to make sure any packages with
4722     * certificate chains get upgraded to the new style. {@code existingSigs}
4723     * will be in the old format (since they were stored on disk from before the
4724     * system upgrade) and {@code scannedSigs} will be in the newer format.
4725     */
4726    private int compareSignaturesCompat(PackageSignatures existingSigs,
4727            PackageParser.Package scannedPkg) {
4728        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4729            return PackageManager.SIGNATURE_NO_MATCH;
4730        }
4731
4732        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4733        for (Signature sig : existingSigs.mSignatures) {
4734            existingSet.add(sig);
4735        }
4736        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4737        for (Signature sig : scannedPkg.mSignatures) {
4738            try {
4739                Signature[] chainSignatures = sig.getChainSignatures();
4740                for (Signature chainSig : chainSignatures) {
4741                    scannedCompatSet.add(chainSig);
4742                }
4743            } catch (CertificateEncodingException e) {
4744                scannedCompatSet.add(sig);
4745            }
4746        }
4747        /*
4748         * Make sure the expanded scanned set contains all signatures in the
4749         * existing one.
4750         */
4751        if (scannedCompatSet.equals(existingSet)) {
4752            // Migrate the old signatures to the new scheme.
4753            existingSigs.assignSignatures(scannedPkg.mSignatures);
4754            // The new KeySets will be re-added later in the scanning process.
4755            synchronized (mPackages) {
4756                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4757            }
4758            return PackageManager.SIGNATURE_MATCH;
4759        }
4760        return PackageManager.SIGNATURE_NO_MATCH;
4761    }
4762
4763    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4764        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4765        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4766    }
4767
4768    private int compareSignaturesRecover(PackageSignatures existingSigs,
4769            PackageParser.Package scannedPkg) {
4770        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4771            return PackageManager.SIGNATURE_NO_MATCH;
4772        }
4773
4774        String msg = null;
4775        try {
4776            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4777                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4778                        + scannedPkg.packageName);
4779                return PackageManager.SIGNATURE_MATCH;
4780            }
4781        } catch (CertificateException e) {
4782            msg = e.getMessage();
4783        }
4784
4785        logCriticalInfo(Log.INFO,
4786                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4787        return PackageManager.SIGNATURE_NO_MATCH;
4788    }
4789
4790    @Override
4791    public List<String> getAllPackages() {
4792        synchronized (mPackages) {
4793            return new ArrayList<String>(mPackages.keySet());
4794        }
4795    }
4796
4797    @Override
4798    public String[] getPackagesForUid(int uid) {
4799        uid = UserHandle.getAppId(uid);
4800        // reader
4801        synchronized (mPackages) {
4802            Object obj = mSettings.getUserIdLPr(uid);
4803            if (obj instanceof SharedUserSetting) {
4804                final SharedUserSetting sus = (SharedUserSetting) obj;
4805                final int N = sus.packages.size();
4806                final String[] res = new String[N];
4807                for (int i = 0; i < N; i++) {
4808                    res[i] = sus.packages.valueAt(i).name;
4809                }
4810                return res;
4811            } else if (obj instanceof PackageSetting) {
4812                final PackageSetting ps = (PackageSetting) obj;
4813                return new String[] { ps.name };
4814            }
4815        }
4816        return null;
4817    }
4818
4819    @Override
4820    public String getNameForUid(int uid) {
4821        // reader
4822        synchronized (mPackages) {
4823            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4824            if (obj instanceof SharedUserSetting) {
4825                final SharedUserSetting sus = (SharedUserSetting) obj;
4826                return sus.name + ":" + sus.userId;
4827            } else if (obj instanceof PackageSetting) {
4828                final PackageSetting ps = (PackageSetting) obj;
4829                return ps.name;
4830            }
4831        }
4832        return null;
4833    }
4834
4835    @Override
4836    public int getUidForSharedUser(String sharedUserName) {
4837        if(sharedUserName == null) {
4838            return -1;
4839        }
4840        // reader
4841        synchronized (mPackages) {
4842            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4843            if (suid == null) {
4844                return -1;
4845            }
4846            return suid.userId;
4847        }
4848    }
4849
4850    @Override
4851    public int getFlagsForUid(int uid) {
4852        synchronized (mPackages) {
4853            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4854            if (obj instanceof SharedUserSetting) {
4855                final SharedUserSetting sus = (SharedUserSetting) obj;
4856                return sus.pkgFlags;
4857            } else if (obj instanceof PackageSetting) {
4858                final PackageSetting ps = (PackageSetting) obj;
4859                return ps.pkgFlags;
4860            }
4861        }
4862        return 0;
4863    }
4864
4865    @Override
4866    public int getPrivateFlagsForUid(int uid) {
4867        synchronized (mPackages) {
4868            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4869            if (obj instanceof SharedUserSetting) {
4870                final SharedUserSetting sus = (SharedUserSetting) obj;
4871                return sus.pkgPrivateFlags;
4872            } else if (obj instanceof PackageSetting) {
4873                final PackageSetting ps = (PackageSetting) obj;
4874                return ps.pkgPrivateFlags;
4875            }
4876        }
4877        return 0;
4878    }
4879
4880    @Override
4881    public boolean isUidPrivileged(int uid) {
4882        uid = UserHandle.getAppId(uid);
4883        // reader
4884        synchronized (mPackages) {
4885            Object obj = mSettings.getUserIdLPr(uid);
4886            if (obj instanceof SharedUserSetting) {
4887                final SharedUserSetting sus = (SharedUserSetting) obj;
4888                final Iterator<PackageSetting> it = sus.packages.iterator();
4889                while (it.hasNext()) {
4890                    if (it.next().isPrivileged()) {
4891                        return true;
4892                    }
4893                }
4894            } else if (obj instanceof PackageSetting) {
4895                final PackageSetting ps = (PackageSetting) obj;
4896                return ps.isPrivileged();
4897            }
4898        }
4899        return false;
4900    }
4901
4902    @Override
4903    public String[] getAppOpPermissionPackages(String permissionName) {
4904        synchronized (mPackages) {
4905            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4906            if (pkgs == null) {
4907                return null;
4908            }
4909            return pkgs.toArray(new String[pkgs.size()]);
4910        }
4911    }
4912
4913    @Override
4914    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4915            int flags, int userId) {
4916        try {
4917            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4918
4919            if (!sUserManager.exists(userId)) return null;
4920            flags = updateFlagsForResolve(flags, userId, intent);
4921            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4922                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4923
4924            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4925            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4926                    flags, userId);
4927            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4928
4929            final ResolveInfo bestChoice =
4930                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4931
4932            if (isEphemeralAllowed(intent, query, userId)) {
4933                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4934                final EphemeralResolveInfo ai =
4935                        getEphemeralResolveInfo(intent, resolvedType, userId);
4936                if (ai != null) {
4937                    if (DEBUG_EPHEMERAL) {
4938                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4939                    }
4940                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4941                    bestChoice.ephemeralResolveInfo = ai;
4942                }
4943                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4944            }
4945            return bestChoice;
4946        } finally {
4947            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4948        }
4949    }
4950
4951    @Override
4952    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4953            IntentFilter filter, int match, ComponentName activity) {
4954        final int userId = UserHandle.getCallingUserId();
4955        if (DEBUG_PREFERRED) {
4956            Log.v(TAG, "setLastChosenActivity intent=" + intent
4957                + " resolvedType=" + resolvedType
4958                + " flags=" + flags
4959                + " filter=" + filter
4960                + " match=" + match
4961                + " activity=" + activity);
4962            filter.dump(new PrintStreamPrinter(System.out), "    ");
4963        }
4964        intent.setComponent(null);
4965        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4966                userId);
4967        // Find any earlier preferred or last chosen entries and nuke them
4968        findPreferredActivity(intent, resolvedType,
4969                flags, query, 0, false, true, false, userId);
4970        // Add the new activity as the last chosen for this filter
4971        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4972                "Setting last chosen");
4973    }
4974
4975    @Override
4976    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4977        final int userId = UserHandle.getCallingUserId();
4978        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4979        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4980                userId);
4981        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4982                false, false, false, userId);
4983    }
4984
4985
4986    private boolean isEphemeralAllowed(
4987            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4988        // Short circuit and return early if possible.
4989        if (DISABLE_EPHEMERAL_APPS) {
4990            return false;
4991        }
4992        final int callingUser = UserHandle.getCallingUserId();
4993        if (callingUser != UserHandle.USER_SYSTEM) {
4994            return false;
4995        }
4996        if (mEphemeralResolverConnection == null) {
4997            return false;
4998        }
4999        if (intent.getComponent() != null) {
5000            return false;
5001        }
5002        if (intent.getPackage() != null) {
5003            return false;
5004        }
5005        final boolean isWebUri = hasWebURI(intent);
5006        if (!isWebUri) {
5007            return false;
5008        }
5009        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5010        synchronized (mPackages) {
5011            final int count = resolvedActivites.size();
5012            for (int n = 0; n < count; n++) {
5013                ResolveInfo info = resolvedActivites.get(n);
5014                String packageName = info.activityInfo.packageName;
5015                PackageSetting ps = mSettings.mPackages.get(packageName);
5016                if (ps != null) {
5017                    // Try to get the status from User settings first
5018                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5019                    int status = (int) (packedStatus >> 32);
5020                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5021                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5022                        if (DEBUG_EPHEMERAL) {
5023                            Slog.v(TAG, "DENY ephemeral apps;"
5024                                + " pkg: " + packageName + ", status: " + status);
5025                        }
5026                        return false;
5027                    }
5028                }
5029            }
5030        }
5031        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5032        return true;
5033    }
5034
5035    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
5036            int userId) {
5037        final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(),
5038                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
5039        final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(),
5040                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
5041        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
5042                ephemeralPrefixCount);
5043        final int[] shaPrefix = digest.getDigestPrefix();
5044        final byte[][] digestBytes = digest.getDigestBytes();
5045        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
5046                mEphemeralResolverConnection.getEphemeralResolveInfoList(
5047                        shaPrefix, ephemeralPrefixMask);
5048        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
5049            // No hash prefix match; there are no ephemeral apps for this domain.
5050            return null;
5051        }
5052
5053        // Go in reverse order so we match the narrowest scope first.
5054        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
5055            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
5056                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
5057                    continue;
5058                }
5059                final List<IntentFilter> filters = ephemeralApplication.getFilters();
5060                // No filters; this should never happen.
5061                if (filters.isEmpty()) {
5062                    continue;
5063                }
5064                // We have a domain match; resolve the filters to see if anything matches.
5065                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
5066                for (int j = filters.size() - 1; j >= 0; --j) {
5067                    final EphemeralResolveIntentInfo intentInfo =
5068                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
5069                    ephemeralResolver.addFilter(intentInfo);
5070                }
5071                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
5072                        intent, resolvedType, false /*defaultOnly*/, userId);
5073                if (!matchedResolveInfoList.isEmpty()) {
5074                    return matchedResolveInfoList.get(0);
5075                }
5076            }
5077        }
5078        // Hash or filter mis-match; no ephemeral apps for this domain.
5079        return null;
5080    }
5081
5082    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5083            int flags, List<ResolveInfo> query, int userId) {
5084        if (query != null) {
5085            final int N = query.size();
5086            if (N == 1) {
5087                return query.get(0);
5088            } else if (N > 1) {
5089                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5090                // If there is more than one activity with the same priority,
5091                // then let the user decide between them.
5092                ResolveInfo r0 = query.get(0);
5093                ResolveInfo r1 = query.get(1);
5094                if (DEBUG_INTENT_MATCHING || debug) {
5095                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5096                            + r1.activityInfo.name + "=" + r1.priority);
5097                }
5098                // If the first activity has a higher priority, or a different
5099                // default, then it is always desirable to pick it.
5100                if (r0.priority != r1.priority
5101                        || r0.preferredOrder != r1.preferredOrder
5102                        || r0.isDefault != r1.isDefault) {
5103                    return query.get(0);
5104                }
5105                // If we have saved a preference for a preferred activity for
5106                // this Intent, use that.
5107                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5108                        flags, query, r0.priority, true, false, debug, userId);
5109                if (ri != null) {
5110                    return ri;
5111                }
5112                ri = new ResolveInfo(mResolveInfo);
5113                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5114                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5115                // If all of the options come from the same package, show the application's
5116                // label and icon instead of the generic resolver's.
5117                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5118                // and then throw away the ResolveInfo itself, meaning that the caller loses
5119                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5120                // a fallback for this case; we only set the target package's resources on
5121                // the ResolveInfo, not the ActivityInfo.
5122                final String intentPackage = intent.getPackage();
5123                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5124                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5125                    ri.resolvePackageName = intentPackage;
5126                    if (userNeedsBadging(userId)) {
5127                        ri.noResourceId = true;
5128                    } else {
5129                        ri.icon = appi.icon;
5130                    }
5131                    ri.iconResourceId = appi.icon;
5132                    ri.labelRes = appi.labelRes;
5133                }
5134                ri.activityInfo.applicationInfo = new ApplicationInfo(
5135                        ri.activityInfo.applicationInfo);
5136                if (userId != 0) {
5137                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5138                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5139                }
5140                // Make sure that the resolver is displayable in car mode
5141                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5142                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5143                return ri;
5144            }
5145        }
5146        return null;
5147    }
5148
5149    /**
5150     * Return true if the given list is not empty and all of its contents have
5151     * an activityInfo with the given package name.
5152     */
5153    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5154        if (ArrayUtils.isEmpty(list)) {
5155            return false;
5156        }
5157        for (int i = 0, N = list.size(); i < N; i++) {
5158            final ResolveInfo ri = list.get(i);
5159            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5160            if (ai == null || !packageName.equals(ai.packageName)) {
5161                return false;
5162            }
5163        }
5164        return true;
5165    }
5166
5167    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5168            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5169        final int N = query.size();
5170        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5171                .get(userId);
5172        // Get the list of persistent preferred activities that handle the intent
5173        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5174        List<PersistentPreferredActivity> pprefs = ppir != null
5175                ? ppir.queryIntent(intent, resolvedType,
5176                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5177                : null;
5178        if (pprefs != null && pprefs.size() > 0) {
5179            final int M = pprefs.size();
5180            for (int i=0; i<M; i++) {
5181                final PersistentPreferredActivity ppa = pprefs.get(i);
5182                if (DEBUG_PREFERRED || debug) {
5183                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5184                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5185                            + "\n  component=" + ppa.mComponent);
5186                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5187                }
5188                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5189                        flags | MATCH_DISABLED_COMPONENTS, userId);
5190                if (DEBUG_PREFERRED || debug) {
5191                    Slog.v(TAG, "Found persistent preferred activity:");
5192                    if (ai != null) {
5193                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5194                    } else {
5195                        Slog.v(TAG, "  null");
5196                    }
5197                }
5198                if (ai == null) {
5199                    // This previously registered persistent preferred activity
5200                    // component is no longer known. Ignore it and do NOT remove it.
5201                    continue;
5202                }
5203                for (int j=0; j<N; j++) {
5204                    final ResolveInfo ri = query.get(j);
5205                    if (!ri.activityInfo.applicationInfo.packageName
5206                            .equals(ai.applicationInfo.packageName)) {
5207                        continue;
5208                    }
5209                    if (!ri.activityInfo.name.equals(ai.name)) {
5210                        continue;
5211                    }
5212                    //  Found a persistent preference that can handle the intent.
5213                    if (DEBUG_PREFERRED || debug) {
5214                        Slog.v(TAG, "Returning persistent preferred activity: " +
5215                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5216                    }
5217                    return ri;
5218                }
5219            }
5220        }
5221        return null;
5222    }
5223
5224    // TODO: handle preferred activities missing while user has amnesia
5225    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5226            List<ResolveInfo> query, int priority, boolean always,
5227            boolean removeMatches, boolean debug, int userId) {
5228        if (!sUserManager.exists(userId)) return null;
5229        flags = updateFlagsForResolve(flags, userId, intent);
5230        // writer
5231        synchronized (mPackages) {
5232            if (intent.getSelector() != null) {
5233                intent = intent.getSelector();
5234            }
5235            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5236
5237            // Try to find a matching persistent preferred activity.
5238            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5239                    debug, userId);
5240
5241            // If a persistent preferred activity matched, use it.
5242            if (pri != null) {
5243                return pri;
5244            }
5245
5246            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5247            // Get the list of preferred activities that handle the intent
5248            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5249            List<PreferredActivity> prefs = pir != null
5250                    ? pir.queryIntent(intent, resolvedType,
5251                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5252                    : null;
5253            if (prefs != null && prefs.size() > 0) {
5254                boolean changed = false;
5255                try {
5256                    // First figure out how good the original match set is.
5257                    // We will only allow preferred activities that came
5258                    // from the same match quality.
5259                    int match = 0;
5260
5261                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5262
5263                    final int N = query.size();
5264                    for (int j=0; j<N; j++) {
5265                        final ResolveInfo ri = query.get(j);
5266                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5267                                + ": 0x" + Integer.toHexString(match));
5268                        if (ri.match > match) {
5269                            match = ri.match;
5270                        }
5271                    }
5272
5273                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5274                            + Integer.toHexString(match));
5275
5276                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5277                    final int M = prefs.size();
5278                    for (int i=0; i<M; i++) {
5279                        final PreferredActivity pa = prefs.get(i);
5280                        if (DEBUG_PREFERRED || debug) {
5281                            Slog.v(TAG, "Checking PreferredActivity ds="
5282                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5283                                    + "\n  component=" + pa.mPref.mComponent);
5284                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5285                        }
5286                        if (pa.mPref.mMatch != match) {
5287                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5288                                    + Integer.toHexString(pa.mPref.mMatch));
5289                            continue;
5290                        }
5291                        // If it's not an "always" type preferred activity and that's what we're
5292                        // looking for, skip it.
5293                        if (always && !pa.mPref.mAlways) {
5294                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5295                            continue;
5296                        }
5297                        final ActivityInfo ai = getActivityInfo(
5298                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5299                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5300                                userId);
5301                        if (DEBUG_PREFERRED || debug) {
5302                            Slog.v(TAG, "Found preferred activity:");
5303                            if (ai != null) {
5304                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5305                            } else {
5306                                Slog.v(TAG, "  null");
5307                            }
5308                        }
5309                        if (ai == null) {
5310                            // This previously registered preferred activity
5311                            // component is no longer known.  Most likely an update
5312                            // to the app was installed and in the new version this
5313                            // component no longer exists.  Clean it up by removing
5314                            // it from the preferred activities list, and skip it.
5315                            Slog.w(TAG, "Removing dangling preferred activity: "
5316                                    + pa.mPref.mComponent);
5317                            pir.removeFilter(pa);
5318                            changed = true;
5319                            continue;
5320                        }
5321                        for (int j=0; j<N; j++) {
5322                            final ResolveInfo ri = query.get(j);
5323                            if (!ri.activityInfo.applicationInfo.packageName
5324                                    .equals(ai.applicationInfo.packageName)) {
5325                                continue;
5326                            }
5327                            if (!ri.activityInfo.name.equals(ai.name)) {
5328                                continue;
5329                            }
5330
5331                            if (removeMatches) {
5332                                pir.removeFilter(pa);
5333                                changed = true;
5334                                if (DEBUG_PREFERRED) {
5335                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5336                                }
5337                                break;
5338                            }
5339
5340                            // Okay we found a previously set preferred or last chosen app.
5341                            // If the result set is different from when this
5342                            // was created, we need to clear it and re-ask the
5343                            // user their preference, if we're looking for an "always" type entry.
5344                            if (always && !pa.mPref.sameSet(query)) {
5345                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5346                                        + intent + " type " + resolvedType);
5347                                if (DEBUG_PREFERRED) {
5348                                    Slog.v(TAG, "Removing preferred activity since set changed "
5349                                            + pa.mPref.mComponent);
5350                                }
5351                                pir.removeFilter(pa);
5352                                // Re-add the filter as a "last chosen" entry (!always)
5353                                PreferredActivity lastChosen = new PreferredActivity(
5354                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5355                                pir.addFilter(lastChosen);
5356                                changed = true;
5357                                return null;
5358                            }
5359
5360                            // Yay! Either the set matched or we're looking for the last chosen
5361                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5362                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5363                            return ri;
5364                        }
5365                    }
5366                } finally {
5367                    if (changed) {
5368                        if (DEBUG_PREFERRED) {
5369                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5370                        }
5371                        scheduleWritePackageRestrictionsLocked(userId);
5372                    }
5373                }
5374            }
5375        }
5376        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5377        return null;
5378    }
5379
5380    /*
5381     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5382     */
5383    @Override
5384    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5385            int targetUserId) {
5386        mContext.enforceCallingOrSelfPermission(
5387                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5388        List<CrossProfileIntentFilter> matches =
5389                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5390        if (matches != null) {
5391            int size = matches.size();
5392            for (int i = 0; i < size; i++) {
5393                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5394            }
5395        }
5396        if (hasWebURI(intent)) {
5397            // cross-profile app linking works only towards the parent.
5398            final UserInfo parent = getProfileParent(sourceUserId);
5399            synchronized(mPackages) {
5400                int flags = updateFlagsForResolve(0, parent.id, intent);
5401                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5402                        intent, resolvedType, flags, sourceUserId, parent.id);
5403                return xpDomainInfo != null;
5404            }
5405        }
5406        return false;
5407    }
5408
5409    private UserInfo getProfileParent(int userId) {
5410        final long identity = Binder.clearCallingIdentity();
5411        try {
5412            return sUserManager.getProfileParent(userId);
5413        } finally {
5414            Binder.restoreCallingIdentity(identity);
5415        }
5416    }
5417
5418    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5419            String resolvedType, int userId) {
5420        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5421        if (resolver != null) {
5422            return resolver.queryIntent(intent, resolvedType, false, userId);
5423        }
5424        return null;
5425    }
5426
5427    @Override
5428    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5429            String resolvedType, int flags, int userId) {
5430        try {
5431            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5432
5433            return new ParceledListSlice<>(
5434                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5435        } finally {
5436            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5437        }
5438    }
5439
5440    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5441            String resolvedType, int flags, int userId) {
5442        if (!sUserManager.exists(userId)) return Collections.emptyList();
5443        flags = updateFlagsForResolve(flags, userId, intent);
5444        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5445                false /* requireFullPermission */, false /* checkShell */,
5446                "query intent activities");
5447        ComponentName comp = intent.getComponent();
5448        if (comp == null) {
5449            if (intent.getSelector() != null) {
5450                intent = intent.getSelector();
5451                comp = intent.getComponent();
5452            }
5453        }
5454
5455        if (comp != null) {
5456            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5457            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5458            if (ai != null) {
5459                final ResolveInfo ri = new ResolveInfo();
5460                ri.activityInfo = ai;
5461                list.add(ri);
5462            }
5463            return list;
5464        }
5465
5466        // reader
5467        synchronized (mPackages) {
5468            final String pkgName = intent.getPackage();
5469            if (pkgName == null) {
5470                List<CrossProfileIntentFilter> matchingFilters =
5471                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5472                // Check for results that need to skip the current profile.
5473                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5474                        resolvedType, flags, userId);
5475                if (xpResolveInfo != null) {
5476                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5477                    result.add(xpResolveInfo);
5478                    return filterIfNotSystemUser(result, userId);
5479                }
5480
5481                // Check for results in the current profile.
5482                List<ResolveInfo> result = mActivities.queryIntent(
5483                        intent, resolvedType, flags, userId);
5484                result = filterIfNotSystemUser(result, userId);
5485
5486                // Check for cross profile results.
5487                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5488                xpResolveInfo = queryCrossProfileIntents(
5489                        matchingFilters, intent, resolvedType, flags, userId,
5490                        hasNonNegativePriorityResult);
5491                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5492                    boolean isVisibleToUser = filterIfNotSystemUser(
5493                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5494                    if (isVisibleToUser) {
5495                        result.add(xpResolveInfo);
5496                        Collections.sort(result, mResolvePrioritySorter);
5497                    }
5498                }
5499                if (hasWebURI(intent)) {
5500                    CrossProfileDomainInfo xpDomainInfo = null;
5501                    final UserInfo parent = getProfileParent(userId);
5502                    if (parent != null) {
5503                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5504                                flags, userId, parent.id);
5505                    }
5506                    if (xpDomainInfo != null) {
5507                        if (xpResolveInfo != null) {
5508                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5509                            // in the result.
5510                            result.remove(xpResolveInfo);
5511                        }
5512                        if (result.size() == 0) {
5513                            result.add(xpDomainInfo.resolveInfo);
5514                            return result;
5515                        }
5516                    } else if (result.size() <= 1) {
5517                        return result;
5518                    }
5519                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5520                            xpDomainInfo, userId);
5521                    Collections.sort(result, mResolvePrioritySorter);
5522                }
5523                return result;
5524            }
5525            final PackageParser.Package pkg = mPackages.get(pkgName);
5526            if (pkg != null) {
5527                return filterIfNotSystemUser(
5528                        mActivities.queryIntentForPackage(
5529                                intent, resolvedType, flags, pkg.activities, userId),
5530                        userId);
5531            }
5532            return new ArrayList<ResolveInfo>();
5533        }
5534    }
5535
5536    private static class CrossProfileDomainInfo {
5537        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5538        ResolveInfo resolveInfo;
5539        /* Best domain verification status of the activities found in the other profile */
5540        int bestDomainVerificationStatus;
5541    }
5542
5543    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5544            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5545        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5546                sourceUserId)) {
5547            return null;
5548        }
5549        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5550                resolvedType, flags, parentUserId);
5551
5552        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5553            return null;
5554        }
5555        CrossProfileDomainInfo result = null;
5556        int size = resultTargetUser.size();
5557        for (int i = 0; i < size; i++) {
5558            ResolveInfo riTargetUser = resultTargetUser.get(i);
5559            // Intent filter verification is only for filters that specify a host. So don't return
5560            // those that handle all web uris.
5561            if (riTargetUser.handleAllWebDataURI) {
5562                continue;
5563            }
5564            String packageName = riTargetUser.activityInfo.packageName;
5565            PackageSetting ps = mSettings.mPackages.get(packageName);
5566            if (ps == null) {
5567                continue;
5568            }
5569            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5570            int status = (int)(verificationState >> 32);
5571            if (result == null) {
5572                result = new CrossProfileDomainInfo();
5573                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5574                        sourceUserId, parentUserId);
5575                result.bestDomainVerificationStatus = status;
5576            } else {
5577                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5578                        result.bestDomainVerificationStatus);
5579            }
5580        }
5581        // Don't consider matches with status NEVER across profiles.
5582        if (result != null && result.bestDomainVerificationStatus
5583                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5584            return null;
5585        }
5586        return result;
5587    }
5588
5589    /**
5590     * Verification statuses are ordered from the worse to the best, except for
5591     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5592     */
5593    private int bestDomainVerificationStatus(int status1, int status2) {
5594        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5595            return status2;
5596        }
5597        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5598            return status1;
5599        }
5600        return (int) MathUtils.max(status1, status2);
5601    }
5602
5603    private boolean isUserEnabled(int userId) {
5604        long callingId = Binder.clearCallingIdentity();
5605        try {
5606            UserInfo userInfo = sUserManager.getUserInfo(userId);
5607            return userInfo != null && userInfo.isEnabled();
5608        } finally {
5609            Binder.restoreCallingIdentity(callingId);
5610        }
5611    }
5612
5613    /**
5614     * Filter out activities with systemUserOnly flag set, when current user is not System.
5615     *
5616     * @return filtered list
5617     */
5618    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5619        if (userId == UserHandle.USER_SYSTEM) {
5620            return resolveInfos;
5621        }
5622        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5623            ResolveInfo info = resolveInfos.get(i);
5624            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5625                resolveInfos.remove(i);
5626            }
5627        }
5628        return resolveInfos;
5629    }
5630
5631    /**
5632     * @param resolveInfos list of resolve infos in descending priority order
5633     * @return if the list contains a resolve info with non-negative priority
5634     */
5635    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5636        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5637    }
5638
5639    private static boolean hasWebURI(Intent intent) {
5640        if (intent.getData() == null) {
5641            return false;
5642        }
5643        final String scheme = intent.getScheme();
5644        if (TextUtils.isEmpty(scheme)) {
5645            return false;
5646        }
5647        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5648    }
5649
5650    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5651            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5652            int userId) {
5653        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5654
5655        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5656            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5657                    candidates.size());
5658        }
5659
5660        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5661        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5662        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5663        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5664        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5665        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5666
5667        synchronized (mPackages) {
5668            final int count = candidates.size();
5669            // First, try to use linked apps. Partition the candidates into four lists:
5670            // one for the final results, one for the "do not use ever", one for "undefined status"
5671            // and finally one for "browser app type".
5672            for (int n=0; n<count; n++) {
5673                ResolveInfo info = candidates.get(n);
5674                String packageName = info.activityInfo.packageName;
5675                PackageSetting ps = mSettings.mPackages.get(packageName);
5676                if (ps != null) {
5677                    // Add to the special match all list (Browser use case)
5678                    if (info.handleAllWebDataURI) {
5679                        matchAllList.add(info);
5680                        continue;
5681                    }
5682                    // Try to get the status from User settings first
5683                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5684                    int status = (int)(packedStatus >> 32);
5685                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5686                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5687                        if (DEBUG_DOMAIN_VERIFICATION) {
5688                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5689                                    + " : linkgen=" + linkGeneration);
5690                        }
5691                        // Use link-enabled generation as preferredOrder, i.e.
5692                        // prefer newly-enabled over earlier-enabled.
5693                        info.preferredOrder = linkGeneration;
5694                        alwaysList.add(info);
5695                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5696                        if (DEBUG_DOMAIN_VERIFICATION) {
5697                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5698                        }
5699                        neverList.add(info);
5700                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5701                        if (DEBUG_DOMAIN_VERIFICATION) {
5702                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5703                        }
5704                        alwaysAskList.add(info);
5705                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5706                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5707                        if (DEBUG_DOMAIN_VERIFICATION) {
5708                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5709                        }
5710                        undefinedList.add(info);
5711                    }
5712                }
5713            }
5714
5715            // We'll want to include browser possibilities in a few cases
5716            boolean includeBrowser = false;
5717
5718            // First try to add the "always" resolution(s) for the current user, if any
5719            if (alwaysList.size() > 0) {
5720                result.addAll(alwaysList);
5721            } else {
5722                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5723                result.addAll(undefinedList);
5724                // Maybe add one for the other profile.
5725                if (xpDomainInfo != null && (
5726                        xpDomainInfo.bestDomainVerificationStatus
5727                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5728                    result.add(xpDomainInfo.resolveInfo);
5729                }
5730                includeBrowser = true;
5731            }
5732
5733            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5734            // If there were 'always' entries their preferred order has been set, so we also
5735            // back that off to make the alternatives equivalent
5736            if (alwaysAskList.size() > 0) {
5737                for (ResolveInfo i : result) {
5738                    i.preferredOrder = 0;
5739                }
5740                result.addAll(alwaysAskList);
5741                includeBrowser = true;
5742            }
5743
5744            if (includeBrowser) {
5745                // Also add browsers (all of them or only the default one)
5746                if (DEBUG_DOMAIN_VERIFICATION) {
5747                    Slog.v(TAG, "   ...including browsers in candidate set");
5748                }
5749                if ((matchFlags & MATCH_ALL) != 0) {
5750                    result.addAll(matchAllList);
5751                } else {
5752                    // Browser/generic handling case.  If there's a default browser, go straight
5753                    // to that (but only if there is no other higher-priority match).
5754                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5755                    int maxMatchPrio = 0;
5756                    ResolveInfo defaultBrowserMatch = null;
5757                    final int numCandidates = matchAllList.size();
5758                    for (int n = 0; n < numCandidates; n++) {
5759                        ResolveInfo info = matchAllList.get(n);
5760                        // track the highest overall match priority...
5761                        if (info.priority > maxMatchPrio) {
5762                            maxMatchPrio = info.priority;
5763                        }
5764                        // ...and the highest-priority default browser match
5765                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5766                            if (defaultBrowserMatch == null
5767                                    || (defaultBrowserMatch.priority < info.priority)) {
5768                                if (debug) {
5769                                    Slog.v(TAG, "Considering default browser match " + info);
5770                                }
5771                                defaultBrowserMatch = info;
5772                            }
5773                        }
5774                    }
5775                    if (defaultBrowserMatch != null
5776                            && defaultBrowserMatch.priority >= maxMatchPrio
5777                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5778                    {
5779                        if (debug) {
5780                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5781                        }
5782                        result.add(defaultBrowserMatch);
5783                    } else {
5784                        result.addAll(matchAllList);
5785                    }
5786                }
5787
5788                // If there is nothing selected, add all candidates and remove the ones that the user
5789                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5790                if (result.size() == 0) {
5791                    result.addAll(candidates);
5792                    result.removeAll(neverList);
5793                }
5794            }
5795        }
5796        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5797            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5798                    result.size());
5799            for (ResolveInfo info : result) {
5800                Slog.v(TAG, "  + " + info.activityInfo);
5801            }
5802        }
5803        return result;
5804    }
5805
5806    // Returns a packed value as a long:
5807    //
5808    // high 'int'-sized word: link status: undefined/ask/never/always.
5809    // low 'int'-sized word: relative priority among 'always' results.
5810    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5811        long result = ps.getDomainVerificationStatusForUser(userId);
5812        // if none available, get the master status
5813        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5814            if (ps.getIntentFilterVerificationInfo() != null) {
5815                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5816            }
5817        }
5818        return result;
5819    }
5820
5821    private ResolveInfo querySkipCurrentProfileIntents(
5822            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5823            int flags, int sourceUserId) {
5824        if (matchingFilters != null) {
5825            int size = matchingFilters.size();
5826            for (int i = 0; i < size; i ++) {
5827                CrossProfileIntentFilter filter = matchingFilters.get(i);
5828                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5829                    // Checking if there are activities in the target user that can handle the
5830                    // intent.
5831                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5832                            resolvedType, flags, sourceUserId);
5833                    if (resolveInfo != null) {
5834                        return resolveInfo;
5835                    }
5836                }
5837            }
5838        }
5839        return null;
5840    }
5841
5842    // Return matching ResolveInfo in target user if any.
5843    private ResolveInfo queryCrossProfileIntents(
5844            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5845            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5846        if (matchingFilters != null) {
5847            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5848            // match the same intent. For performance reasons, it is better not to
5849            // run queryIntent twice for the same userId
5850            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5851            int size = matchingFilters.size();
5852            for (int i = 0; i < size; i++) {
5853                CrossProfileIntentFilter filter = matchingFilters.get(i);
5854                int targetUserId = filter.getTargetUserId();
5855                boolean skipCurrentProfile =
5856                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5857                boolean skipCurrentProfileIfNoMatchFound =
5858                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5859                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5860                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5861                    // Checking if there are activities in the target user that can handle the
5862                    // intent.
5863                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5864                            resolvedType, flags, sourceUserId);
5865                    if (resolveInfo != null) return resolveInfo;
5866                    alreadyTriedUserIds.put(targetUserId, true);
5867                }
5868            }
5869        }
5870        return null;
5871    }
5872
5873    /**
5874     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5875     * will forward the intent to the filter's target user.
5876     * Otherwise, returns null.
5877     */
5878    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5879            String resolvedType, int flags, int sourceUserId) {
5880        int targetUserId = filter.getTargetUserId();
5881        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5882                resolvedType, flags, targetUserId);
5883        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5884            // If all the matches in the target profile are suspended, return null.
5885            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5886                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5887                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5888                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5889                            targetUserId);
5890                }
5891            }
5892        }
5893        return null;
5894    }
5895
5896    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5897            int sourceUserId, int targetUserId) {
5898        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5899        long ident = Binder.clearCallingIdentity();
5900        boolean targetIsProfile;
5901        try {
5902            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5903        } finally {
5904            Binder.restoreCallingIdentity(ident);
5905        }
5906        String className;
5907        if (targetIsProfile) {
5908            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5909        } else {
5910            className = FORWARD_INTENT_TO_PARENT;
5911        }
5912        ComponentName forwardingActivityComponentName = new ComponentName(
5913                mAndroidApplication.packageName, className);
5914        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5915                sourceUserId);
5916        if (!targetIsProfile) {
5917            forwardingActivityInfo.showUserIcon = targetUserId;
5918            forwardingResolveInfo.noResourceId = true;
5919        }
5920        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5921        forwardingResolveInfo.priority = 0;
5922        forwardingResolveInfo.preferredOrder = 0;
5923        forwardingResolveInfo.match = 0;
5924        forwardingResolveInfo.isDefault = true;
5925        forwardingResolveInfo.filter = filter;
5926        forwardingResolveInfo.targetUserId = targetUserId;
5927        return forwardingResolveInfo;
5928    }
5929
5930    @Override
5931    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5932            Intent[] specifics, String[] specificTypes, Intent intent,
5933            String resolvedType, int flags, int userId) {
5934        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5935                specificTypes, intent, resolvedType, flags, userId));
5936    }
5937
5938    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5939            Intent[] specifics, String[] specificTypes, Intent intent,
5940            String resolvedType, int flags, int userId) {
5941        if (!sUserManager.exists(userId)) return Collections.emptyList();
5942        flags = updateFlagsForResolve(flags, userId, intent);
5943        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5944                false /* requireFullPermission */, false /* checkShell */,
5945                "query intent activity options");
5946        final String resultsAction = intent.getAction();
5947
5948        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5949                | PackageManager.GET_RESOLVED_FILTER, userId);
5950
5951        if (DEBUG_INTENT_MATCHING) {
5952            Log.v(TAG, "Query " + intent + ": " + results);
5953        }
5954
5955        int specificsPos = 0;
5956        int N;
5957
5958        // todo: note that the algorithm used here is O(N^2).  This
5959        // isn't a problem in our current environment, but if we start running
5960        // into situations where we have more than 5 or 10 matches then this
5961        // should probably be changed to something smarter...
5962
5963        // First we go through and resolve each of the specific items
5964        // that were supplied, taking care of removing any corresponding
5965        // duplicate items in the generic resolve list.
5966        if (specifics != null) {
5967            for (int i=0; i<specifics.length; i++) {
5968                final Intent sintent = specifics[i];
5969                if (sintent == null) {
5970                    continue;
5971                }
5972
5973                if (DEBUG_INTENT_MATCHING) {
5974                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5975                }
5976
5977                String action = sintent.getAction();
5978                if (resultsAction != null && resultsAction.equals(action)) {
5979                    // If this action was explicitly requested, then don't
5980                    // remove things that have it.
5981                    action = null;
5982                }
5983
5984                ResolveInfo ri = null;
5985                ActivityInfo ai = null;
5986
5987                ComponentName comp = sintent.getComponent();
5988                if (comp == null) {
5989                    ri = resolveIntent(
5990                        sintent,
5991                        specificTypes != null ? specificTypes[i] : null,
5992                            flags, userId);
5993                    if (ri == null) {
5994                        continue;
5995                    }
5996                    if (ri == mResolveInfo) {
5997                        // ACK!  Must do something better with this.
5998                    }
5999                    ai = ri.activityInfo;
6000                    comp = new ComponentName(ai.applicationInfo.packageName,
6001                            ai.name);
6002                } else {
6003                    ai = getActivityInfo(comp, flags, userId);
6004                    if (ai == null) {
6005                        continue;
6006                    }
6007                }
6008
6009                // Look for any generic query activities that are duplicates
6010                // of this specific one, and remove them from the results.
6011                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6012                N = results.size();
6013                int j;
6014                for (j=specificsPos; j<N; j++) {
6015                    ResolveInfo sri = results.get(j);
6016                    if ((sri.activityInfo.name.equals(comp.getClassName())
6017                            && sri.activityInfo.applicationInfo.packageName.equals(
6018                                    comp.getPackageName()))
6019                        || (action != null && sri.filter.matchAction(action))) {
6020                        results.remove(j);
6021                        if (DEBUG_INTENT_MATCHING) Log.v(
6022                            TAG, "Removing duplicate item from " + j
6023                            + " due to specific " + specificsPos);
6024                        if (ri == null) {
6025                            ri = sri;
6026                        }
6027                        j--;
6028                        N--;
6029                    }
6030                }
6031
6032                // Add this specific item to its proper place.
6033                if (ri == null) {
6034                    ri = new ResolveInfo();
6035                    ri.activityInfo = ai;
6036                }
6037                results.add(specificsPos, ri);
6038                ri.specificIndex = i;
6039                specificsPos++;
6040            }
6041        }
6042
6043        // Now we go through the remaining generic results and remove any
6044        // duplicate actions that are found here.
6045        N = results.size();
6046        for (int i=specificsPos; i<N-1; i++) {
6047            final ResolveInfo rii = results.get(i);
6048            if (rii.filter == null) {
6049                continue;
6050            }
6051
6052            // Iterate over all of the actions of this result's intent
6053            // filter...  typically this should be just one.
6054            final Iterator<String> it = rii.filter.actionsIterator();
6055            if (it == null) {
6056                continue;
6057            }
6058            while (it.hasNext()) {
6059                final String action = it.next();
6060                if (resultsAction != null && resultsAction.equals(action)) {
6061                    // If this action was explicitly requested, then don't
6062                    // remove things that have it.
6063                    continue;
6064                }
6065                for (int j=i+1; j<N; j++) {
6066                    final ResolveInfo rij = results.get(j);
6067                    if (rij.filter != null && rij.filter.hasAction(action)) {
6068                        results.remove(j);
6069                        if (DEBUG_INTENT_MATCHING) Log.v(
6070                            TAG, "Removing duplicate item from " + j
6071                            + " due to action " + action + " at " + i);
6072                        j--;
6073                        N--;
6074                    }
6075                }
6076            }
6077
6078            // If the caller didn't request filter information, drop it now
6079            // so we don't have to marshall/unmarshall it.
6080            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6081                rii.filter = null;
6082            }
6083        }
6084
6085        // Filter out the caller activity if so requested.
6086        if (caller != null) {
6087            N = results.size();
6088            for (int i=0; i<N; i++) {
6089                ActivityInfo ainfo = results.get(i).activityInfo;
6090                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6091                        && caller.getClassName().equals(ainfo.name)) {
6092                    results.remove(i);
6093                    break;
6094                }
6095            }
6096        }
6097
6098        // If the caller didn't request filter information,
6099        // drop them now so we don't have to
6100        // marshall/unmarshall it.
6101        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6102            N = results.size();
6103            for (int i=0; i<N; i++) {
6104                results.get(i).filter = null;
6105            }
6106        }
6107
6108        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6109        return results;
6110    }
6111
6112    @Override
6113    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6114            String resolvedType, int flags, int userId) {
6115        return new ParceledListSlice<>(
6116                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6117    }
6118
6119    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6120            String resolvedType, int flags, int userId) {
6121        if (!sUserManager.exists(userId)) return Collections.emptyList();
6122        flags = updateFlagsForResolve(flags, userId, intent);
6123        ComponentName comp = intent.getComponent();
6124        if (comp == null) {
6125            if (intent.getSelector() != null) {
6126                intent = intent.getSelector();
6127                comp = intent.getComponent();
6128            }
6129        }
6130        if (comp != null) {
6131            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6132            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6133            if (ai != null) {
6134                ResolveInfo ri = new ResolveInfo();
6135                ri.activityInfo = ai;
6136                list.add(ri);
6137            }
6138            return list;
6139        }
6140
6141        // reader
6142        synchronized (mPackages) {
6143            String pkgName = intent.getPackage();
6144            if (pkgName == null) {
6145                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6146            }
6147            final PackageParser.Package pkg = mPackages.get(pkgName);
6148            if (pkg != null) {
6149                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6150                        userId);
6151            }
6152            return Collections.emptyList();
6153        }
6154    }
6155
6156    @Override
6157    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6158        if (!sUserManager.exists(userId)) return null;
6159        flags = updateFlagsForResolve(flags, userId, intent);
6160        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6161        if (query != null) {
6162            if (query.size() >= 1) {
6163                // If there is more than one service with the same priority,
6164                // just arbitrarily pick the first one.
6165                return query.get(0);
6166            }
6167        }
6168        return null;
6169    }
6170
6171    @Override
6172    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6173            String resolvedType, int flags, int userId) {
6174        return new ParceledListSlice<>(
6175                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6176    }
6177
6178    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6179            String resolvedType, int flags, int userId) {
6180        if (!sUserManager.exists(userId)) return Collections.emptyList();
6181        flags = updateFlagsForResolve(flags, userId, intent);
6182        ComponentName comp = intent.getComponent();
6183        if (comp == null) {
6184            if (intent.getSelector() != null) {
6185                intent = intent.getSelector();
6186                comp = intent.getComponent();
6187            }
6188        }
6189        if (comp != null) {
6190            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6191            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6192            if (si != null) {
6193                final ResolveInfo ri = new ResolveInfo();
6194                ri.serviceInfo = si;
6195                list.add(ri);
6196            }
6197            return list;
6198        }
6199
6200        // reader
6201        synchronized (mPackages) {
6202            String pkgName = intent.getPackage();
6203            if (pkgName == null) {
6204                return mServices.queryIntent(intent, resolvedType, flags, userId);
6205            }
6206            final PackageParser.Package pkg = mPackages.get(pkgName);
6207            if (pkg != null) {
6208                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6209                        userId);
6210            }
6211            return Collections.emptyList();
6212        }
6213    }
6214
6215    @Override
6216    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6217            String resolvedType, int flags, int userId) {
6218        return new ParceledListSlice<>(
6219                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6220    }
6221
6222    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6223            Intent intent, String resolvedType, int flags, int userId) {
6224        if (!sUserManager.exists(userId)) return Collections.emptyList();
6225        flags = updateFlagsForResolve(flags, userId, intent);
6226        ComponentName comp = intent.getComponent();
6227        if (comp == null) {
6228            if (intent.getSelector() != null) {
6229                intent = intent.getSelector();
6230                comp = intent.getComponent();
6231            }
6232        }
6233        if (comp != null) {
6234            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6235            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6236            if (pi != null) {
6237                final ResolveInfo ri = new ResolveInfo();
6238                ri.providerInfo = pi;
6239                list.add(ri);
6240            }
6241            return list;
6242        }
6243
6244        // reader
6245        synchronized (mPackages) {
6246            String pkgName = intent.getPackage();
6247            if (pkgName == null) {
6248                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6249            }
6250            final PackageParser.Package pkg = mPackages.get(pkgName);
6251            if (pkg != null) {
6252                return mProviders.queryIntentForPackage(
6253                        intent, resolvedType, flags, pkg.providers, userId);
6254            }
6255            return Collections.emptyList();
6256        }
6257    }
6258
6259    @Override
6260    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6261        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6262        flags = updateFlagsForPackage(flags, userId, null);
6263        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6264        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6265                true /* requireFullPermission */, false /* checkShell */,
6266                "get installed packages");
6267
6268        // writer
6269        synchronized (mPackages) {
6270            ArrayList<PackageInfo> list;
6271            if (listUninstalled) {
6272                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6273                for (PackageSetting ps : mSettings.mPackages.values()) {
6274                    final PackageInfo pi;
6275                    if (ps.pkg != null) {
6276                        pi = generatePackageInfo(ps, flags, userId);
6277                    } else {
6278                        pi = generatePackageInfo(ps, flags, userId);
6279                    }
6280                    if (pi != null) {
6281                        list.add(pi);
6282                    }
6283                }
6284            } else {
6285                list = new ArrayList<PackageInfo>(mPackages.size());
6286                for (PackageParser.Package p : mPackages.values()) {
6287                    final PackageInfo pi =
6288                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6289                    if (pi != null) {
6290                        list.add(pi);
6291                    }
6292                }
6293            }
6294
6295            return new ParceledListSlice<PackageInfo>(list);
6296        }
6297    }
6298
6299    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6300            String[] permissions, boolean[] tmp, int flags, int userId) {
6301        int numMatch = 0;
6302        final PermissionsState permissionsState = ps.getPermissionsState();
6303        for (int i=0; i<permissions.length; i++) {
6304            final String permission = permissions[i];
6305            if (permissionsState.hasPermission(permission, userId)) {
6306                tmp[i] = true;
6307                numMatch++;
6308            } else {
6309                tmp[i] = false;
6310            }
6311        }
6312        if (numMatch == 0) {
6313            return;
6314        }
6315        final PackageInfo pi;
6316        if (ps.pkg != null) {
6317            pi = generatePackageInfo(ps, flags, userId);
6318        } else {
6319            pi = generatePackageInfo(ps, flags, userId);
6320        }
6321        // The above might return null in cases of uninstalled apps or install-state
6322        // skew across users/profiles.
6323        if (pi != null) {
6324            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6325                if (numMatch == permissions.length) {
6326                    pi.requestedPermissions = permissions;
6327                } else {
6328                    pi.requestedPermissions = new String[numMatch];
6329                    numMatch = 0;
6330                    for (int i=0; i<permissions.length; i++) {
6331                        if (tmp[i]) {
6332                            pi.requestedPermissions[numMatch] = permissions[i];
6333                            numMatch++;
6334                        }
6335                    }
6336                }
6337            }
6338            list.add(pi);
6339        }
6340    }
6341
6342    @Override
6343    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6344            String[] permissions, int flags, int userId) {
6345        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6346        flags = updateFlagsForPackage(flags, userId, permissions);
6347        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6348
6349        // writer
6350        synchronized (mPackages) {
6351            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6352            boolean[] tmpBools = new boolean[permissions.length];
6353            if (listUninstalled) {
6354                for (PackageSetting ps : mSettings.mPackages.values()) {
6355                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6356                }
6357            } else {
6358                for (PackageParser.Package pkg : mPackages.values()) {
6359                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6360                    if (ps != null) {
6361                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6362                                userId);
6363                    }
6364                }
6365            }
6366
6367            return new ParceledListSlice<PackageInfo>(list);
6368        }
6369    }
6370
6371    @Override
6372    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6373        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6374        flags = updateFlagsForApplication(flags, userId, null);
6375        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6376
6377        // writer
6378        synchronized (mPackages) {
6379            ArrayList<ApplicationInfo> list;
6380            if (listUninstalled) {
6381                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6382                for (PackageSetting ps : mSettings.mPackages.values()) {
6383                    ApplicationInfo ai;
6384                    if (ps.pkg != null) {
6385                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6386                                ps.readUserState(userId), userId);
6387                    } else {
6388                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6389                    }
6390                    if (ai != null) {
6391                        list.add(ai);
6392                    }
6393                }
6394            } else {
6395                list = new ArrayList<ApplicationInfo>(mPackages.size());
6396                for (PackageParser.Package p : mPackages.values()) {
6397                    if (p.mExtras != null) {
6398                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6399                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6400                        if (ai != null) {
6401                            list.add(ai);
6402                        }
6403                    }
6404                }
6405            }
6406
6407            return new ParceledListSlice<ApplicationInfo>(list);
6408        }
6409    }
6410
6411    @Override
6412    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6413        if (DISABLE_EPHEMERAL_APPS) {
6414            return null;
6415        }
6416
6417        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6418                "getEphemeralApplications");
6419        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6420                true /* requireFullPermission */, false /* checkShell */,
6421                "getEphemeralApplications");
6422        synchronized (mPackages) {
6423            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6424                    .getEphemeralApplicationsLPw(userId);
6425            if (ephemeralApps != null) {
6426                return new ParceledListSlice<>(ephemeralApps);
6427            }
6428        }
6429        return null;
6430    }
6431
6432    @Override
6433    public boolean isEphemeralApplication(String packageName, int userId) {
6434        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6435                true /* requireFullPermission */, false /* checkShell */,
6436                "isEphemeral");
6437        if (DISABLE_EPHEMERAL_APPS) {
6438            return false;
6439        }
6440
6441        if (!isCallerSameApp(packageName)) {
6442            return false;
6443        }
6444        synchronized (mPackages) {
6445            PackageParser.Package pkg = mPackages.get(packageName);
6446            if (pkg != null) {
6447                return pkg.applicationInfo.isEphemeralApp();
6448            }
6449        }
6450        return false;
6451    }
6452
6453    @Override
6454    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6455        if (DISABLE_EPHEMERAL_APPS) {
6456            return null;
6457        }
6458
6459        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6460                true /* requireFullPermission */, false /* checkShell */,
6461                "getCookie");
6462        if (!isCallerSameApp(packageName)) {
6463            return null;
6464        }
6465        synchronized (mPackages) {
6466            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6467                    packageName, userId);
6468        }
6469    }
6470
6471    @Override
6472    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6473        if (DISABLE_EPHEMERAL_APPS) {
6474            return true;
6475        }
6476
6477        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6478                true /* requireFullPermission */, true /* checkShell */,
6479                "setCookie");
6480        if (!isCallerSameApp(packageName)) {
6481            return false;
6482        }
6483        synchronized (mPackages) {
6484            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6485                    packageName, cookie, userId);
6486        }
6487    }
6488
6489    @Override
6490    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6491        if (DISABLE_EPHEMERAL_APPS) {
6492            return null;
6493        }
6494
6495        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6496                "getEphemeralApplicationIcon");
6497        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6498                true /* requireFullPermission */, false /* checkShell */,
6499                "getEphemeralApplicationIcon");
6500        synchronized (mPackages) {
6501            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6502                    packageName, userId);
6503        }
6504    }
6505
6506    private boolean isCallerSameApp(String packageName) {
6507        PackageParser.Package pkg = mPackages.get(packageName);
6508        return pkg != null
6509                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6510    }
6511
6512    @Override
6513    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6514        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6515    }
6516
6517    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6518        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6519
6520        // reader
6521        synchronized (mPackages) {
6522            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6523            final int userId = UserHandle.getCallingUserId();
6524            while (i.hasNext()) {
6525                final PackageParser.Package p = i.next();
6526                if (p.applicationInfo == null) continue;
6527
6528                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6529                        && !p.applicationInfo.isDirectBootAware();
6530                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6531                        && p.applicationInfo.isDirectBootAware();
6532
6533                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6534                        && (!mSafeMode || isSystemApp(p))
6535                        && (matchesUnaware || matchesAware)) {
6536                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6537                    if (ps != null) {
6538                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6539                                ps.readUserState(userId), userId);
6540                        if (ai != null) {
6541                            finalList.add(ai);
6542                        }
6543                    }
6544                }
6545            }
6546        }
6547
6548        return finalList;
6549    }
6550
6551    @Override
6552    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6553        if (!sUserManager.exists(userId)) return null;
6554        flags = updateFlagsForComponent(flags, userId, name);
6555        // reader
6556        synchronized (mPackages) {
6557            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6558            PackageSetting ps = provider != null
6559                    ? mSettings.mPackages.get(provider.owner.packageName)
6560                    : null;
6561            return ps != null
6562                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6563                    ? PackageParser.generateProviderInfo(provider, flags,
6564                            ps.readUserState(userId), userId)
6565                    : null;
6566        }
6567    }
6568
6569    /**
6570     * @deprecated
6571     */
6572    @Deprecated
6573    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6574        // reader
6575        synchronized (mPackages) {
6576            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6577                    .entrySet().iterator();
6578            final int userId = UserHandle.getCallingUserId();
6579            while (i.hasNext()) {
6580                Map.Entry<String, PackageParser.Provider> entry = i.next();
6581                PackageParser.Provider p = entry.getValue();
6582                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6583
6584                if (ps != null && p.syncable
6585                        && (!mSafeMode || (p.info.applicationInfo.flags
6586                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6587                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6588                            ps.readUserState(userId), userId);
6589                    if (info != null) {
6590                        outNames.add(entry.getKey());
6591                        outInfo.add(info);
6592                    }
6593                }
6594            }
6595        }
6596    }
6597
6598    @Override
6599    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6600            int uid, int flags) {
6601        final int userId = processName != null ? UserHandle.getUserId(uid)
6602                : UserHandle.getCallingUserId();
6603        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6604        flags = updateFlagsForComponent(flags, userId, processName);
6605
6606        ArrayList<ProviderInfo> finalList = null;
6607        // reader
6608        synchronized (mPackages) {
6609            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6610            while (i.hasNext()) {
6611                final PackageParser.Provider p = i.next();
6612                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6613                if (ps != null && p.info.authority != null
6614                        && (processName == null
6615                                || (p.info.processName.equals(processName)
6616                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6617                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6618                    if (finalList == null) {
6619                        finalList = new ArrayList<ProviderInfo>(3);
6620                    }
6621                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6622                            ps.readUserState(userId), userId);
6623                    if (info != null) {
6624                        finalList.add(info);
6625                    }
6626                }
6627            }
6628        }
6629
6630        if (finalList != null) {
6631            Collections.sort(finalList, mProviderInitOrderSorter);
6632            return new ParceledListSlice<ProviderInfo>(finalList);
6633        }
6634
6635        return ParceledListSlice.emptyList();
6636    }
6637
6638    @Override
6639    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6640        // reader
6641        synchronized (mPackages) {
6642            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6643            return PackageParser.generateInstrumentationInfo(i, flags);
6644        }
6645    }
6646
6647    @Override
6648    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6649            String targetPackage, int flags) {
6650        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6651    }
6652
6653    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6654            int flags) {
6655        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6656
6657        // reader
6658        synchronized (mPackages) {
6659            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6660            while (i.hasNext()) {
6661                final PackageParser.Instrumentation p = i.next();
6662                if (targetPackage == null
6663                        || targetPackage.equals(p.info.targetPackage)) {
6664                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6665                            flags);
6666                    if (ii != null) {
6667                        finalList.add(ii);
6668                    }
6669                }
6670            }
6671        }
6672
6673        return finalList;
6674    }
6675
6676    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6677        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6678        if (overlays == null) {
6679            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6680            return;
6681        }
6682        for (PackageParser.Package opkg : overlays.values()) {
6683            // Not much to do if idmap fails: we already logged the error
6684            // and we certainly don't want to abort installation of pkg simply
6685            // because an overlay didn't fit properly. For these reasons,
6686            // ignore the return value of createIdmapForPackagePairLI.
6687            createIdmapForPackagePairLI(pkg, opkg);
6688        }
6689    }
6690
6691    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6692            PackageParser.Package opkg) {
6693        if (!opkg.mTrustedOverlay) {
6694            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6695                    opkg.baseCodePath + ": overlay not trusted");
6696            return false;
6697        }
6698        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6699        if (overlaySet == null) {
6700            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6701                    opkg.baseCodePath + " but target package has no known overlays");
6702            return false;
6703        }
6704        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6705        // TODO: generate idmap for split APKs
6706        try {
6707            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6708        } catch (InstallerException e) {
6709            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6710                    + opkg.baseCodePath);
6711            return false;
6712        }
6713        PackageParser.Package[] overlayArray =
6714            overlaySet.values().toArray(new PackageParser.Package[0]);
6715        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6716            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6717                return p1.mOverlayPriority - p2.mOverlayPriority;
6718            }
6719        };
6720        Arrays.sort(overlayArray, cmp);
6721
6722        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6723        int i = 0;
6724        for (PackageParser.Package p : overlayArray) {
6725            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6726        }
6727        return true;
6728    }
6729
6730    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6731        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6732        try {
6733            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6734        } finally {
6735            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6736        }
6737    }
6738
6739    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6740        final File[] files = dir.listFiles();
6741        if (ArrayUtils.isEmpty(files)) {
6742            Log.d(TAG, "No files in app dir " + dir);
6743            return;
6744        }
6745
6746        if (DEBUG_PACKAGE_SCANNING) {
6747            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6748                    + " flags=0x" + Integer.toHexString(parseFlags));
6749        }
6750
6751        for (File file : files) {
6752            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6753                    && !PackageInstallerService.isStageName(file.getName());
6754            if (!isPackage) {
6755                // Ignore entries which are not packages
6756                continue;
6757            }
6758            try {
6759                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6760                        scanFlags, currentTime, null);
6761            } catch (PackageManagerException e) {
6762                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6763
6764                // Delete invalid userdata apps
6765                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6766                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6767                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6768                    removeCodePathLI(file);
6769                }
6770            }
6771        }
6772    }
6773
6774    private static File getSettingsProblemFile() {
6775        File dataDir = Environment.getDataDirectory();
6776        File systemDir = new File(dataDir, "system");
6777        File fname = new File(systemDir, "uiderrors.txt");
6778        return fname;
6779    }
6780
6781    static void reportSettingsProblem(int priority, String msg) {
6782        logCriticalInfo(priority, msg);
6783    }
6784
6785    static void logCriticalInfo(int priority, String msg) {
6786        Slog.println(priority, TAG, msg);
6787        EventLogTags.writePmCriticalInfo(msg);
6788        try {
6789            File fname = getSettingsProblemFile();
6790            FileOutputStream out = new FileOutputStream(fname, true);
6791            PrintWriter pw = new FastPrintWriter(out);
6792            SimpleDateFormat formatter = new SimpleDateFormat();
6793            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6794            pw.println(dateString + ": " + msg);
6795            pw.close();
6796            FileUtils.setPermissions(
6797                    fname.toString(),
6798                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6799                    -1, -1);
6800        } catch (java.io.IOException e) {
6801        }
6802    }
6803
6804    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6805        if (srcFile.isDirectory()) {
6806            final File baseFile = new File(pkg.baseCodePath);
6807            long maxModifiedTime = baseFile.lastModified();
6808            if (pkg.splitCodePaths != null) {
6809                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6810                    final File splitFile = new File(pkg.splitCodePaths[i]);
6811                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6812                }
6813            }
6814            return maxModifiedTime;
6815        }
6816        return srcFile.lastModified();
6817    }
6818
6819    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6820            final int policyFlags) throws PackageManagerException {
6821        if (ps != null
6822                && ps.codePath.equals(srcFile)
6823                && ps.timeStamp == getLastModifiedTime(pkg, srcFile)
6824                && !isCompatSignatureUpdateNeeded(pkg)
6825                && !isRecoverSignatureUpdateNeeded(pkg)) {
6826            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6827            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6828            ArraySet<PublicKey> signingKs;
6829            synchronized (mPackages) {
6830                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6831            }
6832            if (ps.signatures.mSignatures != null
6833                    && ps.signatures.mSignatures.length != 0
6834                    && signingKs != null) {
6835                // Optimization: reuse the existing cached certificates
6836                // if the package appears to be unchanged.
6837                pkg.mSignatures = ps.signatures.mSignatures;
6838                pkg.mSigningKeys = signingKs;
6839                return;
6840            }
6841
6842            Slog.w(TAG, "PackageSetting for " + ps.name
6843                    + " is missing signatures.  Collecting certs again to recover them.");
6844        } else {
6845            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6846        }
6847
6848        try {
6849            PackageParser.collectCertificates(pkg, policyFlags);
6850        } catch (PackageParserException e) {
6851            throw PackageManagerException.from(e);
6852        }
6853    }
6854
6855    /**
6856     *  Traces a package scan.
6857     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6858     */
6859    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6860            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6861        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6862        try {
6863            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6864        } finally {
6865            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6866        }
6867    }
6868
6869    /**
6870     *  Scans a package and returns the newly parsed package.
6871     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6872     */
6873    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6874            long currentTime, UserHandle user) throws PackageManagerException {
6875        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6876        PackageParser pp = new PackageParser();
6877        pp.setSeparateProcesses(mSeparateProcesses);
6878        pp.setOnlyCoreApps(mOnlyCore);
6879        pp.setDisplayMetrics(mMetrics);
6880
6881        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6882            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6883        }
6884
6885        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6886        final PackageParser.Package pkg;
6887        try {
6888            pkg = pp.parsePackage(scanFile, parseFlags);
6889        } catch (PackageParserException e) {
6890            throw PackageManagerException.from(e);
6891        } finally {
6892            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6893        }
6894
6895        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6896    }
6897
6898    /**
6899     *  Scans a package and returns the newly parsed package.
6900     *  @throws PackageManagerException on a parse error.
6901     */
6902    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6903            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6904            throws PackageManagerException {
6905        // If the package has children and this is the first dive in the function
6906        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6907        // packages (parent and children) would be successfully scanned before the
6908        // actual scan since scanning mutates internal state and we want to atomically
6909        // install the package and its children.
6910        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6911            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6912                scanFlags |= SCAN_CHECK_ONLY;
6913            }
6914        } else {
6915            scanFlags &= ~SCAN_CHECK_ONLY;
6916        }
6917
6918        // Scan the parent
6919        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6920                scanFlags, currentTime, user);
6921
6922        // Scan the children
6923        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6924        for (int i = 0; i < childCount; i++) {
6925            PackageParser.Package childPackage = pkg.childPackages.get(i);
6926            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6927                    currentTime, user);
6928        }
6929
6930
6931        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6932            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6933        }
6934
6935        return scannedPkg;
6936    }
6937
6938    /**
6939     *  Scans a package and returns the newly parsed package.
6940     *  @throws PackageManagerException on a parse error.
6941     */
6942    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6943            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6944            throws PackageManagerException {
6945        PackageSetting ps = null;
6946        PackageSetting updatedPkg;
6947        // reader
6948        synchronized (mPackages) {
6949            // Look to see if we already know about this package.
6950            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6951            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6952                // This package has been renamed to its original name.  Let's
6953                // use that.
6954                ps = mSettings.peekPackageLPr(oldName);
6955            }
6956            // If there was no original package, see one for the real package name.
6957            if (ps == null) {
6958                ps = mSettings.peekPackageLPr(pkg.packageName);
6959            }
6960            // Check to see if this package could be hiding/updating a system
6961            // package.  Must look for it either under the original or real
6962            // package name depending on our state.
6963            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6964            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6965
6966            // If this is a package we don't know about on the system partition, we
6967            // may need to remove disabled child packages on the system partition
6968            // or may need to not add child packages if the parent apk is updated
6969            // on the data partition and no longer defines this child package.
6970            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6971                // If this is a parent package for an updated system app and this system
6972                // app got an OTA update which no longer defines some of the child packages
6973                // we have to prune them from the disabled system packages.
6974                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6975                if (disabledPs != null) {
6976                    final int scannedChildCount = (pkg.childPackages != null)
6977                            ? pkg.childPackages.size() : 0;
6978                    final int disabledChildCount = disabledPs.childPackageNames != null
6979                            ? disabledPs.childPackageNames.size() : 0;
6980                    for (int i = 0; i < disabledChildCount; i++) {
6981                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6982                        boolean disabledPackageAvailable = false;
6983                        for (int j = 0; j < scannedChildCount; j++) {
6984                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6985                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6986                                disabledPackageAvailable = true;
6987                                break;
6988                            }
6989                         }
6990                         if (!disabledPackageAvailable) {
6991                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6992                         }
6993                    }
6994                }
6995            }
6996        }
6997
6998        boolean updatedPkgBetter = false;
6999        // First check if this is a system package that may involve an update
7000        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7001            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7002            // it needs to drop FLAG_PRIVILEGED.
7003            if (locationIsPrivileged(scanFile)) {
7004                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7005            } else {
7006                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7007            }
7008
7009            if (ps != null && !ps.codePath.equals(scanFile)) {
7010                // The path has changed from what was last scanned...  check the
7011                // version of the new path against what we have stored to determine
7012                // what to do.
7013                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7014                if (pkg.mVersionCode <= ps.versionCode) {
7015                    // The system package has been updated and the code path does not match
7016                    // Ignore entry. Skip it.
7017                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7018                            + " ignored: updated version " + ps.versionCode
7019                            + " better than this " + pkg.mVersionCode);
7020                    if (!updatedPkg.codePath.equals(scanFile)) {
7021                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7022                                + ps.name + " changing from " + updatedPkg.codePathString
7023                                + " to " + scanFile);
7024                        updatedPkg.codePath = scanFile;
7025                        updatedPkg.codePathString = scanFile.toString();
7026                        updatedPkg.resourcePath = scanFile;
7027                        updatedPkg.resourcePathString = scanFile.toString();
7028                    }
7029                    updatedPkg.pkg = pkg;
7030                    updatedPkg.versionCode = pkg.mVersionCode;
7031
7032                    // Update the disabled system child packages to point to the package too.
7033                    final int childCount = updatedPkg.childPackageNames != null
7034                            ? updatedPkg.childPackageNames.size() : 0;
7035                    for (int i = 0; i < childCount; i++) {
7036                        String childPackageName = updatedPkg.childPackageNames.get(i);
7037                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7038                                childPackageName);
7039                        if (updatedChildPkg != null) {
7040                            updatedChildPkg.pkg = pkg;
7041                            updatedChildPkg.versionCode = pkg.mVersionCode;
7042                        }
7043                    }
7044
7045                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7046                            + scanFile + " ignored: updated version " + ps.versionCode
7047                            + " better than this " + pkg.mVersionCode);
7048                } else {
7049                    // The current app on the system partition is better than
7050                    // what we have updated to on the data partition; switch
7051                    // back to the system partition version.
7052                    // At this point, its safely assumed that package installation for
7053                    // apps in system partition will go through. If not there won't be a working
7054                    // version of the app
7055                    // writer
7056                    synchronized (mPackages) {
7057                        // Just remove the loaded entries from package lists.
7058                        mPackages.remove(ps.name);
7059                    }
7060
7061                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7062                            + " reverting from " + ps.codePathString
7063                            + ": new version " + pkg.mVersionCode
7064                            + " better than installed " + ps.versionCode);
7065
7066                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7067                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7068                    synchronized (mInstallLock) {
7069                        args.cleanUpResourcesLI();
7070                    }
7071                    synchronized (mPackages) {
7072                        mSettings.enableSystemPackageLPw(ps.name);
7073                    }
7074                    updatedPkgBetter = true;
7075                }
7076            }
7077        }
7078
7079        if (updatedPkg != null) {
7080            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7081            // initially
7082            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7083
7084            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7085            // flag set initially
7086            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7087                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7088            }
7089        }
7090
7091        // Verify certificates against what was last scanned
7092        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7093
7094        /*
7095         * A new system app appeared, but we already had a non-system one of the
7096         * same name installed earlier.
7097         */
7098        boolean shouldHideSystemApp = false;
7099        if (updatedPkg == null && ps != null
7100                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7101            /*
7102             * Check to make sure the signatures match first. If they don't,
7103             * wipe the installed application and its data.
7104             */
7105            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7106                    != PackageManager.SIGNATURE_MATCH) {
7107                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7108                        + " signatures don't match existing userdata copy; removing");
7109                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7110                        "scanPackageInternalLI")) {
7111                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7112                }
7113                ps = null;
7114            } else {
7115                /*
7116                 * If the newly-added system app is an older version than the
7117                 * already installed version, hide it. It will be scanned later
7118                 * and re-added like an update.
7119                 */
7120                if (pkg.mVersionCode <= ps.versionCode) {
7121                    shouldHideSystemApp = true;
7122                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7123                            + " but new version " + pkg.mVersionCode + " better than installed "
7124                            + ps.versionCode + "; hiding system");
7125                } else {
7126                    /*
7127                     * The newly found system app is a newer version that the
7128                     * one previously installed. Simply remove the
7129                     * already-installed application and replace it with our own
7130                     * while keeping the application data.
7131                     */
7132                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7133                            + " reverting from " + ps.codePathString + ": new version "
7134                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7135                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7136                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7137                    synchronized (mInstallLock) {
7138                        args.cleanUpResourcesLI();
7139                    }
7140                }
7141            }
7142        }
7143
7144        // The apk is forward locked (not public) if its code and resources
7145        // are kept in different files. (except for app in either system or
7146        // vendor path).
7147        // TODO grab this value from PackageSettings
7148        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7149            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7150                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7151            }
7152        }
7153
7154        // TODO: extend to support forward-locked splits
7155        String resourcePath = null;
7156        String baseResourcePath = null;
7157        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7158            if (ps != null && ps.resourcePathString != null) {
7159                resourcePath = ps.resourcePathString;
7160                baseResourcePath = ps.resourcePathString;
7161            } else {
7162                // Should not happen at all. Just log an error.
7163                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7164            }
7165        } else {
7166            resourcePath = pkg.codePath;
7167            baseResourcePath = pkg.baseCodePath;
7168        }
7169
7170        // Set application objects path explicitly.
7171        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7172        pkg.setApplicationInfoCodePath(pkg.codePath);
7173        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7174        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7175        pkg.setApplicationInfoResourcePath(resourcePath);
7176        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7177        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7178
7179        // Note that we invoke the following method only if we are about to unpack an application
7180        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7181                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7182
7183        /*
7184         * If the system app should be overridden by a previously installed
7185         * data, hide the system app now and let the /data/app scan pick it up
7186         * again.
7187         */
7188        if (shouldHideSystemApp) {
7189            synchronized (mPackages) {
7190                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7191            }
7192        }
7193
7194        return scannedPkg;
7195    }
7196
7197    private static String fixProcessName(String defProcessName,
7198            String processName, int uid) {
7199        if (processName == null) {
7200            return defProcessName;
7201        }
7202        return processName;
7203    }
7204
7205    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7206            throws PackageManagerException {
7207        if (pkgSetting.signatures.mSignatures != null) {
7208            // Already existing package. Make sure signatures match
7209            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7210                    == PackageManager.SIGNATURE_MATCH;
7211            if (!match) {
7212                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7213                        == PackageManager.SIGNATURE_MATCH;
7214            }
7215            if (!match) {
7216                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7217                        == PackageManager.SIGNATURE_MATCH;
7218            }
7219            if (!match) {
7220                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7221                        + pkg.packageName + " signatures do not match the "
7222                        + "previously installed version; ignoring!");
7223            }
7224        }
7225
7226        // Check for shared user signatures
7227        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7228            // Already existing package. Make sure signatures match
7229            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7230                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7231            if (!match) {
7232                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7233                        == PackageManager.SIGNATURE_MATCH;
7234            }
7235            if (!match) {
7236                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7237                        == PackageManager.SIGNATURE_MATCH;
7238            }
7239            if (!match) {
7240                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7241                        "Package " + pkg.packageName
7242                        + " has no signatures that match those in shared user "
7243                        + pkgSetting.sharedUser.name + "; ignoring!");
7244            }
7245        }
7246    }
7247
7248    /**
7249     * Enforces that only the system UID or root's UID can call a method exposed
7250     * via Binder.
7251     *
7252     * @param message used as message if SecurityException is thrown
7253     * @throws SecurityException if the caller is not system or root
7254     */
7255    private static final void enforceSystemOrRoot(String message) {
7256        final int uid = Binder.getCallingUid();
7257        if (uid != Process.SYSTEM_UID && uid != 0) {
7258            throw new SecurityException(message);
7259        }
7260    }
7261
7262    @Override
7263    public void performFstrimIfNeeded() {
7264        enforceSystemOrRoot("Only the system can request fstrim");
7265
7266        // Before everything else, see whether we need to fstrim.
7267        try {
7268            IMountService ms = PackageHelper.getMountService();
7269            if (ms != null) {
7270                boolean doTrim = false;
7271                final long interval = android.provider.Settings.Global.getLong(
7272                        mContext.getContentResolver(),
7273                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7274                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7275                if (interval > 0) {
7276                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7277                    if (timeSinceLast > interval) {
7278                        doTrim = true;
7279                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7280                                + "; running immediately");
7281                    }
7282                }
7283                if (doTrim) {
7284                    if (!isFirstBoot()) {
7285                        try {
7286                            ActivityManagerNative.getDefault().showBootMessage(
7287                                    mContext.getResources().getString(
7288                                            R.string.android_upgrading_fstrim), true);
7289                        } catch (RemoteException e) {
7290                        }
7291                    }
7292                    ms.runMaintenance();
7293                }
7294            } else {
7295                Slog.e(TAG, "Mount service unavailable!");
7296            }
7297        } catch (RemoteException e) {
7298            // Can't happen; MountService is local
7299        }
7300    }
7301
7302    @Override
7303    public void updatePackagesIfNeeded() {
7304        enforceSystemOrRoot("Only the system can request package update");
7305
7306        // We need to re-extract after an OTA.
7307        boolean causeUpgrade = isUpgrade();
7308
7309        // First boot or factory reset.
7310        // Note: we also handle devices that are upgrading to N right now as if it is their
7311        //       first boot, as they do not have profile data.
7312        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7313
7314        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7315        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7316
7317        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7318            return;
7319        }
7320
7321        List<PackageParser.Package> pkgs;
7322        synchronized (mPackages) {
7323            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7324        }
7325
7326        final long startTime = System.nanoTime();
7327        final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */,
7328                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7329
7330        final int elapsedTimeSeconds =
7331                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7332
7333        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7334        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7335        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7336        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7337        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7338    }
7339
7340    /**
7341     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7342     * containing statistics about the invocation. The array consists of three elements,
7343     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7344     * and {@code numberOfPackagesFailed}.
7345     */
7346    private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog,
7347            String compilerFilter) {
7348
7349        int numberOfPackagesVisited = 0;
7350        int numberOfPackagesOptimized = 0;
7351        int numberOfPackagesSkipped = 0;
7352        int numberOfPackagesFailed = 0;
7353        final int numberOfPackagesToDexopt = pkgs.size();
7354
7355        for (PackageParser.Package pkg : pkgs) {
7356            numberOfPackagesVisited++;
7357
7358            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7359                if (DEBUG_DEXOPT) {
7360                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7361                }
7362                numberOfPackagesSkipped++;
7363                continue;
7364            }
7365
7366            if (DEBUG_DEXOPT) {
7367                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7368                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7369            }
7370
7371            if (showDialog) {
7372                try {
7373                    ActivityManagerNative.getDefault().showBootMessage(
7374                            mContext.getResources().getString(R.string.android_upgrading_apk,
7375                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7376                } catch (RemoteException e) {
7377                }
7378            }
7379
7380            // checkProfiles is false to avoid merging profiles during boot which
7381            // might interfere with background compilation (b/28612421).
7382            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7383            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7384            // trade-off worth doing to save boot time work.
7385            int dexOptStatus = performDexOptTraced(pkg.packageName,
7386                    false /* checkProfiles */,
7387                    compilerFilter,
7388                    false /* force */);
7389            switch (dexOptStatus) {
7390                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7391                    numberOfPackagesOptimized++;
7392                    break;
7393                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7394                    numberOfPackagesSkipped++;
7395                    break;
7396                case PackageDexOptimizer.DEX_OPT_FAILED:
7397                    numberOfPackagesFailed++;
7398                    break;
7399                default:
7400                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7401                    break;
7402            }
7403        }
7404
7405        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7406                numberOfPackagesFailed };
7407    }
7408
7409    @Override
7410    public void notifyPackageUse(String packageName, int reason) {
7411        synchronized (mPackages) {
7412            PackageParser.Package p = mPackages.get(packageName);
7413            if (p == null) {
7414                return;
7415            }
7416            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7417        }
7418    }
7419
7420    // TODO: this is not used nor needed. Delete it.
7421    @Override
7422    public boolean performDexOptIfNeeded(String packageName) {
7423        int dexOptStatus = performDexOptTraced(packageName,
7424                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7425        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7426    }
7427
7428    @Override
7429    public boolean performDexOpt(String packageName,
7430            boolean checkProfiles, int compileReason, boolean force) {
7431        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7432                getCompilerFilterForReason(compileReason), force);
7433        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7434    }
7435
7436    @Override
7437    public boolean performDexOptMode(String packageName,
7438            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7439        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7440                targetCompilerFilter, force);
7441        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7442    }
7443
7444    private int performDexOptTraced(String packageName,
7445                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7446        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7447        try {
7448            return performDexOptInternal(packageName, checkProfiles,
7449                    targetCompilerFilter, force);
7450        } finally {
7451            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7452        }
7453    }
7454
7455    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7456    // if the package can now be considered up to date for the given filter.
7457    private int performDexOptInternal(String packageName,
7458                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7459        PackageParser.Package p;
7460        synchronized (mPackages) {
7461            p = mPackages.get(packageName);
7462            if (p == null) {
7463                // Package could not be found. Report failure.
7464                return PackageDexOptimizer.DEX_OPT_FAILED;
7465            }
7466            mPackageUsage.write(false);
7467        }
7468        long callingId = Binder.clearCallingIdentity();
7469        try {
7470            synchronized (mInstallLock) {
7471                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7472                        targetCompilerFilter, force);
7473            }
7474        } finally {
7475            Binder.restoreCallingIdentity(callingId);
7476        }
7477    }
7478
7479    public ArraySet<String> getOptimizablePackages() {
7480        ArraySet<String> pkgs = new ArraySet<String>();
7481        synchronized (mPackages) {
7482            for (PackageParser.Package p : mPackages.values()) {
7483                if (PackageDexOptimizer.canOptimizePackage(p)) {
7484                    pkgs.add(p.packageName);
7485                }
7486            }
7487        }
7488        return pkgs;
7489    }
7490
7491    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7492            boolean checkProfiles, String targetCompilerFilter,
7493            boolean force) {
7494        // Select the dex optimizer based on the force parameter.
7495        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7496        //       allocate an object here.
7497        PackageDexOptimizer pdo = force
7498                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7499                : mPackageDexOptimizer;
7500
7501        // Optimize all dependencies first. Note: we ignore the return value and march on
7502        // on errors.
7503        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7504        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7505        if (!deps.isEmpty()) {
7506            for (PackageParser.Package depPackage : deps) {
7507                // TODO: Analyze and investigate if we (should) profile libraries.
7508                // Currently this will do a full compilation of the library by default.
7509                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7510                        false /* checkProfiles */,
7511                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7512            }
7513        }
7514        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7515                targetCompilerFilter);
7516    }
7517
7518    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7519        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7520            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7521            Set<String> collectedNames = new HashSet<>();
7522            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7523
7524            retValue.remove(p);
7525
7526            return retValue;
7527        } else {
7528            return Collections.emptyList();
7529        }
7530    }
7531
7532    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7533            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7534        if (!collectedNames.contains(p.packageName)) {
7535            collectedNames.add(p.packageName);
7536            collected.add(p);
7537
7538            if (p.usesLibraries != null) {
7539                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7540            }
7541            if (p.usesOptionalLibraries != null) {
7542                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7543                        collectedNames);
7544            }
7545        }
7546    }
7547
7548    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7549            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7550        for (String libName : libs) {
7551            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7552            if (libPkg != null) {
7553                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7554            }
7555        }
7556    }
7557
7558    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7559        synchronized (mPackages) {
7560            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7561            if (lib != null && lib.apk != null) {
7562                return mPackages.get(lib.apk);
7563            }
7564        }
7565        return null;
7566    }
7567
7568    public void shutdown() {
7569        mPackageUsage.write(true);
7570    }
7571
7572    @Override
7573    public void dumpProfiles(String packageName) {
7574        PackageParser.Package pkg;
7575        synchronized (mPackages) {
7576            pkg = mPackages.get(packageName);
7577            if (pkg == null) {
7578                throw new IllegalArgumentException("Unknown package: " + packageName);
7579            }
7580        }
7581        /* Only the shell, root, or the app user should be able to dump profiles. */
7582        int callingUid = Binder.getCallingUid();
7583        if (callingUid != Process.SHELL_UID &&
7584            callingUid != Process.ROOT_UID &&
7585            callingUid != pkg.applicationInfo.uid) {
7586            throw new SecurityException("dumpProfiles");
7587        }
7588
7589        synchronized (mInstallLock) {
7590            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7591            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7592            try {
7593                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7594                String gid = Integer.toString(sharedGid);
7595                String codePaths = TextUtils.join(";", allCodePaths);
7596                mInstaller.dumpProfiles(gid, packageName, codePaths);
7597            } catch (InstallerException e) {
7598                Slog.w(TAG, "Failed to dump profiles", e);
7599            }
7600            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7601        }
7602    }
7603
7604    @Override
7605    public void forceDexOpt(String packageName) {
7606        enforceSystemOrRoot("forceDexOpt");
7607
7608        PackageParser.Package pkg;
7609        synchronized (mPackages) {
7610            pkg = mPackages.get(packageName);
7611            if (pkg == null) {
7612                throw new IllegalArgumentException("Unknown package: " + packageName);
7613            }
7614        }
7615
7616        synchronized (mInstallLock) {
7617            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7618
7619            // Whoever is calling forceDexOpt wants a fully compiled package.
7620            // Don't use profiles since that may cause compilation to be skipped.
7621            final int res = performDexOptInternalWithDependenciesLI(pkg,
7622                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7623                    true /* force */);
7624
7625            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7626            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7627                throw new IllegalStateException("Failed to dexopt: " + res);
7628            }
7629        }
7630    }
7631
7632    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7633        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7634            Slog.w(TAG, "Unable to update from " + oldPkg.name
7635                    + " to " + newPkg.packageName
7636                    + ": old package not in system partition");
7637            return false;
7638        } else if (mPackages.get(oldPkg.name) != null) {
7639            Slog.w(TAG, "Unable to update from " + oldPkg.name
7640                    + " to " + newPkg.packageName
7641                    + ": old package still exists");
7642            return false;
7643        }
7644        return true;
7645    }
7646
7647    void removeCodePathLI(File codePath) {
7648        if (codePath.isDirectory()) {
7649            try {
7650                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7651            } catch (InstallerException e) {
7652                Slog.w(TAG, "Failed to remove code path", e);
7653            }
7654        } else {
7655            codePath.delete();
7656        }
7657    }
7658
7659    private int[] resolveUserIds(int userId) {
7660        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7661    }
7662
7663    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7664        if (pkg == null) {
7665            Slog.wtf(TAG, "Package was null!", new Throwable());
7666            return;
7667        }
7668        clearAppDataLeafLIF(pkg, userId, flags);
7669        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7670        for (int i = 0; i < childCount; i++) {
7671            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7672        }
7673    }
7674
7675    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7676        final PackageSetting ps;
7677        synchronized (mPackages) {
7678            ps = mSettings.mPackages.get(pkg.packageName);
7679        }
7680        for (int realUserId : resolveUserIds(userId)) {
7681            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7682            try {
7683                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7684                        ceDataInode);
7685            } catch (InstallerException e) {
7686                Slog.w(TAG, String.valueOf(e));
7687            }
7688        }
7689    }
7690
7691    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7692        if (pkg == null) {
7693            Slog.wtf(TAG, "Package was null!", new Throwable());
7694            return;
7695        }
7696        destroyAppDataLeafLIF(pkg, userId, flags);
7697        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7698        for (int i = 0; i < childCount; i++) {
7699            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7700        }
7701    }
7702
7703    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7704        final PackageSetting ps;
7705        synchronized (mPackages) {
7706            ps = mSettings.mPackages.get(pkg.packageName);
7707        }
7708        for (int realUserId : resolveUserIds(userId)) {
7709            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7710            try {
7711                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7712                        ceDataInode);
7713            } catch (InstallerException e) {
7714                Slog.w(TAG, String.valueOf(e));
7715            }
7716        }
7717    }
7718
7719    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7720        if (pkg == null) {
7721            Slog.wtf(TAG, "Package was null!", new Throwable());
7722            return;
7723        }
7724        destroyAppProfilesLeafLIF(pkg);
7725        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7726        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7727        for (int i = 0; i < childCount; i++) {
7728            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7729            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7730                    true /* removeBaseMarker */);
7731        }
7732    }
7733
7734    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7735            boolean removeBaseMarker) {
7736        if (pkg.isForwardLocked()) {
7737            return;
7738        }
7739
7740        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7741            try {
7742                path = PackageManagerServiceUtils.realpath(new File(path));
7743            } catch (IOException e) {
7744                // TODO: Should we return early here ?
7745                Slog.w(TAG, "Failed to get canonical path", e);
7746                continue;
7747            }
7748
7749            final String useMarker = path.replace('/', '@');
7750            for (int realUserId : resolveUserIds(userId)) {
7751                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7752                if (removeBaseMarker) {
7753                    File foreignUseMark = new File(profileDir, useMarker);
7754                    if (foreignUseMark.exists()) {
7755                        if (!foreignUseMark.delete()) {
7756                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7757                                    + pkg.packageName);
7758                        }
7759                    }
7760                }
7761
7762                File[] markers = profileDir.listFiles();
7763                if (markers != null) {
7764                    final String searchString = "@" + pkg.packageName + "@";
7765                    // We also delete all markers that contain the package name we're
7766                    // uninstalling. These are associated with secondary dex-files belonging
7767                    // to the package. Reconstructing the path of these dex files is messy
7768                    // in general.
7769                    for (File marker : markers) {
7770                        if (marker.getName().indexOf(searchString) > 0) {
7771                            if (!marker.delete()) {
7772                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7773                                    + pkg.packageName);
7774                            }
7775                        }
7776                    }
7777                }
7778            }
7779        }
7780    }
7781
7782    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7783        try {
7784            mInstaller.destroyAppProfiles(pkg.packageName);
7785        } catch (InstallerException e) {
7786            Slog.w(TAG, String.valueOf(e));
7787        }
7788    }
7789
7790    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7791        if (pkg == null) {
7792            Slog.wtf(TAG, "Package was null!", new Throwable());
7793            return;
7794        }
7795        clearAppProfilesLeafLIF(pkg);
7796        // We don't remove the base foreign use marker when clearing profiles because
7797        // we will rename it when the app is updated. Unlike the actual profile contents,
7798        // the foreign use marker is good across installs.
7799        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7800        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7801        for (int i = 0; i < childCount; i++) {
7802            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7803        }
7804    }
7805
7806    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7807        try {
7808            mInstaller.clearAppProfiles(pkg.packageName);
7809        } catch (InstallerException e) {
7810            Slog.w(TAG, String.valueOf(e));
7811        }
7812    }
7813
7814    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7815            long lastUpdateTime) {
7816        // Set parent install/update time
7817        PackageSetting ps = (PackageSetting) pkg.mExtras;
7818        if (ps != null) {
7819            ps.firstInstallTime = firstInstallTime;
7820            ps.lastUpdateTime = lastUpdateTime;
7821        }
7822        // Set children install/update time
7823        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7824        for (int i = 0; i < childCount; i++) {
7825            PackageParser.Package childPkg = pkg.childPackages.get(i);
7826            ps = (PackageSetting) childPkg.mExtras;
7827            if (ps != null) {
7828                ps.firstInstallTime = firstInstallTime;
7829                ps.lastUpdateTime = lastUpdateTime;
7830            }
7831        }
7832    }
7833
7834    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7835            PackageParser.Package changingLib) {
7836        if (file.path != null) {
7837            usesLibraryFiles.add(file.path);
7838            return;
7839        }
7840        PackageParser.Package p = mPackages.get(file.apk);
7841        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7842            // If we are doing this while in the middle of updating a library apk,
7843            // then we need to make sure to use that new apk for determining the
7844            // dependencies here.  (We haven't yet finished committing the new apk
7845            // to the package manager state.)
7846            if (p == null || p.packageName.equals(changingLib.packageName)) {
7847                p = changingLib;
7848            }
7849        }
7850        if (p != null) {
7851            usesLibraryFiles.addAll(p.getAllCodePaths());
7852        }
7853    }
7854
7855    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7856            PackageParser.Package changingLib) throws PackageManagerException {
7857        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7858            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7859            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7860            for (int i=0; i<N; i++) {
7861                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7862                if (file == null) {
7863                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7864                            "Package " + pkg.packageName + " requires unavailable shared library "
7865                            + pkg.usesLibraries.get(i) + "; failing!");
7866                }
7867                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7868            }
7869            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7870            for (int i=0; i<N; i++) {
7871                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7872                if (file == null) {
7873                    Slog.w(TAG, "Package " + pkg.packageName
7874                            + " desires unavailable shared library "
7875                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7876                } else {
7877                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7878                }
7879            }
7880            N = usesLibraryFiles.size();
7881            if (N > 0) {
7882                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7883            } else {
7884                pkg.usesLibraryFiles = null;
7885            }
7886        }
7887    }
7888
7889    private static boolean hasString(List<String> list, List<String> which) {
7890        if (list == null) {
7891            return false;
7892        }
7893        for (int i=list.size()-1; i>=0; i--) {
7894            for (int j=which.size()-1; j>=0; j--) {
7895                if (which.get(j).equals(list.get(i))) {
7896                    return true;
7897                }
7898            }
7899        }
7900        return false;
7901    }
7902
7903    private void updateAllSharedLibrariesLPw() {
7904        for (PackageParser.Package pkg : mPackages.values()) {
7905            try {
7906                updateSharedLibrariesLPw(pkg, null);
7907            } catch (PackageManagerException e) {
7908                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7909            }
7910        }
7911    }
7912
7913    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7914            PackageParser.Package changingPkg) {
7915        ArrayList<PackageParser.Package> res = null;
7916        for (PackageParser.Package pkg : mPackages.values()) {
7917            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7918                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7919                if (res == null) {
7920                    res = new ArrayList<PackageParser.Package>();
7921                }
7922                res.add(pkg);
7923                try {
7924                    updateSharedLibrariesLPw(pkg, changingPkg);
7925                } catch (PackageManagerException e) {
7926                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7927                }
7928            }
7929        }
7930        return res;
7931    }
7932
7933    /**
7934     * Derive the value of the {@code cpuAbiOverride} based on the provided
7935     * value and an optional stored value from the package settings.
7936     */
7937    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7938        String cpuAbiOverride = null;
7939
7940        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7941            cpuAbiOverride = null;
7942        } else if (abiOverride != null) {
7943            cpuAbiOverride = abiOverride;
7944        } else if (settings != null) {
7945            cpuAbiOverride = settings.cpuAbiOverrideString;
7946        }
7947
7948        return cpuAbiOverride;
7949    }
7950
7951    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7952            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7953                    throws PackageManagerException {
7954        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7955        // If the package has children and this is the first dive in the function
7956        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7957        // whether all packages (parent and children) would be successfully scanned
7958        // before the actual scan since scanning mutates internal state and we want
7959        // to atomically install the package and its children.
7960        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7961            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7962                scanFlags |= SCAN_CHECK_ONLY;
7963            }
7964        } else {
7965            scanFlags &= ~SCAN_CHECK_ONLY;
7966        }
7967
7968        final PackageParser.Package scannedPkg;
7969        try {
7970            // Scan the parent
7971            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7972            // Scan the children
7973            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7974            for (int i = 0; i < childCount; i++) {
7975                PackageParser.Package childPkg = pkg.childPackages.get(i);
7976                scanPackageLI(childPkg, policyFlags,
7977                        scanFlags, currentTime, user);
7978            }
7979        } finally {
7980            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7981        }
7982
7983        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7984            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7985        }
7986
7987        return scannedPkg;
7988    }
7989
7990    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7991            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7992        boolean success = false;
7993        try {
7994            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7995                    currentTime, user);
7996            success = true;
7997            return res;
7998        } finally {
7999            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8000                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8001                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8002                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8003                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8004            }
8005        }
8006    }
8007
8008    /**
8009     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8010     */
8011    private static boolean apkHasCode(String fileName) {
8012        StrictJarFile jarFile = null;
8013        try {
8014            jarFile = new StrictJarFile(fileName,
8015                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8016            return jarFile.findEntry("classes.dex") != null;
8017        } catch (IOException ignore) {
8018        } finally {
8019            try {
8020                if (jarFile != null) {
8021                    jarFile.close();
8022                }
8023            } catch (IOException ignore) {}
8024        }
8025        return false;
8026    }
8027
8028    /**
8029     * Enforces code policy for the package. This ensures that if an APK has
8030     * declared hasCode="true" in its manifest that the APK actually contains
8031     * code.
8032     *
8033     * @throws PackageManagerException If bytecode could not be found when it should exist
8034     */
8035    private static void enforceCodePolicy(PackageParser.Package pkg)
8036            throws PackageManagerException {
8037        final boolean shouldHaveCode =
8038                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8039        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8040            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8041                    "Package " + pkg.baseCodePath + " code is missing");
8042        }
8043
8044        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8045            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8046                final boolean splitShouldHaveCode =
8047                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8048                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8049                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8050                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8051                }
8052            }
8053        }
8054    }
8055
8056    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8057            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8058            throws PackageManagerException {
8059        final File scanFile = new File(pkg.codePath);
8060        if (pkg.applicationInfo.getCodePath() == null ||
8061                pkg.applicationInfo.getResourcePath() == null) {
8062            // Bail out. The resource and code paths haven't been set.
8063            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8064                    "Code and resource paths haven't been set correctly");
8065        }
8066
8067        // Apply policy
8068        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8069            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8070            if (pkg.applicationInfo.isDirectBootAware()) {
8071                // we're direct boot aware; set for all components
8072                for (PackageParser.Service s : pkg.services) {
8073                    s.info.encryptionAware = s.info.directBootAware = true;
8074                }
8075                for (PackageParser.Provider p : pkg.providers) {
8076                    p.info.encryptionAware = p.info.directBootAware = true;
8077                }
8078                for (PackageParser.Activity a : pkg.activities) {
8079                    a.info.encryptionAware = a.info.directBootAware = true;
8080                }
8081                for (PackageParser.Activity r : pkg.receivers) {
8082                    r.info.encryptionAware = r.info.directBootAware = true;
8083                }
8084            }
8085        } else {
8086            // Only allow system apps to be flagged as core apps.
8087            pkg.coreApp = false;
8088            // clear flags not applicable to regular apps
8089            pkg.applicationInfo.privateFlags &=
8090                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8091            pkg.applicationInfo.privateFlags &=
8092                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8093        }
8094        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8095
8096        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8097            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8098        }
8099
8100        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8101            enforceCodePolicy(pkg);
8102        }
8103
8104        if (mCustomResolverComponentName != null &&
8105                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8106            setUpCustomResolverActivity(pkg);
8107        }
8108
8109        if (pkg.packageName.equals("android")) {
8110            synchronized (mPackages) {
8111                if (mAndroidApplication != null) {
8112                    Slog.w(TAG, "*************************************************");
8113                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8114                    Slog.w(TAG, " file=" + scanFile);
8115                    Slog.w(TAG, "*************************************************");
8116                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8117                            "Core android package being redefined.  Skipping.");
8118                }
8119
8120                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8121                    // Set up information for our fall-back user intent resolution activity.
8122                    mPlatformPackage = pkg;
8123                    pkg.mVersionCode = mSdkVersion;
8124                    mAndroidApplication = pkg.applicationInfo;
8125
8126                    if (!mResolverReplaced) {
8127                        mResolveActivity.applicationInfo = mAndroidApplication;
8128                        mResolveActivity.name = ResolverActivity.class.getName();
8129                        mResolveActivity.packageName = mAndroidApplication.packageName;
8130                        mResolveActivity.processName = "system:ui";
8131                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8132                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8133                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8134                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8135                        mResolveActivity.exported = true;
8136                        mResolveActivity.enabled = true;
8137                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8138                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8139                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8140                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8141                                | ActivityInfo.CONFIG_ORIENTATION
8142                                | ActivityInfo.CONFIG_KEYBOARD
8143                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8144                        mResolveInfo.activityInfo = mResolveActivity;
8145                        mResolveInfo.priority = 0;
8146                        mResolveInfo.preferredOrder = 0;
8147                        mResolveInfo.match = 0;
8148                        mResolveComponentName = new ComponentName(
8149                                mAndroidApplication.packageName, mResolveActivity.name);
8150                    }
8151                }
8152            }
8153        }
8154
8155        if (DEBUG_PACKAGE_SCANNING) {
8156            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8157                Log.d(TAG, "Scanning package " + pkg.packageName);
8158        }
8159
8160        synchronized (mPackages) {
8161            if (mPackages.containsKey(pkg.packageName)
8162                    || mSharedLibraries.containsKey(pkg.packageName)) {
8163                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8164                        "Application package " + pkg.packageName
8165                                + " already installed.  Skipping duplicate.");
8166            }
8167
8168            // If we're only installing presumed-existing packages, require that the
8169            // scanned APK is both already known and at the path previously established
8170            // for it.  Previously unknown packages we pick up normally, but if we have an
8171            // a priori expectation about this package's install presence, enforce it.
8172            // With a singular exception for new system packages. When an OTA contains
8173            // a new system package, we allow the codepath to change from a system location
8174            // to the user-installed location. If we don't allow this change, any newer,
8175            // user-installed version of the application will be ignored.
8176            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8177                if (mExpectingBetter.containsKey(pkg.packageName)) {
8178                    logCriticalInfo(Log.WARN,
8179                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8180                } else {
8181                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8182                    if (known != null) {
8183                        if (DEBUG_PACKAGE_SCANNING) {
8184                            Log.d(TAG, "Examining " + pkg.codePath
8185                                    + " and requiring known paths " + known.codePathString
8186                                    + " & " + known.resourcePathString);
8187                        }
8188                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8189                                || !pkg.applicationInfo.getResourcePath().equals(
8190                                known.resourcePathString)) {
8191                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8192                                    "Application package " + pkg.packageName
8193                                            + " found at " + pkg.applicationInfo.getCodePath()
8194                                            + " but expected at " + known.codePathString
8195                                            + "; ignoring.");
8196                        }
8197                    }
8198                }
8199            }
8200        }
8201
8202        // Initialize package source and resource directories
8203        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8204        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8205
8206        SharedUserSetting suid = null;
8207        PackageSetting pkgSetting = null;
8208
8209        if (!isSystemApp(pkg)) {
8210            // Only system apps can use these features.
8211            pkg.mOriginalPackages = null;
8212            pkg.mRealPackage = null;
8213            pkg.mAdoptPermissions = null;
8214        }
8215
8216        // Getting the package setting may have a side-effect, so if we
8217        // are only checking if scan would succeed, stash a copy of the
8218        // old setting to restore at the end.
8219        PackageSetting nonMutatedPs = null;
8220
8221        // writer
8222        synchronized (mPackages) {
8223            if (pkg.mSharedUserId != null) {
8224                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8225                if (suid == null) {
8226                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8227                            "Creating application package " + pkg.packageName
8228                            + " for shared user failed");
8229                }
8230                if (DEBUG_PACKAGE_SCANNING) {
8231                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8232                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8233                                + "): packages=" + suid.packages);
8234                }
8235            }
8236
8237            // Check if we are renaming from an original package name.
8238            PackageSetting origPackage = null;
8239            String realName = null;
8240            if (pkg.mOriginalPackages != null) {
8241                // This package may need to be renamed to a previously
8242                // installed name.  Let's check on that...
8243                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8244                if (pkg.mOriginalPackages.contains(renamed)) {
8245                    // This package had originally been installed as the
8246                    // original name, and we have already taken care of
8247                    // transitioning to the new one.  Just update the new
8248                    // one to continue using the old name.
8249                    realName = pkg.mRealPackage;
8250                    if (!pkg.packageName.equals(renamed)) {
8251                        // Callers into this function may have already taken
8252                        // care of renaming the package; only do it here if
8253                        // it is not already done.
8254                        pkg.setPackageName(renamed);
8255                    }
8256
8257                } else {
8258                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8259                        if ((origPackage = mSettings.peekPackageLPr(
8260                                pkg.mOriginalPackages.get(i))) != null) {
8261                            // We do have the package already installed under its
8262                            // original name...  should we use it?
8263                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8264                                // New package is not compatible with original.
8265                                origPackage = null;
8266                                continue;
8267                            } else if (origPackage.sharedUser != null) {
8268                                // Make sure uid is compatible between packages.
8269                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8270                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8271                                            + " to " + pkg.packageName + ": old uid "
8272                                            + origPackage.sharedUser.name
8273                                            + " differs from " + pkg.mSharedUserId);
8274                                    origPackage = null;
8275                                    continue;
8276                                }
8277                                // TODO: Add case when shared user id is added [b/28144775]
8278                            } else {
8279                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8280                                        + pkg.packageName + " to old name " + origPackage.name);
8281                            }
8282                            break;
8283                        }
8284                    }
8285                }
8286            }
8287
8288            if (mTransferedPackages.contains(pkg.packageName)) {
8289                Slog.w(TAG, "Package " + pkg.packageName
8290                        + " was transferred to another, but its .apk remains");
8291            }
8292
8293            // See comments in nonMutatedPs declaration
8294            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8295                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8296                if (foundPs != null) {
8297                    nonMutatedPs = new PackageSetting(foundPs);
8298                }
8299            }
8300
8301            // Just create the setting, don't add it yet. For already existing packages
8302            // the PkgSetting exists already and doesn't have to be created.
8303            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8304                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8305                    pkg.applicationInfo.primaryCpuAbi,
8306                    pkg.applicationInfo.secondaryCpuAbi,
8307                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8308                    user, false);
8309            if (pkgSetting == null) {
8310                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8311                        "Creating application package " + pkg.packageName + " failed");
8312            }
8313
8314            if (pkgSetting.origPackage != null) {
8315                // If we are first transitioning from an original package,
8316                // fix up the new package's name now.  We need to do this after
8317                // looking up the package under its new name, so getPackageLP
8318                // can take care of fiddling things correctly.
8319                pkg.setPackageName(origPackage.name);
8320
8321                // File a report about this.
8322                String msg = "New package " + pkgSetting.realName
8323                        + " renamed to replace old package " + pkgSetting.name;
8324                reportSettingsProblem(Log.WARN, msg);
8325
8326                // Make a note of it.
8327                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8328                    mTransferedPackages.add(origPackage.name);
8329                }
8330
8331                // No longer need to retain this.
8332                pkgSetting.origPackage = null;
8333            }
8334
8335            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8336                // Make a note of it.
8337                mTransferedPackages.add(pkg.packageName);
8338            }
8339
8340            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8341                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8342            }
8343
8344            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8345                // Check all shared libraries and map to their actual file path.
8346                // We only do this here for apps not on a system dir, because those
8347                // are the only ones that can fail an install due to this.  We
8348                // will take care of the system apps by updating all of their
8349                // library paths after the scan is done.
8350                updateSharedLibrariesLPw(pkg, null);
8351            }
8352
8353            if (mFoundPolicyFile) {
8354                SELinuxMMAC.assignSeinfoValue(pkg);
8355            }
8356
8357            pkg.applicationInfo.uid = pkgSetting.appId;
8358            pkg.mExtras = pkgSetting;
8359            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8360                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8361                    // We just determined the app is signed correctly, so bring
8362                    // over the latest parsed certs.
8363                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8364                } else {
8365                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8366                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8367                                "Package " + pkg.packageName + " upgrade keys do not match the "
8368                                + "previously installed version");
8369                    } else {
8370                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8371                        String msg = "System package " + pkg.packageName
8372                            + " signature changed; retaining data.";
8373                        reportSettingsProblem(Log.WARN, msg);
8374                    }
8375                }
8376            } else {
8377                try {
8378                    verifySignaturesLP(pkgSetting, pkg);
8379                    // We just determined the app is signed correctly, so bring
8380                    // over the latest parsed certs.
8381                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8382                } catch (PackageManagerException e) {
8383                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8384                        throw e;
8385                    }
8386                    // The signature has changed, but this package is in the system
8387                    // image...  let's recover!
8388                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8389                    // However...  if this package is part of a shared user, but it
8390                    // doesn't match the signature of the shared user, let's fail.
8391                    // What this means is that you can't change the signatures
8392                    // associated with an overall shared user, which doesn't seem all
8393                    // that unreasonable.
8394                    if (pkgSetting.sharedUser != null) {
8395                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8396                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8397                            throw new PackageManagerException(
8398                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8399                                            "Signature mismatch for shared user: "
8400                                            + pkgSetting.sharedUser);
8401                        }
8402                    }
8403                    // File a report about this.
8404                    String msg = "System package " + pkg.packageName
8405                        + " signature changed; retaining data.";
8406                    reportSettingsProblem(Log.WARN, msg);
8407                }
8408            }
8409            // Verify that this new package doesn't have any content providers
8410            // that conflict with existing packages.  Only do this if the
8411            // package isn't already installed, since we don't want to break
8412            // things that are installed.
8413            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8414                final int N = pkg.providers.size();
8415                int i;
8416                for (i=0; i<N; i++) {
8417                    PackageParser.Provider p = pkg.providers.get(i);
8418                    if (p.info.authority != null) {
8419                        String names[] = p.info.authority.split(";");
8420                        for (int j = 0; j < names.length; j++) {
8421                            if (mProvidersByAuthority.containsKey(names[j])) {
8422                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8423                                final String otherPackageName =
8424                                        ((other != null && other.getComponentName() != null) ?
8425                                                other.getComponentName().getPackageName() : "?");
8426                                throw new PackageManagerException(
8427                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8428                                                "Can't install because provider name " + names[j]
8429                                                + " (in package " + pkg.applicationInfo.packageName
8430                                                + ") is already used by " + otherPackageName);
8431                            }
8432                        }
8433                    }
8434                }
8435            }
8436
8437            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8438                // This package wants to adopt ownership of permissions from
8439                // another package.
8440                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8441                    final String origName = pkg.mAdoptPermissions.get(i);
8442                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8443                    if (orig != null) {
8444                        if (verifyPackageUpdateLPr(orig, pkg)) {
8445                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8446                                    + pkg.packageName);
8447                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8448                        }
8449                    }
8450                }
8451            }
8452        }
8453
8454        final String pkgName = pkg.packageName;
8455
8456        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8457        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8458        pkg.applicationInfo.processName = fixProcessName(
8459                pkg.applicationInfo.packageName,
8460                pkg.applicationInfo.processName,
8461                pkg.applicationInfo.uid);
8462
8463        if (pkg != mPlatformPackage) {
8464            // Get all of our default paths setup
8465            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8466        }
8467
8468        final String path = scanFile.getPath();
8469        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8470
8471        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8472            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8473
8474            // Some system apps still use directory structure for native libraries
8475            // in which case we might end up not detecting abi solely based on apk
8476            // structure. Try to detect abi based on directory structure.
8477            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8478                    pkg.applicationInfo.primaryCpuAbi == null) {
8479                setBundledAppAbisAndRoots(pkg, pkgSetting);
8480                setNativeLibraryPaths(pkg);
8481            }
8482
8483        } else {
8484            if ((scanFlags & SCAN_MOVE) != 0) {
8485                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8486                // but we already have this packages package info in the PackageSetting. We just
8487                // use that and derive the native library path based on the new codepath.
8488                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8489                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8490            }
8491
8492            // Set native library paths again. For moves, the path will be updated based on the
8493            // ABIs we've determined above. For non-moves, the path will be updated based on the
8494            // ABIs we determined during compilation, but the path will depend on the final
8495            // package path (after the rename away from the stage path).
8496            setNativeLibraryPaths(pkg);
8497        }
8498
8499        // This is a special case for the "system" package, where the ABI is
8500        // dictated by the zygote configuration (and init.rc). We should keep track
8501        // of this ABI so that we can deal with "normal" applications that run under
8502        // the same UID correctly.
8503        if (mPlatformPackage == pkg) {
8504            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8505                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8506        }
8507
8508        // If there's a mismatch between the abi-override in the package setting
8509        // and the abiOverride specified for the install. Warn about this because we
8510        // would've already compiled the app without taking the package setting into
8511        // account.
8512        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8513            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8514                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8515                        " for package " + pkg.packageName);
8516            }
8517        }
8518
8519        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8520        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8521        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8522
8523        // Copy the derived override back to the parsed package, so that we can
8524        // update the package settings accordingly.
8525        pkg.cpuAbiOverride = cpuAbiOverride;
8526
8527        if (DEBUG_ABI_SELECTION) {
8528            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8529                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8530                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8531        }
8532
8533        // Push the derived path down into PackageSettings so we know what to
8534        // clean up at uninstall time.
8535        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8536
8537        if (DEBUG_ABI_SELECTION) {
8538            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8539                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8540                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8541        }
8542
8543        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8544            // We don't do this here during boot because we can do it all
8545            // at once after scanning all existing packages.
8546            //
8547            // We also do this *before* we perform dexopt on this package, so that
8548            // we can avoid redundant dexopts, and also to make sure we've got the
8549            // code and package path correct.
8550            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8551                    pkg, true /* boot complete */);
8552        }
8553
8554        if (mFactoryTest && pkg.requestedPermissions.contains(
8555                android.Manifest.permission.FACTORY_TEST)) {
8556            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8557        }
8558
8559        ArrayList<PackageParser.Package> clientLibPkgs = null;
8560
8561        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8562            if (nonMutatedPs != null) {
8563                synchronized (mPackages) {
8564                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8565                }
8566            }
8567            return pkg;
8568        }
8569
8570        // Only privileged apps and updated privileged apps can add child packages.
8571        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8572            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8573                throw new PackageManagerException("Only privileged apps and updated "
8574                        + "privileged apps can add child packages. Ignoring package "
8575                        + pkg.packageName);
8576            }
8577            final int childCount = pkg.childPackages.size();
8578            for (int i = 0; i < childCount; i++) {
8579                PackageParser.Package childPkg = pkg.childPackages.get(i);
8580                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8581                        childPkg.packageName)) {
8582                    throw new PackageManagerException("Cannot override a child package of "
8583                            + "another disabled system app. Ignoring package " + pkg.packageName);
8584                }
8585            }
8586        }
8587
8588        // writer
8589        synchronized (mPackages) {
8590            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8591                // Only system apps can add new shared libraries.
8592                if (pkg.libraryNames != null) {
8593                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8594                        String name = pkg.libraryNames.get(i);
8595                        boolean allowed = false;
8596                        if (pkg.isUpdatedSystemApp()) {
8597                            // New library entries can only be added through the
8598                            // system image.  This is important to get rid of a lot
8599                            // of nasty edge cases: for example if we allowed a non-
8600                            // system update of the app to add a library, then uninstalling
8601                            // the update would make the library go away, and assumptions
8602                            // we made such as through app install filtering would now
8603                            // have allowed apps on the device which aren't compatible
8604                            // with it.  Better to just have the restriction here, be
8605                            // conservative, and create many fewer cases that can negatively
8606                            // impact the user experience.
8607                            final PackageSetting sysPs = mSettings
8608                                    .getDisabledSystemPkgLPr(pkg.packageName);
8609                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8610                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8611                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8612                                        allowed = true;
8613                                        break;
8614                                    }
8615                                }
8616                            }
8617                        } else {
8618                            allowed = true;
8619                        }
8620                        if (allowed) {
8621                            if (!mSharedLibraries.containsKey(name)) {
8622                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8623                            } else if (!name.equals(pkg.packageName)) {
8624                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8625                                        + name + " already exists; skipping");
8626                            }
8627                        } else {
8628                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8629                                    + name + " that is not declared on system image; skipping");
8630                        }
8631                    }
8632                    if ((scanFlags & SCAN_BOOTING) == 0) {
8633                        // If we are not booting, we need to update any applications
8634                        // that are clients of our shared library.  If we are booting,
8635                        // this will all be done once the scan is complete.
8636                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8637                    }
8638                }
8639            }
8640        }
8641
8642        if ((scanFlags & SCAN_BOOTING) != 0) {
8643            // No apps can run during boot scan, so they don't need to be frozen
8644        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8645            // Caller asked to not kill app, so it's probably not frozen
8646        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8647            // Caller asked us to ignore frozen check for some reason; they
8648            // probably didn't know the package name
8649        } else {
8650            // We're doing major surgery on this package, so it better be frozen
8651            // right now to keep it from launching
8652            checkPackageFrozen(pkgName);
8653        }
8654
8655        // Also need to kill any apps that are dependent on the library.
8656        if (clientLibPkgs != null) {
8657            for (int i=0; i<clientLibPkgs.size(); i++) {
8658                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8659                killApplication(clientPkg.applicationInfo.packageName,
8660                        clientPkg.applicationInfo.uid, "update lib");
8661            }
8662        }
8663
8664        // Make sure we're not adding any bogus keyset info
8665        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8666        ksms.assertScannedPackageValid(pkg);
8667
8668        // writer
8669        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8670
8671        boolean createIdmapFailed = false;
8672        synchronized (mPackages) {
8673            // We don't expect installation to fail beyond this point
8674
8675            if (pkgSetting.pkg != null) {
8676                // Note that |user| might be null during the initial boot scan. If a codePath
8677                // for an app has changed during a boot scan, it's due to an app update that's
8678                // part of the system partition and marker changes must be applied to all users.
8679                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8680                    (user != null) ? user : UserHandle.ALL);
8681            }
8682
8683            // Add the new setting to mSettings
8684            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8685            // Add the new setting to mPackages
8686            mPackages.put(pkg.applicationInfo.packageName, pkg);
8687            // Make sure we don't accidentally delete its data.
8688            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8689            while (iter.hasNext()) {
8690                PackageCleanItem item = iter.next();
8691                if (pkgName.equals(item.packageName)) {
8692                    iter.remove();
8693                }
8694            }
8695
8696            // Take care of first install / last update times.
8697            if (currentTime != 0) {
8698                if (pkgSetting.firstInstallTime == 0) {
8699                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8700                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8701                    pkgSetting.lastUpdateTime = currentTime;
8702                }
8703            } else if (pkgSetting.firstInstallTime == 0) {
8704                // We need *something*.  Take time time stamp of the file.
8705                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8706            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8707                if (scanFileTime != pkgSetting.timeStamp) {
8708                    // A package on the system image has changed; consider this
8709                    // to be an update.
8710                    pkgSetting.lastUpdateTime = scanFileTime;
8711                }
8712            }
8713
8714            // Add the package's KeySets to the global KeySetManagerService
8715            ksms.addScannedPackageLPw(pkg);
8716
8717            int N = pkg.providers.size();
8718            StringBuilder r = null;
8719            int i;
8720            for (i=0; i<N; i++) {
8721                PackageParser.Provider p = pkg.providers.get(i);
8722                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8723                        p.info.processName, pkg.applicationInfo.uid);
8724                mProviders.addProvider(p);
8725                p.syncable = p.info.isSyncable;
8726                if (p.info.authority != null) {
8727                    String names[] = p.info.authority.split(";");
8728                    p.info.authority = null;
8729                    for (int j = 0; j < names.length; j++) {
8730                        if (j == 1 && p.syncable) {
8731                            // We only want the first authority for a provider to possibly be
8732                            // syncable, so if we already added this provider using a different
8733                            // authority clear the syncable flag. We copy the provider before
8734                            // changing it because the mProviders object contains a reference
8735                            // to a provider that we don't want to change.
8736                            // Only do this for the second authority since the resulting provider
8737                            // object can be the same for all future authorities for this provider.
8738                            p = new PackageParser.Provider(p);
8739                            p.syncable = false;
8740                        }
8741                        if (!mProvidersByAuthority.containsKey(names[j])) {
8742                            mProvidersByAuthority.put(names[j], p);
8743                            if (p.info.authority == null) {
8744                                p.info.authority = names[j];
8745                            } else {
8746                                p.info.authority = p.info.authority + ";" + names[j];
8747                            }
8748                            if (DEBUG_PACKAGE_SCANNING) {
8749                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8750                                    Log.d(TAG, "Registered content provider: " + names[j]
8751                                            + ", className = " + p.info.name + ", isSyncable = "
8752                                            + p.info.isSyncable);
8753                            }
8754                        } else {
8755                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8756                            Slog.w(TAG, "Skipping provider name " + names[j] +
8757                                    " (in package " + pkg.applicationInfo.packageName +
8758                                    "): name already used by "
8759                                    + ((other != null && other.getComponentName() != null)
8760                                            ? other.getComponentName().getPackageName() : "?"));
8761                        }
8762                    }
8763                }
8764                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8765                    if (r == null) {
8766                        r = new StringBuilder(256);
8767                    } else {
8768                        r.append(' ');
8769                    }
8770                    r.append(p.info.name);
8771                }
8772            }
8773            if (r != null) {
8774                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8775            }
8776
8777            N = pkg.services.size();
8778            r = null;
8779            for (i=0; i<N; i++) {
8780                PackageParser.Service s = pkg.services.get(i);
8781                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8782                        s.info.processName, pkg.applicationInfo.uid);
8783                mServices.addService(s);
8784                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8785                    if (r == null) {
8786                        r = new StringBuilder(256);
8787                    } else {
8788                        r.append(' ');
8789                    }
8790                    r.append(s.info.name);
8791                }
8792            }
8793            if (r != null) {
8794                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8795            }
8796
8797            N = pkg.receivers.size();
8798            r = null;
8799            for (i=0; i<N; i++) {
8800                PackageParser.Activity a = pkg.receivers.get(i);
8801                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8802                        a.info.processName, pkg.applicationInfo.uid);
8803                mReceivers.addActivity(a, "receiver");
8804                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8805                    if (r == null) {
8806                        r = new StringBuilder(256);
8807                    } else {
8808                        r.append(' ');
8809                    }
8810                    r.append(a.info.name);
8811                }
8812            }
8813            if (r != null) {
8814                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8815            }
8816
8817            N = pkg.activities.size();
8818            r = null;
8819            for (i=0; i<N; i++) {
8820                PackageParser.Activity a = pkg.activities.get(i);
8821                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8822                        a.info.processName, pkg.applicationInfo.uid);
8823                mActivities.addActivity(a, "activity");
8824                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8825                    if (r == null) {
8826                        r = new StringBuilder(256);
8827                    } else {
8828                        r.append(' ');
8829                    }
8830                    r.append(a.info.name);
8831                }
8832            }
8833            if (r != null) {
8834                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8835            }
8836
8837            N = pkg.permissionGroups.size();
8838            r = null;
8839            for (i=0; i<N; i++) {
8840                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8841                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8842                if (cur == null) {
8843                    mPermissionGroups.put(pg.info.name, pg);
8844                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8845                        if (r == null) {
8846                            r = new StringBuilder(256);
8847                        } else {
8848                            r.append(' ');
8849                        }
8850                        r.append(pg.info.name);
8851                    }
8852                } else {
8853                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8854                            + pg.info.packageName + " ignored: original from "
8855                            + cur.info.packageName);
8856                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8857                        if (r == null) {
8858                            r = new StringBuilder(256);
8859                        } else {
8860                            r.append(' ');
8861                        }
8862                        r.append("DUP:");
8863                        r.append(pg.info.name);
8864                    }
8865                }
8866            }
8867            if (r != null) {
8868                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8869            }
8870
8871            N = pkg.permissions.size();
8872            r = null;
8873            for (i=0; i<N; i++) {
8874                PackageParser.Permission p = pkg.permissions.get(i);
8875
8876                // Assume by default that we did not install this permission into the system.
8877                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8878
8879                // Now that permission groups have a special meaning, we ignore permission
8880                // groups for legacy apps to prevent unexpected behavior. In particular,
8881                // permissions for one app being granted to someone just becase they happen
8882                // to be in a group defined by another app (before this had no implications).
8883                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8884                    p.group = mPermissionGroups.get(p.info.group);
8885                    // Warn for a permission in an unknown group.
8886                    if (p.info.group != null && p.group == null) {
8887                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8888                                + p.info.packageName + " in an unknown group " + p.info.group);
8889                    }
8890                }
8891
8892                ArrayMap<String, BasePermission> permissionMap =
8893                        p.tree ? mSettings.mPermissionTrees
8894                                : mSettings.mPermissions;
8895                BasePermission bp = permissionMap.get(p.info.name);
8896
8897                // Allow system apps to redefine non-system permissions
8898                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8899                    final boolean currentOwnerIsSystem = (bp.perm != null
8900                            && isSystemApp(bp.perm.owner));
8901                    if (isSystemApp(p.owner)) {
8902                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8903                            // It's a built-in permission and no owner, take ownership now
8904                            bp.packageSetting = pkgSetting;
8905                            bp.perm = p;
8906                            bp.uid = pkg.applicationInfo.uid;
8907                            bp.sourcePackage = p.info.packageName;
8908                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8909                        } else if (!currentOwnerIsSystem) {
8910                            String msg = "New decl " + p.owner + " of permission  "
8911                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8912                            reportSettingsProblem(Log.WARN, msg);
8913                            bp = null;
8914                        }
8915                    }
8916                }
8917
8918                if (bp == null) {
8919                    bp = new BasePermission(p.info.name, p.info.packageName,
8920                            BasePermission.TYPE_NORMAL);
8921                    permissionMap.put(p.info.name, bp);
8922                }
8923
8924                if (bp.perm == null) {
8925                    if (bp.sourcePackage == null
8926                            || bp.sourcePackage.equals(p.info.packageName)) {
8927                        BasePermission tree = findPermissionTreeLP(p.info.name);
8928                        if (tree == null
8929                                || tree.sourcePackage.equals(p.info.packageName)) {
8930                            bp.packageSetting = pkgSetting;
8931                            bp.perm = p;
8932                            bp.uid = pkg.applicationInfo.uid;
8933                            bp.sourcePackage = p.info.packageName;
8934                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8935                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8936                                if (r == null) {
8937                                    r = new StringBuilder(256);
8938                                } else {
8939                                    r.append(' ');
8940                                }
8941                                r.append(p.info.name);
8942                            }
8943                        } else {
8944                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8945                                    + p.info.packageName + " ignored: base tree "
8946                                    + tree.name + " is from package "
8947                                    + tree.sourcePackage);
8948                        }
8949                    } else {
8950                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8951                                + p.info.packageName + " ignored: original from "
8952                                + bp.sourcePackage);
8953                    }
8954                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8955                    if (r == null) {
8956                        r = new StringBuilder(256);
8957                    } else {
8958                        r.append(' ');
8959                    }
8960                    r.append("DUP:");
8961                    r.append(p.info.name);
8962                }
8963                if (bp.perm == p) {
8964                    bp.protectionLevel = p.info.protectionLevel;
8965                }
8966            }
8967
8968            if (r != null) {
8969                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8970            }
8971
8972            N = pkg.instrumentation.size();
8973            r = null;
8974            for (i=0; i<N; i++) {
8975                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8976                a.info.packageName = pkg.applicationInfo.packageName;
8977                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8978                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8979                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8980                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8981                a.info.dataDir = pkg.applicationInfo.dataDir;
8982                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8983                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8984
8985                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8986                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8987                mInstrumentation.put(a.getComponentName(), a);
8988                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8989                    if (r == null) {
8990                        r = new StringBuilder(256);
8991                    } else {
8992                        r.append(' ');
8993                    }
8994                    r.append(a.info.name);
8995                }
8996            }
8997            if (r != null) {
8998                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8999            }
9000
9001            if (pkg.protectedBroadcasts != null) {
9002                N = pkg.protectedBroadcasts.size();
9003                for (i=0; i<N; i++) {
9004                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9005                }
9006            }
9007
9008            pkgSetting.setTimeStamp(scanFileTime);
9009
9010            // Create idmap files for pairs of (packages, overlay packages).
9011            // Note: "android", ie framework-res.apk, is handled by native layers.
9012            if (pkg.mOverlayTarget != null) {
9013                // This is an overlay package.
9014                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9015                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9016                        mOverlays.put(pkg.mOverlayTarget,
9017                                new ArrayMap<String, PackageParser.Package>());
9018                    }
9019                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9020                    map.put(pkg.packageName, pkg);
9021                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9022                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9023                        createIdmapFailed = true;
9024                    }
9025                }
9026            } else if (mOverlays.containsKey(pkg.packageName) &&
9027                    !pkg.packageName.equals("android")) {
9028                // This is a regular package, with one or more known overlay packages.
9029                createIdmapsForPackageLI(pkg);
9030            }
9031        }
9032
9033        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9034
9035        if (createIdmapFailed) {
9036            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9037                    "scanPackageLI failed to createIdmap");
9038        }
9039        return pkg;
9040    }
9041
9042    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9043            PackageParser.Package update, UserHandle user) {
9044        if (existing.applicationInfo == null || update.applicationInfo == null) {
9045            // This isn't due to an app installation.
9046            return;
9047        }
9048
9049        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9050        final File newCodePath = new File(update.applicationInfo.getCodePath());
9051
9052        // The codePath hasn't changed, so there's nothing for us to do.
9053        if (Objects.equals(oldCodePath, newCodePath)) {
9054            return;
9055        }
9056
9057        File canonicalNewCodePath;
9058        try {
9059            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9060        } catch (IOException e) {
9061            Slog.w(TAG, "Failed to get canonical path.", e);
9062            return;
9063        }
9064
9065        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9066        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9067        // that the last component of the path (i.e, the name) doesn't need canonicalization
9068        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9069        // but may change in the future. Hopefully this function won't exist at that point.
9070        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9071                oldCodePath.getName());
9072
9073        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9074        // with "@".
9075        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9076        if (!oldMarkerPrefix.endsWith("@")) {
9077            oldMarkerPrefix += "@";
9078        }
9079        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9080        if (!newMarkerPrefix.endsWith("@")) {
9081            newMarkerPrefix += "@";
9082        }
9083
9084        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9085        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9086        for (String updatedPath : updatedPaths) {
9087            String updatedPathName = new File(updatedPath).getName();
9088            markerSuffixes.add(updatedPathName.replace('/', '@'));
9089        }
9090
9091        for (int userId : resolveUserIds(user.getIdentifier())) {
9092            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9093
9094            for (String markerSuffix : markerSuffixes) {
9095                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9096                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9097                if (oldForeignUseMark.exists()) {
9098                    try {
9099                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9100                                newForeignUseMark.getAbsolutePath());
9101                    } catch (ErrnoException e) {
9102                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9103                        oldForeignUseMark.delete();
9104                    }
9105                }
9106            }
9107        }
9108    }
9109
9110    /**
9111     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9112     * is derived purely on the basis of the contents of {@code scanFile} and
9113     * {@code cpuAbiOverride}.
9114     *
9115     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9116     */
9117    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9118                                 String cpuAbiOverride, boolean extractLibs)
9119            throws PackageManagerException {
9120        // TODO: We can probably be smarter about this stuff. For installed apps,
9121        // we can calculate this information at install time once and for all. For
9122        // system apps, we can probably assume that this information doesn't change
9123        // after the first boot scan. As things stand, we do lots of unnecessary work.
9124
9125        // Give ourselves some initial paths; we'll come back for another
9126        // pass once we've determined ABI below.
9127        setNativeLibraryPaths(pkg);
9128
9129        // We would never need to extract libs for forward-locked and external packages,
9130        // since the container service will do it for us. We shouldn't attempt to
9131        // extract libs from system app when it was not updated.
9132        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9133                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9134            extractLibs = false;
9135        }
9136
9137        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9138        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9139
9140        NativeLibraryHelper.Handle handle = null;
9141        try {
9142            handle = NativeLibraryHelper.Handle.create(pkg);
9143            // TODO(multiArch): This can be null for apps that didn't go through the
9144            // usual installation process. We can calculate it again, like we
9145            // do during install time.
9146            //
9147            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9148            // unnecessary.
9149            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9150
9151            // Null out the abis so that they can be recalculated.
9152            pkg.applicationInfo.primaryCpuAbi = null;
9153            pkg.applicationInfo.secondaryCpuAbi = null;
9154            if (isMultiArch(pkg.applicationInfo)) {
9155                // Warn if we've set an abiOverride for multi-lib packages..
9156                // By definition, we need to copy both 32 and 64 bit libraries for
9157                // such packages.
9158                if (pkg.cpuAbiOverride != null
9159                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9160                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9161                }
9162
9163                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9164                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9165                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9166                    if (extractLibs) {
9167                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9168                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9169                                useIsaSpecificSubdirs);
9170                    } else {
9171                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9172                    }
9173                }
9174
9175                maybeThrowExceptionForMultiArchCopy(
9176                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9177
9178                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9179                    if (extractLibs) {
9180                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9181                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9182                                useIsaSpecificSubdirs);
9183                    } else {
9184                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9185                    }
9186                }
9187
9188                maybeThrowExceptionForMultiArchCopy(
9189                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9190
9191                if (abi64 >= 0) {
9192                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9193                }
9194
9195                if (abi32 >= 0) {
9196                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9197                    if (abi64 >= 0) {
9198                        if (pkg.use32bitAbi) {
9199                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9200                            pkg.applicationInfo.primaryCpuAbi = abi;
9201                        } else {
9202                            pkg.applicationInfo.secondaryCpuAbi = abi;
9203                        }
9204                    } else {
9205                        pkg.applicationInfo.primaryCpuAbi = abi;
9206                    }
9207                }
9208
9209            } else {
9210                String[] abiList = (cpuAbiOverride != null) ?
9211                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9212
9213                // Enable gross and lame hacks for apps that are built with old
9214                // SDK tools. We must scan their APKs for renderscript bitcode and
9215                // not launch them if it's present. Don't bother checking on devices
9216                // that don't have 64 bit support.
9217                boolean needsRenderScriptOverride = false;
9218                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9219                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9220                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9221                    needsRenderScriptOverride = true;
9222                }
9223
9224                final int copyRet;
9225                if (extractLibs) {
9226                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9227                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9228                } else {
9229                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9230                }
9231
9232                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9233                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9234                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9235                }
9236
9237                if (copyRet >= 0) {
9238                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9239                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9240                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9241                } else if (needsRenderScriptOverride) {
9242                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9243                }
9244            }
9245        } catch (IOException ioe) {
9246            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9247        } finally {
9248            IoUtils.closeQuietly(handle);
9249        }
9250
9251        // Now that we've calculated the ABIs and determined if it's an internal app,
9252        // we will go ahead and populate the nativeLibraryPath.
9253        setNativeLibraryPaths(pkg);
9254    }
9255
9256    /**
9257     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9258     * i.e, so that all packages can be run inside a single process if required.
9259     *
9260     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9261     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9262     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9263     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9264     * updating a package that belongs to a shared user.
9265     *
9266     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9267     * adds unnecessary complexity.
9268     */
9269    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9270            PackageParser.Package scannedPackage, boolean bootComplete) {
9271        String requiredInstructionSet = null;
9272        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9273            requiredInstructionSet = VMRuntime.getInstructionSet(
9274                     scannedPackage.applicationInfo.primaryCpuAbi);
9275        }
9276
9277        PackageSetting requirer = null;
9278        for (PackageSetting ps : packagesForUser) {
9279            // If packagesForUser contains scannedPackage, we skip it. This will happen
9280            // when scannedPackage is an update of an existing package. Without this check,
9281            // we will never be able to change the ABI of any package belonging to a shared
9282            // user, even if it's compatible with other packages.
9283            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9284                if (ps.primaryCpuAbiString == null) {
9285                    continue;
9286                }
9287
9288                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9289                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9290                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9291                    // this but there's not much we can do.
9292                    String errorMessage = "Instruction set mismatch, "
9293                            + ((requirer == null) ? "[caller]" : requirer)
9294                            + " requires " + requiredInstructionSet + " whereas " + ps
9295                            + " requires " + instructionSet;
9296                    Slog.w(TAG, errorMessage);
9297                }
9298
9299                if (requiredInstructionSet == null) {
9300                    requiredInstructionSet = instructionSet;
9301                    requirer = ps;
9302                }
9303            }
9304        }
9305
9306        if (requiredInstructionSet != null) {
9307            String adjustedAbi;
9308            if (requirer != null) {
9309                // requirer != null implies that either scannedPackage was null or that scannedPackage
9310                // did not require an ABI, in which case we have to adjust scannedPackage to match
9311                // the ABI of the set (which is the same as requirer's ABI)
9312                adjustedAbi = requirer.primaryCpuAbiString;
9313                if (scannedPackage != null) {
9314                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9315                }
9316            } else {
9317                // requirer == null implies that we're updating all ABIs in the set to
9318                // match scannedPackage.
9319                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9320            }
9321
9322            for (PackageSetting ps : packagesForUser) {
9323                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9324                    if (ps.primaryCpuAbiString != null) {
9325                        continue;
9326                    }
9327
9328                    ps.primaryCpuAbiString = adjustedAbi;
9329                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9330                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9331                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9332                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9333                                + " (requirer="
9334                                + (requirer == null ? "null" : requirer.pkg.packageName)
9335                                + ", scannedPackage="
9336                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9337                                + ")");
9338                        try {
9339                            mInstaller.rmdex(ps.codePathString,
9340                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9341                        } catch (InstallerException ignored) {
9342                        }
9343                    }
9344                }
9345            }
9346        }
9347    }
9348
9349    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9350        synchronized (mPackages) {
9351            mResolverReplaced = true;
9352            // Set up information for custom user intent resolution activity.
9353            mResolveActivity.applicationInfo = pkg.applicationInfo;
9354            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9355            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9356            mResolveActivity.processName = pkg.applicationInfo.packageName;
9357            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9358            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9359                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9360            mResolveActivity.theme = 0;
9361            mResolveActivity.exported = true;
9362            mResolveActivity.enabled = true;
9363            mResolveInfo.activityInfo = mResolveActivity;
9364            mResolveInfo.priority = 0;
9365            mResolveInfo.preferredOrder = 0;
9366            mResolveInfo.match = 0;
9367            mResolveComponentName = mCustomResolverComponentName;
9368            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9369                    mResolveComponentName);
9370        }
9371    }
9372
9373    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9374        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9375
9376        // Set up information for ephemeral installer activity
9377        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9378        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9379        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9380        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9381        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9382        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9383                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9384        mEphemeralInstallerActivity.theme = 0;
9385        mEphemeralInstallerActivity.exported = true;
9386        mEphemeralInstallerActivity.enabled = true;
9387        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9388        mEphemeralInstallerInfo.priority = 0;
9389        mEphemeralInstallerInfo.preferredOrder = 0;
9390        mEphemeralInstallerInfo.match = 0;
9391
9392        if (DEBUG_EPHEMERAL) {
9393            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9394        }
9395    }
9396
9397    private static String calculateBundledApkRoot(final String codePathString) {
9398        final File codePath = new File(codePathString);
9399        final File codeRoot;
9400        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9401            codeRoot = Environment.getRootDirectory();
9402        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9403            codeRoot = Environment.getOemDirectory();
9404        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9405            codeRoot = Environment.getVendorDirectory();
9406        } else {
9407            // Unrecognized code path; take its top real segment as the apk root:
9408            // e.g. /something/app/blah.apk => /something
9409            try {
9410                File f = codePath.getCanonicalFile();
9411                File parent = f.getParentFile();    // non-null because codePath is a file
9412                File tmp;
9413                while ((tmp = parent.getParentFile()) != null) {
9414                    f = parent;
9415                    parent = tmp;
9416                }
9417                codeRoot = f;
9418                Slog.w(TAG, "Unrecognized code path "
9419                        + codePath + " - using " + codeRoot);
9420            } catch (IOException e) {
9421                // Can't canonicalize the code path -- shenanigans?
9422                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9423                return Environment.getRootDirectory().getPath();
9424            }
9425        }
9426        return codeRoot.getPath();
9427    }
9428
9429    /**
9430     * Derive and set the location of native libraries for the given package,
9431     * which varies depending on where and how the package was installed.
9432     */
9433    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9434        final ApplicationInfo info = pkg.applicationInfo;
9435        final String codePath = pkg.codePath;
9436        final File codeFile = new File(codePath);
9437        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9438        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9439
9440        info.nativeLibraryRootDir = null;
9441        info.nativeLibraryRootRequiresIsa = false;
9442        info.nativeLibraryDir = null;
9443        info.secondaryNativeLibraryDir = null;
9444
9445        if (isApkFile(codeFile)) {
9446            // Monolithic install
9447            if (bundledApp) {
9448                // If "/system/lib64/apkname" exists, assume that is the per-package
9449                // native library directory to use; otherwise use "/system/lib/apkname".
9450                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9451                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9452                        getPrimaryInstructionSet(info));
9453
9454                // This is a bundled system app so choose the path based on the ABI.
9455                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9456                // is just the default path.
9457                final String apkName = deriveCodePathName(codePath);
9458                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9459                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9460                        apkName).getAbsolutePath();
9461
9462                if (info.secondaryCpuAbi != null) {
9463                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9464                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9465                            secondaryLibDir, apkName).getAbsolutePath();
9466                }
9467            } else if (asecApp) {
9468                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9469                        .getAbsolutePath();
9470            } else {
9471                final String apkName = deriveCodePathName(codePath);
9472                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9473                        .getAbsolutePath();
9474            }
9475
9476            info.nativeLibraryRootRequiresIsa = false;
9477            info.nativeLibraryDir = info.nativeLibraryRootDir;
9478        } else {
9479            // Cluster install
9480            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9481            info.nativeLibraryRootRequiresIsa = true;
9482
9483            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9484                    getPrimaryInstructionSet(info)).getAbsolutePath();
9485
9486            if (info.secondaryCpuAbi != null) {
9487                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9488                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9489            }
9490        }
9491    }
9492
9493    /**
9494     * Calculate the abis and roots for a bundled app. These can uniquely
9495     * be determined from the contents of the system partition, i.e whether
9496     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9497     * of this information, and instead assume that the system was built
9498     * sensibly.
9499     */
9500    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9501                                           PackageSetting pkgSetting) {
9502        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9503
9504        // If "/system/lib64/apkname" exists, assume that is the per-package
9505        // native library directory to use; otherwise use "/system/lib/apkname".
9506        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9507        setBundledAppAbi(pkg, apkRoot, apkName);
9508        // pkgSetting might be null during rescan following uninstall of updates
9509        // to a bundled app, so accommodate that possibility.  The settings in
9510        // that case will be established later from the parsed package.
9511        //
9512        // If the settings aren't null, sync them up with what we've just derived.
9513        // note that apkRoot isn't stored in the package settings.
9514        if (pkgSetting != null) {
9515            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9516            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9517        }
9518    }
9519
9520    /**
9521     * Deduces the ABI of a bundled app and sets the relevant fields on the
9522     * parsed pkg object.
9523     *
9524     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9525     *        under which system libraries are installed.
9526     * @param apkName the name of the installed package.
9527     */
9528    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9529        final File codeFile = new File(pkg.codePath);
9530
9531        final boolean has64BitLibs;
9532        final boolean has32BitLibs;
9533        if (isApkFile(codeFile)) {
9534            // Monolithic install
9535            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9536            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9537        } else {
9538            // Cluster install
9539            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9540            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9541                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9542                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9543                has64BitLibs = (new File(rootDir, isa)).exists();
9544            } else {
9545                has64BitLibs = false;
9546            }
9547            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9548                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9549                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9550                has32BitLibs = (new File(rootDir, isa)).exists();
9551            } else {
9552                has32BitLibs = false;
9553            }
9554        }
9555
9556        if (has64BitLibs && !has32BitLibs) {
9557            // The package has 64 bit libs, but not 32 bit libs. Its primary
9558            // ABI should be 64 bit. We can safely assume here that the bundled
9559            // native libraries correspond to the most preferred ABI in the list.
9560
9561            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9562            pkg.applicationInfo.secondaryCpuAbi = null;
9563        } else if (has32BitLibs && !has64BitLibs) {
9564            // The package has 32 bit libs but not 64 bit libs. Its primary
9565            // ABI should be 32 bit.
9566
9567            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9568            pkg.applicationInfo.secondaryCpuAbi = null;
9569        } else if (has32BitLibs && has64BitLibs) {
9570            // The application has both 64 and 32 bit bundled libraries. We check
9571            // here that the app declares multiArch support, and warn if it doesn't.
9572            //
9573            // We will be lenient here and record both ABIs. The primary will be the
9574            // ABI that's higher on the list, i.e, a device that's configured to prefer
9575            // 64 bit apps will see a 64 bit primary ABI,
9576
9577            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9578                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9579            }
9580
9581            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9582                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9583                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9584            } else {
9585                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9586                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9587            }
9588        } else {
9589            pkg.applicationInfo.primaryCpuAbi = null;
9590            pkg.applicationInfo.secondaryCpuAbi = null;
9591        }
9592    }
9593
9594    private void killApplication(String pkgName, int appId, String reason) {
9595        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9596    }
9597
9598    private void killApplication(String pkgName, int appId, int userId, String reason) {
9599        // Request the ActivityManager to kill the process(only for existing packages)
9600        // so that we do not end up in a confused state while the user is still using the older
9601        // version of the application while the new one gets installed.
9602        final long token = Binder.clearCallingIdentity();
9603        try {
9604            IActivityManager am = ActivityManagerNative.getDefault();
9605            if (am != null) {
9606                try {
9607                    am.killApplication(pkgName, appId, userId, reason);
9608                } catch (RemoteException e) {
9609                }
9610            }
9611        } finally {
9612            Binder.restoreCallingIdentity(token);
9613        }
9614    }
9615
9616    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9617        // Remove the parent package setting
9618        PackageSetting ps = (PackageSetting) pkg.mExtras;
9619        if (ps != null) {
9620            removePackageLI(ps, chatty);
9621        }
9622        // Remove the child package setting
9623        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9624        for (int i = 0; i < childCount; i++) {
9625            PackageParser.Package childPkg = pkg.childPackages.get(i);
9626            ps = (PackageSetting) childPkg.mExtras;
9627            if (ps != null) {
9628                removePackageLI(ps, chatty);
9629            }
9630        }
9631    }
9632
9633    void removePackageLI(PackageSetting ps, boolean chatty) {
9634        if (DEBUG_INSTALL) {
9635            if (chatty)
9636                Log.d(TAG, "Removing package " + ps.name);
9637        }
9638
9639        // writer
9640        synchronized (mPackages) {
9641            mPackages.remove(ps.name);
9642            final PackageParser.Package pkg = ps.pkg;
9643            if (pkg != null) {
9644                cleanPackageDataStructuresLILPw(pkg, chatty);
9645            }
9646        }
9647    }
9648
9649    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9650        if (DEBUG_INSTALL) {
9651            if (chatty)
9652                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9653        }
9654
9655        // writer
9656        synchronized (mPackages) {
9657            // Remove the parent package
9658            mPackages.remove(pkg.applicationInfo.packageName);
9659            cleanPackageDataStructuresLILPw(pkg, chatty);
9660
9661            // Remove the child packages
9662            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9663            for (int i = 0; i < childCount; i++) {
9664                PackageParser.Package childPkg = pkg.childPackages.get(i);
9665                mPackages.remove(childPkg.applicationInfo.packageName);
9666                cleanPackageDataStructuresLILPw(childPkg, chatty);
9667            }
9668        }
9669    }
9670
9671    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9672        int N = pkg.providers.size();
9673        StringBuilder r = null;
9674        int i;
9675        for (i=0; i<N; i++) {
9676            PackageParser.Provider p = pkg.providers.get(i);
9677            mProviders.removeProvider(p);
9678            if (p.info.authority == null) {
9679
9680                /* There was another ContentProvider with this authority when
9681                 * this app was installed so this authority is null,
9682                 * Ignore it as we don't have to unregister the provider.
9683                 */
9684                continue;
9685            }
9686            String names[] = p.info.authority.split(";");
9687            for (int j = 0; j < names.length; j++) {
9688                if (mProvidersByAuthority.get(names[j]) == p) {
9689                    mProvidersByAuthority.remove(names[j]);
9690                    if (DEBUG_REMOVE) {
9691                        if (chatty)
9692                            Log.d(TAG, "Unregistered content provider: " + names[j]
9693                                    + ", className = " + p.info.name + ", isSyncable = "
9694                                    + p.info.isSyncable);
9695                    }
9696                }
9697            }
9698            if (DEBUG_REMOVE && chatty) {
9699                if (r == null) {
9700                    r = new StringBuilder(256);
9701                } else {
9702                    r.append(' ');
9703                }
9704                r.append(p.info.name);
9705            }
9706        }
9707        if (r != null) {
9708            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9709        }
9710
9711        N = pkg.services.size();
9712        r = null;
9713        for (i=0; i<N; i++) {
9714            PackageParser.Service s = pkg.services.get(i);
9715            mServices.removeService(s);
9716            if (chatty) {
9717                if (r == null) {
9718                    r = new StringBuilder(256);
9719                } else {
9720                    r.append(' ');
9721                }
9722                r.append(s.info.name);
9723            }
9724        }
9725        if (r != null) {
9726            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9727        }
9728
9729        N = pkg.receivers.size();
9730        r = null;
9731        for (i=0; i<N; i++) {
9732            PackageParser.Activity a = pkg.receivers.get(i);
9733            mReceivers.removeActivity(a, "receiver");
9734            if (DEBUG_REMOVE && chatty) {
9735                if (r == null) {
9736                    r = new StringBuilder(256);
9737                } else {
9738                    r.append(' ');
9739                }
9740                r.append(a.info.name);
9741            }
9742        }
9743        if (r != null) {
9744            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9745        }
9746
9747        N = pkg.activities.size();
9748        r = null;
9749        for (i=0; i<N; i++) {
9750            PackageParser.Activity a = pkg.activities.get(i);
9751            mActivities.removeActivity(a, "activity");
9752            if (DEBUG_REMOVE && chatty) {
9753                if (r == null) {
9754                    r = new StringBuilder(256);
9755                } else {
9756                    r.append(' ');
9757                }
9758                r.append(a.info.name);
9759            }
9760        }
9761        if (r != null) {
9762            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9763        }
9764
9765        N = pkg.permissions.size();
9766        r = null;
9767        for (i=0; i<N; i++) {
9768            PackageParser.Permission p = pkg.permissions.get(i);
9769            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9770            if (bp == null) {
9771                bp = mSettings.mPermissionTrees.get(p.info.name);
9772            }
9773            if (bp != null && bp.perm == p) {
9774                bp.perm = null;
9775                if (DEBUG_REMOVE && chatty) {
9776                    if (r == null) {
9777                        r = new StringBuilder(256);
9778                    } else {
9779                        r.append(' ');
9780                    }
9781                    r.append(p.info.name);
9782                }
9783            }
9784            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9785                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9786                if (appOpPkgs != null) {
9787                    appOpPkgs.remove(pkg.packageName);
9788                }
9789            }
9790        }
9791        if (r != null) {
9792            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9793        }
9794
9795        N = pkg.requestedPermissions.size();
9796        r = null;
9797        for (i=0; i<N; i++) {
9798            String perm = pkg.requestedPermissions.get(i);
9799            BasePermission bp = mSettings.mPermissions.get(perm);
9800            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9801                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9802                if (appOpPkgs != null) {
9803                    appOpPkgs.remove(pkg.packageName);
9804                    if (appOpPkgs.isEmpty()) {
9805                        mAppOpPermissionPackages.remove(perm);
9806                    }
9807                }
9808            }
9809        }
9810        if (r != null) {
9811            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9812        }
9813
9814        N = pkg.instrumentation.size();
9815        r = null;
9816        for (i=0; i<N; i++) {
9817            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9818            mInstrumentation.remove(a.getComponentName());
9819            if (DEBUG_REMOVE && chatty) {
9820                if (r == null) {
9821                    r = new StringBuilder(256);
9822                } else {
9823                    r.append(' ');
9824                }
9825                r.append(a.info.name);
9826            }
9827        }
9828        if (r != null) {
9829            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9830        }
9831
9832        r = null;
9833        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9834            // Only system apps can hold shared libraries.
9835            if (pkg.libraryNames != null) {
9836                for (i=0; i<pkg.libraryNames.size(); i++) {
9837                    String name = pkg.libraryNames.get(i);
9838                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9839                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9840                        mSharedLibraries.remove(name);
9841                        if (DEBUG_REMOVE && chatty) {
9842                            if (r == null) {
9843                                r = new StringBuilder(256);
9844                            } else {
9845                                r.append(' ');
9846                            }
9847                            r.append(name);
9848                        }
9849                    }
9850                }
9851            }
9852        }
9853        if (r != null) {
9854            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9855        }
9856    }
9857
9858    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9859        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9860            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9861                return true;
9862            }
9863        }
9864        return false;
9865    }
9866
9867    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9868    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9869    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9870
9871    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9872        // Update the parent permissions
9873        updatePermissionsLPw(pkg.packageName, pkg, flags);
9874        // Update the child permissions
9875        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9876        for (int i = 0; i < childCount; i++) {
9877            PackageParser.Package childPkg = pkg.childPackages.get(i);
9878            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9879        }
9880    }
9881
9882    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9883            int flags) {
9884        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9885        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9886    }
9887
9888    private void updatePermissionsLPw(String changingPkg,
9889            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9890        // Make sure there are no dangling permission trees.
9891        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9892        while (it.hasNext()) {
9893            final BasePermission bp = it.next();
9894            if (bp.packageSetting == null) {
9895                // We may not yet have parsed the package, so just see if
9896                // we still know about its settings.
9897                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9898            }
9899            if (bp.packageSetting == null) {
9900                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9901                        + " from package " + bp.sourcePackage);
9902                it.remove();
9903            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9904                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9905                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9906                            + " from package " + bp.sourcePackage);
9907                    flags |= UPDATE_PERMISSIONS_ALL;
9908                    it.remove();
9909                }
9910            }
9911        }
9912
9913        // Make sure all dynamic permissions have been assigned to a package,
9914        // and make sure there are no dangling permissions.
9915        it = mSettings.mPermissions.values().iterator();
9916        while (it.hasNext()) {
9917            final BasePermission bp = it.next();
9918            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9919                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9920                        + bp.name + " pkg=" + bp.sourcePackage
9921                        + " info=" + bp.pendingInfo);
9922                if (bp.packageSetting == null && bp.pendingInfo != null) {
9923                    final BasePermission tree = findPermissionTreeLP(bp.name);
9924                    if (tree != null && tree.perm != null) {
9925                        bp.packageSetting = tree.packageSetting;
9926                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9927                                new PermissionInfo(bp.pendingInfo));
9928                        bp.perm.info.packageName = tree.perm.info.packageName;
9929                        bp.perm.info.name = bp.name;
9930                        bp.uid = tree.uid;
9931                    }
9932                }
9933            }
9934            if (bp.packageSetting == null) {
9935                // We may not yet have parsed the package, so just see if
9936                // we still know about its settings.
9937                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9938            }
9939            if (bp.packageSetting == null) {
9940                Slog.w(TAG, "Removing dangling permission: " + bp.name
9941                        + " from package " + bp.sourcePackage);
9942                it.remove();
9943            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9944                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9945                    Slog.i(TAG, "Removing old permission: " + bp.name
9946                            + " from package " + bp.sourcePackage);
9947                    flags |= UPDATE_PERMISSIONS_ALL;
9948                    it.remove();
9949                }
9950            }
9951        }
9952
9953        // Now update the permissions for all packages, in particular
9954        // replace the granted permissions of the system packages.
9955        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9956            for (PackageParser.Package pkg : mPackages.values()) {
9957                if (pkg != pkgInfo) {
9958                    // Only replace for packages on requested volume
9959                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9960                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9961                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9962                    grantPermissionsLPw(pkg, replace, changingPkg);
9963                }
9964            }
9965        }
9966
9967        if (pkgInfo != null) {
9968            // Only replace for packages on requested volume
9969            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9970            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9971                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9972            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9973        }
9974    }
9975
9976    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9977            String packageOfInterest) {
9978        // IMPORTANT: There are two types of permissions: install and runtime.
9979        // Install time permissions are granted when the app is installed to
9980        // all device users and users added in the future. Runtime permissions
9981        // are granted at runtime explicitly to specific users. Normal and signature
9982        // protected permissions are install time permissions. Dangerous permissions
9983        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9984        // otherwise they are runtime permissions. This function does not manage
9985        // runtime permissions except for the case an app targeting Lollipop MR1
9986        // being upgraded to target a newer SDK, in which case dangerous permissions
9987        // are transformed from install time to runtime ones.
9988
9989        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9990        if (ps == null) {
9991            return;
9992        }
9993
9994        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9995
9996        PermissionsState permissionsState = ps.getPermissionsState();
9997        PermissionsState origPermissions = permissionsState;
9998
9999        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10000
10001        boolean runtimePermissionsRevoked = false;
10002        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10003
10004        boolean changedInstallPermission = false;
10005
10006        if (replace) {
10007            ps.installPermissionsFixed = false;
10008            if (!ps.isSharedUser()) {
10009                origPermissions = new PermissionsState(permissionsState);
10010                permissionsState.reset();
10011            } else {
10012                // We need to know only about runtime permission changes since the
10013                // calling code always writes the install permissions state but
10014                // the runtime ones are written only if changed. The only cases of
10015                // changed runtime permissions here are promotion of an install to
10016                // runtime and revocation of a runtime from a shared user.
10017                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10018                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10019                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10020                    runtimePermissionsRevoked = true;
10021                }
10022            }
10023        }
10024
10025        permissionsState.setGlobalGids(mGlobalGids);
10026
10027        final int N = pkg.requestedPermissions.size();
10028        for (int i=0; i<N; i++) {
10029            final String name = pkg.requestedPermissions.get(i);
10030            final BasePermission bp = mSettings.mPermissions.get(name);
10031
10032            if (DEBUG_INSTALL) {
10033                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10034            }
10035
10036            if (bp == null || bp.packageSetting == null) {
10037                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10038                    Slog.w(TAG, "Unknown permission " + name
10039                            + " in package " + pkg.packageName);
10040                }
10041                continue;
10042            }
10043
10044            final String perm = bp.name;
10045            boolean allowedSig = false;
10046            int grant = GRANT_DENIED;
10047
10048            // Keep track of app op permissions.
10049            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10050                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10051                if (pkgs == null) {
10052                    pkgs = new ArraySet<>();
10053                    mAppOpPermissionPackages.put(bp.name, pkgs);
10054                }
10055                pkgs.add(pkg.packageName);
10056            }
10057
10058            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10059            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10060                    >= Build.VERSION_CODES.M;
10061            switch (level) {
10062                case PermissionInfo.PROTECTION_NORMAL: {
10063                    // For all apps normal permissions are install time ones.
10064                    grant = GRANT_INSTALL;
10065                } break;
10066
10067                case PermissionInfo.PROTECTION_DANGEROUS: {
10068                    // If a permission review is required for legacy apps we represent
10069                    // their permissions as always granted runtime ones since we need
10070                    // to keep the review required permission flag per user while an
10071                    // install permission's state is shared across all users.
10072                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10073                        // For legacy apps dangerous permissions are install time ones.
10074                        grant = GRANT_INSTALL;
10075                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10076                        // For legacy apps that became modern, install becomes runtime.
10077                        grant = GRANT_UPGRADE;
10078                    } else if (mPromoteSystemApps
10079                            && isSystemApp(ps)
10080                            && mExistingSystemPackages.contains(ps.name)) {
10081                        // For legacy system apps, install becomes runtime.
10082                        // We cannot check hasInstallPermission() for system apps since those
10083                        // permissions were granted implicitly and not persisted pre-M.
10084                        grant = GRANT_UPGRADE;
10085                    } else {
10086                        // For modern apps keep runtime permissions unchanged.
10087                        grant = GRANT_RUNTIME;
10088                    }
10089                } break;
10090
10091                case PermissionInfo.PROTECTION_SIGNATURE: {
10092                    // For all apps signature permissions are install time ones.
10093                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10094                    if (allowedSig) {
10095                        grant = GRANT_INSTALL;
10096                    }
10097                } break;
10098            }
10099
10100            if (DEBUG_INSTALL) {
10101                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10102            }
10103
10104            if (grant != GRANT_DENIED) {
10105                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10106                    // If this is an existing, non-system package, then
10107                    // we can't add any new permissions to it.
10108                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10109                        // Except...  if this is a permission that was added
10110                        // to the platform (note: need to only do this when
10111                        // updating the platform).
10112                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10113                            grant = GRANT_DENIED;
10114                        }
10115                    }
10116                }
10117
10118                switch (grant) {
10119                    case GRANT_INSTALL: {
10120                        // Revoke this as runtime permission to handle the case of
10121                        // a runtime permission being downgraded to an install one.
10122                        // Also in permission review mode we keep dangerous permissions
10123                        // for legacy apps
10124                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10125                            if (origPermissions.getRuntimePermissionState(
10126                                    bp.name, userId) != null) {
10127                                // Revoke the runtime permission and clear the flags.
10128                                origPermissions.revokeRuntimePermission(bp, userId);
10129                                origPermissions.updatePermissionFlags(bp, userId,
10130                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10131                                // If we revoked a permission permission, we have to write.
10132                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10133                                        changedRuntimePermissionUserIds, userId);
10134                            }
10135                        }
10136                        // Grant an install permission.
10137                        if (permissionsState.grantInstallPermission(bp) !=
10138                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10139                            changedInstallPermission = true;
10140                        }
10141                    } break;
10142
10143                    case GRANT_RUNTIME: {
10144                        // Grant previously granted runtime permissions.
10145                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10146                            PermissionState permissionState = origPermissions
10147                                    .getRuntimePermissionState(bp.name, userId);
10148                            int flags = permissionState != null
10149                                    ? permissionState.getFlags() : 0;
10150                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10151                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10152                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10153                                    // If we cannot put the permission as it was, we have to write.
10154                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10155                                            changedRuntimePermissionUserIds, userId);
10156                                }
10157                                // If the app supports runtime permissions no need for a review.
10158                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10159                                        && appSupportsRuntimePermissions
10160                                        && (flags & PackageManager
10161                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10162                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10163                                    // Since we changed the flags, we have to write.
10164                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10165                                            changedRuntimePermissionUserIds, userId);
10166                                }
10167                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10168                                    && !appSupportsRuntimePermissions) {
10169                                // For legacy apps that need a permission review, every new
10170                                // runtime permission is granted but it is pending a review.
10171                                // We also need to review only platform defined runtime
10172                                // permissions as these are the only ones the platform knows
10173                                // how to disable the API to simulate revocation as legacy
10174                                // apps don't expect to run with revoked permissions.
10175                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10176                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10177                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10178                                        // We changed the flags, hence have to write.
10179                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10180                                                changedRuntimePermissionUserIds, userId);
10181                                    }
10182                                }
10183                                if (permissionsState.grantRuntimePermission(bp, userId)
10184                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10185                                    // We changed the permission, hence have to write.
10186                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10187                                            changedRuntimePermissionUserIds, userId);
10188                                }
10189                            }
10190                            // Propagate the permission flags.
10191                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10192                        }
10193                    } break;
10194
10195                    case GRANT_UPGRADE: {
10196                        // Grant runtime permissions for a previously held install permission.
10197                        PermissionState permissionState = origPermissions
10198                                .getInstallPermissionState(bp.name);
10199                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10200
10201                        if (origPermissions.revokeInstallPermission(bp)
10202                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10203                            // We will be transferring the permission flags, so clear them.
10204                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10205                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10206                            changedInstallPermission = true;
10207                        }
10208
10209                        // If the permission is not to be promoted to runtime we ignore it and
10210                        // also its other flags as they are not applicable to install permissions.
10211                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10212                            for (int userId : currentUserIds) {
10213                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10214                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10215                                    // Transfer the permission flags.
10216                                    permissionsState.updatePermissionFlags(bp, userId,
10217                                            flags, flags);
10218                                    // If we granted the permission, we have to write.
10219                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10220                                            changedRuntimePermissionUserIds, userId);
10221                                }
10222                            }
10223                        }
10224                    } break;
10225
10226                    default: {
10227                        if (packageOfInterest == null
10228                                || packageOfInterest.equals(pkg.packageName)) {
10229                            Slog.w(TAG, "Not granting permission " + perm
10230                                    + " to package " + pkg.packageName
10231                                    + " because it was previously installed without");
10232                        }
10233                    } break;
10234                }
10235            } else {
10236                if (permissionsState.revokeInstallPermission(bp) !=
10237                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10238                    // Also drop the permission flags.
10239                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10240                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10241                    changedInstallPermission = true;
10242                    Slog.i(TAG, "Un-granting permission " + perm
10243                            + " from package " + pkg.packageName
10244                            + " (protectionLevel=" + bp.protectionLevel
10245                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10246                            + ")");
10247                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10248                    // Don't print warning for app op permissions, since it is fine for them
10249                    // not to be granted, there is a UI for the user to decide.
10250                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10251                        Slog.w(TAG, "Not granting permission " + perm
10252                                + " to package " + pkg.packageName
10253                                + " (protectionLevel=" + bp.protectionLevel
10254                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10255                                + ")");
10256                    }
10257                }
10258            }
10259        }
10260
10261        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10262                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10263            // This is the first that we have heard about this package, so the
10264            // permissions we have now selected are fixed until explicitly
10265            // changed.
10266            ps.installPermissionsFixed = true;
10267        }
10268
10269        // Persist the runtime permissions state for users with changes. If permissions
10270        // were revoked because no app in the shared user declares them we have to
10271        // write synchronously to avoid losing runtime permissions state.
10272        for (int userId : changedRuntimePermissionUserIds) {
10273            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10274        }
10275
10276        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10277    }
10278
10279    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10280        boolean allowed = false;
10281        final int NP = PackageParser.NEW_PERMISSIONS.length;
10282        for (int ip=0; ip<NP; ip++) {
10283            final PackageParser.NewPermissionInfo npi
10284                    = PackageParser.NEW_PERMISSIONS[ip];
10285            if (npi.name.equals(perm)
10286                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10287                allowed = true;
10288                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10289                        + pkg.packageName);
10290                break;
10291            }
10292        }
10293        return allowed;
10294    }
10295
10296    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10297            BasePermission bp, PermissionsState origPermissions) {
10298        boolean allowed;
10299        allowed = (compareSignatures(
10300                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10301                        == PackageManager.SIGNATURE_MATCH)
10302                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10303                        == PackageManager.SIGNATURE_MATCH);
10304        if (!allowed && (bp.protectionLevel
10305                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10306            if (isSystemApp(pkg)) {
10307                // For updated system applications, a system permission
10308                // is granted only if it had been defined by the original application.
10309                if (pkg.isUpdatedSystemApp()) {
10310                    final PackageSetting sysPs = mSettings
10311                            .getDisabledSystemPkgLPr(pkg.packageName);
10312                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10313                        // If the original was granted this permission, we take
10314                        // that grant decision as read and propagate it to the
10315                        // update.
10316                        if (sysPs.isPrivileged()) {
10317                            allowed = true;
10318                        }
10319                    } else {
10320                        // The system apk may have been updated with an older
10321                        // version of the one on the data partition, but which
10322                        // granted a new system permission that it didn't have
10323                        // before.  In this case we do want to allow the app to
10324                        // now get the new permission if the ancestral apk is
10325                        // privileged to get it.
10326                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10327                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10328                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10329                                    allowed = true;
10330                                    break;
10331                                }
10332                            }
10333                        }
10334                        // Also if a privileged parent package on the system image or any of
10335                        // its children requested a privileged permission, the updated child
10336                        // packages can also get the permission.
10337                        if (pkg.parentPackage != null) {
10338                            final PackageSetting disabledSysParentPs = mSettings
10339                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10340                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10341                                    && disabledSysParentPs.isPrivileged()) {
10342                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10343                                    allowed = true;
10344                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10345                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10346                                    for (int i = 0; i < count; i++) {
10347                                        PackageParser.Package disabledSysChildPkg =
10348                                                disabledSysParentPs.pkg.childPackages.get(i);
10349                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10350                                                perm)) {
10351                                            allowed = true;
10352                                            break;
10353                                        }
10354                                    }
10355                                }
10356                            }
10357                        }
10358                    }
10359                } else {
10360                    allowed = isPrivilegedApp(pkg);
10361                }
10362            }
10363        }
10364        if (!allowed) {
10365            if (!allowed && (bp.protectionLevel
10366                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10367                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10368                // If this was a previously normal/dangerous permission that got moved
10369                // to a system permission as part of the runtime permission redesign, then
10370                // we still want to blindly grant it to old apps.
10371                allowed = true;
10372            }
10373            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10374                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10375                // If this permission is to be granted to the system installer and
10376                // this app is an installer, then it gets the permission.
10377                allowed = true;
10378            }
10379            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10380                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10381                // If this permission is to be granted to the system verifier and
10382                // this app is a verifier, then it gets the permission.
10383                allowed = true;
10384            }
10385            if (!allowed && (bp.protectionLevel
10386                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10387                    && isSystemApp(pkg)) {
10388                // Any pre-installed system app is allowed to get this permission.
10389                allowed = true;
10390            }
10391            if (!allowed && (bp.protectionLevel
10392                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10393                // For development permissions, a development permission
10394                // is granted only if it was already granted.
10395                allowed = origPermissions.hasInstallPermission(perm);
10396            }
10397            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10398                    && pkg.packageName.equals(mSetupWizardPackage)) {
10399                // If this permission is to be granted to the system setup wizard and
10400                // this app is a setup wizard, then it gets the permission.
10401                allowed = true;
10402            }
10403        }
10404        return allowed;
10405    }
10406
10407    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10408        final int permCount = pkg.requestedPermissions.size();
10409        for (int j = 0; j < permCount; j++) {
10410            String requestedPermission = pkg.requestedPermissions.get(j);
10411            if (permission.equals(requestedPermission)) {
10412                return true;
10413            }
10414        }
10415        return false;
10416    }
10417
10418    final class ActivityIntentResolver
10419            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10420        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10421                boolean defaultOnly, int userId) {
10422            if (!sUserManager.exists(userId)) return null;
10423            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10424            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10425        }
10426
10427        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10428                int userId) {
10429            if (!sUserManager.exists(userId)) return null;
10430            mFlags = flags;
10431            return super.queryIntent(intent, resolvedType,
10432                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10433        }
10434
10435        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10436                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10437            if (!sUserManager.exists(userId)) return null;
10438            if (packageActivities == null) {
10439                return null;
10440            }
10441            mFlags = flags;
10442            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10443            final int N = packageActivities.size();
10444            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10445                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10446
10447            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10448            for (int i = 0; i < N; ++i) {
10449                intentFilters = packageActivities.get(i).intents;
10450                if (intentFilters != null && intentFilters.size() > 0) {
10451                    PackageParser.ActivityIntentInfo[] array =
10452                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10453                    intentFilters.toArray(array);
10454                    listCut.add(array);
10455                }
10456            }
10457            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10458        }
10459
10460        /**
10461         * Finds a privileged activity that matches the specified activity names.
10462         */
10463        private PackageParser.Activity findMatchingActivity(
10464                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10465            for (PackageParser.Activity sysActivity : activityList) {
10466                if (sysActivity.info.name.equals(activityInfo.name)) {
10467                    return sysActivity;
10468                }
10469                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10470                    return sysActivity;
10471                }
10472                if (sysActivity.info.targetActivity != null) {
10473                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10474                        return sysActivity;
10475                    }
10476                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10477                        return sysActivity;
10478                    }
10479                }
10480            }
10481            return null;
10482        }
10483
10484        public class IterGenerator<E> {
10485            public Iterator<E> generate(ActivityIntentInfo info) {
10486                return null;
10487            }
10488        }
10489
10490        public class ActionIterGenerator extends IterGenerator<String> {
10491            @Override
10492            public Iterator<String> generate(ActivityIntentInfo info) {
10493                return info.actionsIterator();
10494            }
10495        }
10496
10497        public class CategoriesIterGenerator extends IterGenerator<String> {
10498            @Override
10499            public Iterator<String> generate(ActivityIntentInfo info) {
10500                return info.categoriesIterator();
10501            }
10502        }
10503
10504        public class SchemesIterGenerator extends IterGenerator<String> {
10505            @Override
10506            public Iterator<String> generate(ActivityIntentInfo info) {
10507                return info.schemesIterator();
10508            }
10509        }
10510
10511        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10512            @Override
10513            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10514                return info.authoritiesIterator();
10515            }
10516        }
10517
10518        /**
10519         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10520         * MODIFIED. Do not pass in a list that should not be changed.
10521         */
10522        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10523                IterGenerator<T> generator, Iterator<T> searchIterator) {
10524            // loop through the set of actions; every one must be found in the intent filter
10525            while (searchIterator.hasNext()) {
10526                // we must have at least one filter in the list to consider a match
10527                if (intentList.size() == 0) {
10528                    break;
10529                }
10530
10531                final T searchAction = searchIterator.next();
10532
10533                // loop through the set of intent filters
10534                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10535                while (intentIter.hasNext()) {
10536                    final ActivityIntentInfo intentInfo = intentIter.next();
10537                    boolean selectionFound = false;
10538
10539                    // loop through the intent filter's selection criteria; at least one
10540                    // of them must match the searched criteria
10541                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10542                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10543                        final T intentSelection = intentSelectionIter.next();
10544                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10545                            selectionFound = true;
10546                            break;
10547                        }
10548                    }
10549
10550                    // the selection criteria wasn't found in this filter's set; this filter
10551                    // is not a potential match
10552                    if (!selectionFound) {
10553                        intentIter.remove();
10554                    }
10555                }
10556            }
10557        }
10558
10559        private boolean isProtectedAction(ActivityIntentInfo filter) {
10560            final Iterator<String> actionsIter = filter.actionsIterator();
10561            while (actionsIter != null && actionsIter.hasNext()) {
10562                final String filterAction = actionsIter.next();
10563                if (PROTECTED_ACTIONS.contains(filterAction)) {
10564                    return true;
10565                }
10566            }
10567            return false;
10568        }
10569
10570        /**
10571         * Adjusts the priority of the given intent filter according to policy.
10572         * <p>
10573         * <ul>
10574         * <li>The priority for non privileged applications is capped to '0'</li>
10575         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10576         * <li>The priority for unbundled updates to privileged applications is capped to the
10577         *      priority defined on the system partition</li>
10578         * </ul>
10579         * <p>
10580         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10581         * allowed to obtain any priority on any action.
10582         */
10583        private void adjustPriority(
10584                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10585            // nothing to do; priority is fine as-is
10586            if (intent.getPriority() <= 0) {
10587                return;
10588            }
10589
10590            final ActivityInfo activityInfo = intent.activity.info;
10591            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10592
10593            final boolean privilegedApp =
10594                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10595            if (!privilegedApp) {
10596                // non-privileged applications can never define a priority >0
10597                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10598                        + " package: " + applicationInfo.packageName
10599                        + " activity: " + intent.activity.className
10600                        + " origPrio: " + intent.getPriority());
10601                intent.setPriority(0);
10602                return;
10603            }
10604
10605            if (systemActivities == null) {
10606                // the system package is not disabled; we're parsing the system partition
10607                if (isProtectedAction(intent)) {
10608                    if (mDeferProtectedFilters) {
10609                        // We can't deal with these just yet. No component should ever obtain a
10610                        // >0 priority for a protected actions, with ONE exception -- the setup
10611                        // wizard. The setup wizard, however, cannot be known until we're able to
10612                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10613                        // until all intent filters have been processed. Chicken, meet egg.
10614                        // Let the filter temporarily have a high priority and rectify the
10615                        // priorities after all system packages have been scanned.
10616                        mProtectedFilters.add(intent);
10617                        if (DEBUG_FILTERS) {
10618                            Slog.i(TAG, "Protected action; save for later;"
10619                                    + " package: " + applicationInfo.packageName
10620                                    + " activity: " + intent.activity.className
10621                                    + " origPrio: " + intent.getPriority());
10622                        }
10623                        return;
10624                    } else {
10625                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10626                            Slog.i(TAG, "No setup wizard;"
10627                                + " All protected intents capped to priority 0");
10628                        }
10629                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10630                            if (DEBUG_FILTERS) {
10631                                Slog.i(TAG, "Found setup wizard;"
10632                                    + " allow priority " + intent.getPriority() + ";"
10633                                    + " package: " + intent.activity.info.packageName
10634                                    + " activity: " + intent.activity.className
10635                                    + " priority: " + intent.getPriority());
10636                            }
10637                            // setup wizard gets whatever it wants
10638                            return;
10639                        }
10640                        Slog.w(TAG, "Protected action; cap priority to 0;"
10641                                + " package: " + intent.activity.info.packageName
10642                                + " activity: " + intent.activity.className
10643                                + " origPrio: " + intent.getPriority());
10644                        intent.setPriority(0);
10645                        return;
10646                    }
10647                }
10648                // privileged apps on the system image get whatever priority they request
10649                return;
10650            }
10651
10652            // privileged app unbundled update ... try to find the same activity
10653            final PackageParser.Activity foundActivity =
10654                    findMatchingActivity(systemActivities, activityInfo);
10655            if (foundActivity == null) {
10656                // this is a new activity; it cannot obtain >0 priority
10657                if (DEBUG_FILTERS) {
10658                    Slog.i(TAG, "New activity; cap priority to 0;"
10659                            + " package: " + applicationInfo.packageName
10660                            + " activity: " + intent.activity.className
10661                            + " origPrio: " + intent.getPriority());
10662                }
10663                intent.setPriority(0);
10664                return;
10665            }
10666
10667            // found activity, now check for filter equivalence
10668
10669            // a shallow copy is enough; we modify the list, not its contents
10670            final List<ActivityIntentInfo> intentListCopy =
10671                    new ArrayList<>(foundActivity.intents);
10672            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10673
10674            // find matching action subsets
10675            final Iterator<String> actionsIterator = intent.actionsIterator();
10676            if (actionsIterator != null) {
10677                getIntentListSubset(
10678                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10679                if (intentListCopy.size() == 0) {
10680                    // no more intents to match; we're not equivalent
10681                    if (DEBUG_FILTERS) {
10682                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10683                                + " package: " + applicationInfo.packageName
10684                                + " activity: " + intent.activity.className
10685                                + " origPrio: " + intent.getPriority());
10686                    }
10687                    intent.setPriority(0);
10688                    return;
10689                }
10690            }
10691
10692            // find matching category subsets
10693            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10694            if (categoriesIterator != null) {
10695                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10696                        categoriesIterator);
10697                if (intentListCopy.size() == 0) {
10698                    // no more intents to match; we're not equivalent
10699                    if (DEBUG_FILTERS) {
10700                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10701                                + " package: " + applicationInfo.packageName
10702                                + " activity: " + intent.activity.className
10703                                + " origPrio: " + intent.getPriority());
10704                    }
10705                    intent.setPriority(0);
10706                    return;
10707                }
10708            }
10709
10710            // find matching schemes subsets
10711            final Iterator<String> schemesIterator = intent.schemesIterator();
10712            if (schemesIterator != null) {
10713                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10714                        schemesIterator);
10715                if (intentListCopy.size() == 0) {
10716                    // no more intents to match; we're not equivalent
10717                    if (DEBUG_FILTERS) {
10718                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10719                                + " package: " + applicationInfo.packageName
10720                                + " activity: " + intent.activity.className
10721                                + " origPrio: " + intent.getPriority());
10722                    }
10723                    intent.setPriority(0);
10724                    return;
10725                }
10726            }
10727
10728            // find matching authorities subsets
10729            final Iterator<IntentFilter.AuthorityEntry>
10730                    authoritiesIterator = intent.authoritiesIterator();
10731            if (authoritiesIterator != null) {
10732                getIntentListSubset(intentListCopy,
10733                        new AuthoritiesIterGenerator(),
10734                        authoritiesIterator);
10735                if (intentListCopy.size() == 0) {
10736                    // no more intents to match; we're not equivalent
10737                    if (DEBUG_FILTERS) {
10738                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10739                                + " package: " + applicationInfo.packageName
10740                                + " activity: " + intent.activity.className
10741                                + " origPrio: " + intent.getPriority());
10742                    }
10743                    intent.setPriority(0);
10744                    return;
10745                }
10746            }
10747
10748            // we found matching filter(s); app gets the max priority of all intents
10749            int cappedPriority = 0;
10750            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10751                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10752            }
10753            if (intent.getPriority() > cappedPriority) {
10754                if (DEBUG_FILTERS) {
10755                    Slog.i(TAG, "Found matching filter(s);"
10756                            + " cap priority to " + cappedPriority + ";"
10757                            + " package: " + applicationInfo.packageName
10758                            + " activity: " + intent.activity.className
10759                            + " origPrio: " + intent.getPriority());
10760                }
10761                intent.setPriority(cappedPriority);
10762                return;
10763            }
10764            // all this for nothing; the requested priority was <= what was on the system
10765        }
10766
10767        public final void addActivity(PackageParser.Activity a, String type) {
10768            mActivities.put(a.getComponentName(), a);
10769            if (DEBUG_SHOW_INFO)
10770                Log.v(
10771                TAG, "  " + type + " " +
10772                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10773            if (DEBUG_SHOW_INFO)
10774                Log.v(TAG, "    Class=" + a.info.name);
10775            final int NI = a.intents.size();
10776            for (int j=0; j<NI; j++) {
10777                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10778                if ("activity".equals(type)) {
10779                    final PackageSetting ps =
10780                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10781                    final List<PackageParser.Activity> systemActivities =
10782                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10783                    adjustPriority(systemActivities, intent);
10784                }
10785                if (DEBUG_SHOW_INFO) {
10786                    Log.v(TAG, "    IntentFilter:");
10787                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10788                }
10789                if (!intent.debugCheck()) {
10790                    Log.w(TAG, "==> For Activity " + a.info.name);
10791                }
10792                addFilter(intent);
10793            }
10794        }
10795
10796        public final void removeActivity(PackageParser.Activity a, String type) {
10797            mActivities.remove(a.getComponentName());
10798            if (DEBUG_SHOW_INFO) {
10799                Log.v(TAG, "  " + type + " "
10800                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10801                                : a.info.name) + ":");
10802                Log.v(TAG, "    Class=" + a.info.name);
10803            }
10804            final int NI = a.intents.size();
10805            for (int j=0; j<NI; j++) {
10806                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10807                if (DEBUG_SHOW_INFO) {
10808                    Log.v(TAG, "    IntentFilter:");
10809                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10810                }
10811                removeFilter(intent);
10812            }
10813        }
10814
10815        @Override
10816        protected boolean allowFilterResult(
10817                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10818            ActivityInfo filterAi = filter.activity.info;
10819            for (int i=dest.size()-1; i>=0; i--) {
10820                ActivityInfo destAi = dest.get(i).activityInfo;
10821                if (destAi.name == filterAi.name
10822                        && destAi.packageName == filterAi.packageName) {
10823                    return false;
10824                }
10825            }
10826            return true;
10827        }
10828
10829        @Override
10830        protected ActivityIntentInfo[] newArray(int size) {
10831            return new ActivityIntentInfo[size];
10832        }
10833
10834        @Override
10835        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10836            if (!sUserManager.exists(userId)) return true;
10837            PackageParser.Package p = filter.activity.owner;
10838            if (p != null) {
10839                PackageSetting ps = (PackageSetting)p.mExtras;
10840                if (ps != null) {
10841                    // System apps are never considered stopped for purposes of
10842                    // filtering, because there may be no way for the user to
10843                    // actually re-launch them.
10844                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10845                            && ps.getStopped(userId);
10846                }
10847            }
10848            return false;
10849        }
10850
10851        @Override
10852        protected boolean isPackageForFilter(String packageName,
10853                PackageParser.ActivityIntentInfo info) {
10854            return packageName.equals(info.activity.owner.packageName);
10855        }
10856
10857        @Override
10858        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10859                int match, int userId) {
10860            if (!sUserManager.exists(userId)) return null;
10861            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10862                return null;
10863            }
10864            final PackageParser.Activity activity = info.activity;
10865            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10866            if (ps == null) {
10867                return null;
10868            }
10869            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10870                    ps.readUserState(userId), userId);
10871            if (ai == null) {
10872                return null;
10873            }
10874            final ResolveInfo res = new ResolveInfo();
10875            res.activityInfo = ai;
10876            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10877                res.filter = info;
10878            }
10879            if (info != null) {
10880                res.handleAllWebDataURI = info.handleAllWebDataURI();
10881            }
10882            res.priority = info.getPriority();
10883            res.preferredOrder = activity.owner.mPreferredOrder;
10884            //System.out.println("Result: " + res.activityInfo.className +
10885            //                   " = " + res.priority);
10886            res.match = match;
10887            res.isDefault = info.hasDefault;
10888            res.labelRes = info.labelRes;
10889            res.nonLocalizedLabel = info.nonLocalizedLabel;
10890            if (userNeedsBadging(userId)) {
10891                res.noResourceId = true;
10892            } else {
10893                res.icon = info.icon;
10894            }
10895            res.iconResourceId = info.icon;
10896            res.system = res.activityInfo.applicationInfo.isSystemApp();
10897            return res;
10898        }
10899
10900        @Override
10901        protected void sortResults(List<ResolveInfo> results) {
10902            Collections.sort(results, mResolvePrioritySorter);
10903        }
10904
10905        @Override
10906        protected void dumpFilter(PrintWriter out, String prefix,
10907                PackageParser.ActivityIntentInfo filter) {
10908            out.print(prefix); out.print(
10909                    Integer.toHexString(System.identityHashCode(filter.activity)));
10910                    out.print(' ');
10911                    filter.activity.printComponentShortName(out);
10912                    out.print(" filter ");
10913                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10914        }
10915
10916        @Override
10917        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10918            return filter.activity;
10919        }
10920
10921        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10922            PackageParser.Activity activity = (PackageParser.Activity)label;
10923            out.print(prefix); out.print(
10924                    Integer.toHexString(System.identityHashCode(activity)));
10925                    out.print(' ');
10926                    activity.printComponentShortName(out);
10927            if (count > 1) {
10928                out.print(" ("); out.print(count); out.print(" filters)");
10929            }
10930            out.println();
10931        }
10932
10933        // Keys are String (activity class name), values are Activity.
10934        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10935                = new ArrayMap<ComponentName, PackageParser.Activity>();
10936        private int mFlags;
10937    }
10938
10939    private final class ServiceIntentResolver
10940            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10941        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10942                boolean defaultOnly, int userId) {
10943            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10944            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10945        }
10946
10947        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10948                int userId) {
10949            if (!sUserManager.exists(userId)) return null;
10950            mFlags = flags;
10951            return super.queryIntent(intent, resolvedType,
10952                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10953        }
10954
10955        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10956                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10957            if (!sUserManager.exists(userId)) return null;
10958            if (packageServices == null) {
10959                return null;
10960            }
10961            mFlags = flags;
10962            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10963            final int N = packageServices.size();
10964            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10965                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10966
10967            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10968            for (int i = 0; i < N; ++i) {
10969                intentFilters = packageServices.get(i).intents;
10970                if (intentFilters != null && intentFilters.size() > 0) {
10971                    PackageParser.ServiceIntentInfo[] array =
10972                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10973                    intentFilters.toArray(array);
10974                    listCut.add(array);
10975                }
10976            }
10977            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10978        }
10979
10980        public final void addService(PackageParser.Service s) {
10981            mServices.put(s.getComponentName(), s);
10982            if (DEBUG_SHOW_INFO) {
10983                Log.v(TAG, "  "
10984                        + (s.info.nonLocalizedLabel != null
10985                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10986                Log.v(TAG, "    Class=" + s.info.name);
10987            }
10988            final int NI = s.intents.size();
10989            int j;
10990            for (j=0; j<NI; j++) {
10991                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10992                if (DEBUG_SHOW_INFO) {
10993                    Log.v(TAG, "    IntentFilter:");
10994                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10995                }
10996                if (!intent.debugCheck()) {
10997                    Log.w(TAG, "==> For Service " + s.info.name);
10998                }
10999                addFilter(intent);
11000            }
11001        }
11002
11003        public final void removeService(PackageParser.Service s) {
11004            mServices.remove(s.getComponentName());
11005            if (DEBUG_SHOW_INFO) {
11006                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11007                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11008                Log.v(TAG, "    Class=" + s.info.name);
11009            }
11010            final int NI = s.intents.size();
11011            int j;
11012            for (j=0; j<NI; j++) {
11013                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11014                if (DEBUG_SHOW_INFO) {
11015                    Log.v(TAG, "    IntentFilter:");
11016                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11017                }
11018                removeFilter(intent);
11019            }
11020        }
11021
11022        @Override
11023        protected boolean allowFilterResult(
11024                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11025            ServiceInfo filterSi = filter.service.info;
11026            for (int i=dest.size()-1; i>=0; i--) {
11027                ServiceInfo destAi = dest.get(i).serviceInfo;
11028                if (destAi.name == filterSi.name
11029                        && destAi.packageName == filterSi.packageName) {
11030                    return false;
11031                }
11032            }
11033            return true;
11034        }
11035
11036        @Override
11037        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11038            return new PackageParser.ServiceIntentInfo[size];
11039        }
11040
11041        @Override
11042        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11043            if (!sUserManager.exists(userId)) return true;
11044            PackageParser.Package p = filter.service.owner;
11045            if (p != null) {
11046                PackageSetting ps = (PackageSetting)p.mExtras;
11047                if (ps != null) {
11048                    // System apps are never considered stopped for purposes of
11049                    // filtering, because there may be no way for the user to
11050                    // actually re-launch them.
11051                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11052                            && ps.getStopped(userId);
11053                }
11054            }
11055            return false;
11056        }
11057
11058        @Override
11059        protected boolean isPackageForFilter(String packageName,
11060                PackageParser.ServiceIntentInfo info) {
11061            return packageName.equals(info.service.owner.packageName);
11062        }
11063
11064        @Override
11065        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11066                int match, int userId) {
11067            if (!sUserManager.exists(userId)) return null;
11068            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11069            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11070                return null;
11071            }
11072            final PackageParser.Service service = info.service;
11073            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11074            if (ps == null) {
11075                return null;
11076            }
11077            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11078                    ps.readUserState(userId), userId);
11079            if (si == null) {
11080                return null;
11081            }
11082            final ResolveInfo res = new ResolveInfo();
11083            res.serviceInfo = si;
11084            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11085                res.filter = filter;
11086            }
11087            res.priority = info.getPriority();
11088            res.preferredOrder = service.owner.mPreferredOrder;
11089            res.match = match;
11090            res.isDefault = info.hasDefault;
11091            res.labelRes = info.labelRes;
11092            res.nonLocalizedLabel = info.nonLocalizedLabel;
11093            res.icon = info.icon;
11094            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11095            return res;
11096        }
11097
11098        @Override
11099        protected void sortResults(List<ResolveInfo> results) {
11100            Collections.sort(results, mResolvePrioritySorter);
11101        }
11102
11103        @Override
11104        protected void dumpFilter(PrintWriter out, String prefix,
11105                PackageParser.ServiceIntentInfo filter) {
11106            out.print(prefix); out.print(
11107                    Integer.toHexString(System.identityHashCode(filter.service)));
11108                    out.print(' ');
11109                    filter.service.printComponentShortName(out);
11110                    out.print(" filter ");
11111                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11112        }
11113
11114        @Override
11115        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11116            return filter.service;
11117        }
11118
11119        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11120            PackageParser.Service service = (PackageParser.Service)label;
11121            out.print(prefix); out.print(
11122                    Integer.toHexString(System.identityHashCode(service)));
11123                    out.print(' ');
11124                    service.printComponentShortName(out);
11125            if (count > 1) {
11126                out.print(" ("); out.print(count); out.print(" filters)");
11127            }
11128            out.println();
11129        }
11130
11131//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11132//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11133//            final List<ResolveInfo> retList = Lists.newArrayList();
11134//            while (i.hasNext()) {
11135//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11136//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11137//                    retList.add(resolveInfo);
11138//                }
11139//            }
11140//            return retList;
11141//        }
11142
11143        // Keys are String (activity class name), values are Activity.
11144        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11145                = new ArrayMap<ComponentName, PackageParser.Service>();
11146        private int mFlags;
11147    };
11148
11149    private final class ProviderIntentResolver
11150            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11151        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11152                boolean defaultOnly, int userId) {
11153            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11154            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11155        }
11156
11157        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11158                int userId) {
11159            if (!sUserManager.exists(userId))
11160                return null;
11161            mFlags = flags;
11162            return super.queryIntent(intent, resolvedType,
11163                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11164        }
11165
11166        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11167                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11168            if (!sUserManager.exists(userId))
11169                return null;
11170            if (packageProviders == null) {
11171                return null;
11172            }
11173            mFlags = flags;
11174            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11175            final int N = packageProviders.size();
11176            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11177                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11178
11179            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11180            for (int i = 0; i < N; ++i) {
11181                intentFilters = packageProviders.get(i).intents;
11182                if (intentFilters != null && intentFilters.size() > 0) {
11183                    PackageParser.ProviderIntentInfo[] array =
11184                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11185                    intentFilters.toArray(array);
11186                    listCut.add(array);
11187                }
11188            }
11189            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11190        }
11191
11192        public final void addProvider(PackageParser.Provider p) {
11193            if (mProviders.containsKey(p.getComponentName())) {
11194                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11195                return;
11196            }
11197
11198            mProviders.put(p.getComponentName(), p);
11199            if (DEBUG_SHOW_INFO) {
11200                Log.v(TAG, "  "
11201                        + (p.info.nonLocalizedLabel != null
11202                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11203                Log.v(TAG, "    Class=" + p.info.name);
11204            }
11205            final int NI = p.intents.size();
11206            int j;
11207            for (j = 0; j < NI; j++) {
11208                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11209                if (DEBUG_SHOW_INFO) {
11210                    Log.v(TAG, "    IntentFilter:");
11211                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11212                }
11213                if (!intent.debugCheck()) {
11214                    Log.w(TAG, "==> For Provider " + p.info.name);
11215                }
11216                addFilter(intent);
11217            }
11218        }
11219
11220        public final void removeProvider(PackageParser.Provider p) {
11221            mProviders.remove(p.getComponentName());
11222            if (DEBUG_SHOW_INFO) {
11223                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11224                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11225                Log.v(TAG, "    Class=" + p.info.name);
11226            }
11227            final int NI = p.intents.size();
11228            int j;
11229            for (j = 0; j < NI; j++) {
11230                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11231                if (DEBUG_SHOW_INFO) {
11232                    Log.v(TAG, "    IntentFilter:");
11233                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11234                }
11235                removeFilter(intent);
11236            }
11237        }
11238
11239        @Override
11240        protected boolean allowFilterResult(
11241                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11242            ProviderInfo filterPi = filter.provider.info;
11243            for (int i = dest.size() - 1; i >= 0; i--) {
11244                ProviderInfo destPi = dest.get(i).providerInfo;
11245                if (destPi.name == filterPi.name
11246                        && destPi.packageName == filterPi.packageName) {
11247                    return false;
11248                }
11249            }
11250            return true;
11251        }
11252
11253        @Override
11254        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11255            return new PackageParser.ProviderIntentInfo[size];
11256        }
11257
11258        @Override
11259        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11260            if (!sUserManager.exists(userId))
11261                return true;
11262            PackageParser.Package p = filter.provider.owner;
11263            if (p != null) {
11264                PackageSetting ps = (PackageSetting) p.mExtras;
11265                if (ps != null) {
11266                    // System apps are never considered stopped for purposes of
11267                    // filtering, because there may be no way for the user to
11268                    // actually re-launch them.
11269                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11270                            && ps.getStopped(userId);
11271                }
11272            }
11273            return false;
11274        }
11275
11276        @Override
11277        protected boolean isPackageForFilter(String packageName,
11278                PackageParser.ProviderIntentInfo info) {
11279            return packageName.equals(info.provider.owner.packageName);
11280        }
11281
11282        @Override
11283        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11284                int match, int userId) {
11285            if (!sUserManager.exists(userId))
11286                return null;
11287            final PackageParser.ProviderIntentInfo info = filter;
11288            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11289                return null;
11290            }
11291            final PackageParser.Provider provider = info.provider;
11292            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11293            if (ps == null) {
11294                return null;
11295            }
11296            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11297                    ps.readUserState(userId), userId);
11298            if (pi == null) {
11299                return null;
11300            }
11301            final ResolveInfo res = new ResolveInfo();
11302            res.providerInfo = pi;
11303            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11304                res.filter = filter;
11305            }
11306            res.priority = info.getPriority();
11307            res.preferredOrder = provider.owner.mPreferredOrder;
11308            res.match = match;
11309            res.isDefault = info.hasDefault;
11310            res.labelRes = info.labelRes;
11311            res.nonLocalizedLabel = info.nonLocalizedLabel;
11312            res.icon = info.icon;
11313            res.system = res.providerInfo.applicationInfo.isSystemApp();
11314            return res;
11315        }
11316
11317        @Override
11318        protected void sortResults(List<ResolveInfo> results) {
11319            Collections.sort(results, mResolvePrioritySorter);
11320        }
11321
11322        @Override
11323        protected void dumpFilter(PrintWriter out, String prefix,
11324                PackageParser.ProviderIntentInfo filter) {
11325            out.print(prefix);
11326            out.print(
11327                    Integer.toHexString(System.identityHashCode(filter.provider)));
11328            out.print(' ');
11329            filter.provider.printComponentShortName(out);
11330            out.print(" filter ");
11331            out.println(Integer.toHexString(System.identityHashCode(filter)));
11332        }
11333
11334        @Override
11335        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11336            return filter.provider;
11337        }
11338
11339        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11340            PackageParser.Provider provider = (PackageParser.Provider)label;
11341            out.print(prefix); out.print(
11342                    Integer.toHexString(System.identityHashCode(provider)));
11343                    out.print(' ');
11344                    provider.printComponentShortName(out);
11345            if (count > 1) {
11346                out.print(" ("); out.print(count); out.print(" filters)");
11347            }
11348            out.println();
11349        }
11350
11351        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11352                = new ArrayMap<ComponentName, PackageParser.Provider>();
11353        private int mFlags;
11354    }
11355
11356    private static final class EphemeralIntentResolver
11357            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11358        @Override
11359        protected EphemeralResolveIntentInfo[] newArray(int size) {
11360            return new EphemeralResolveIntentInfo[size];
11361        }
11362
11363        @Override
11364        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11365            return true;
11366        }
11367
11368        @Override
11369        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11370                int userId) {
11371            if (!sUserManager.exists(userId)) {
11372                return null;
11373            }
11374            return info.getEphemeralResolveInfo();
11375        }
11376    }
11377
11378    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11379            new Comparator<ResolveInfo>() {
11380        public int compare(ResolveInfo r1, ResolveInfo r2) {
11381            int v1 = r1.priority;
11382            int v2 = r2.priority;
11383            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11384            if (v1 != v2) {
11385                return (v1 > v2) ? -1 : 1;
11386            }
11387            v1 = r1.preferredOrder;
11388            v2 = r2.preferredOrder;
11389            if (v1 != v2) {
11390                return (v1 > v2) ? -1 : 1;
11391            }
11392            if (r1.isDefault != r2.isDefault) {
11393                return r1.isDefault ? -1 : 1;
11394            }
11395            v1 = r1.match;
11396            v2 = r2.match;
11397            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11398            if (v1 != v2) {
11399                return (v1 > v2) ? -1 : 1;
11400            }
11401            if (r1.system != r2.system) {
11402                return r1.system ? -1 : 1;
11403            }
11404            if (r1.activityInfo != null) {
11405                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11406            }
11407            if (r1.serviceInfo != null) {
11408                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11409            }
11410            if (r1.providerInfo != null) {
11411                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11412            }
11413            return 0;
11414        }
11415    };
11416
11417    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11418            new Comparator<ProviderInfo>() {
11419        public int compare(ProviderInfo p1, ProviderInfo p2) {
11420            final int v1 = p1.initOrder;
11421            final int v2 = p2.initOrder;
11422            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11423        }
11424    };
11425
11426    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11427            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11428            final int[] userIds) {
11429        mHandler.post(new Runnable() {
11430            @Override
11431            public void run() {
11432                try {
11433                    final IActivityManager am = ActivityManagerNative.getDefault();
11434                    if (am == null) return;
11435                    final int[] resolvedUserIds;
11436                    if (userIds == null) {
11437                        resolvedUserIds = am.getRunningUserIds();
11438                    } else {
11439                        resolvedUserIds = userIds;
11440                    }
11441                    for (int id : resolvedUserIds) {
11442                        final Intent intent = new Intent(action,
11443                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11444                        if (extras != null) {
11445                            intent.putExtras(extras);
11446                        }
11447                        if (targetPkg != null) {
11448                            intent.setPackage(targetPkg);
11449                        }
11450                        // Modify the UID when posting to other users
11451                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11452                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11453                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11454                            intent.putExtra(Intent.EXTRA_UID, uid);
11455                        }
11456                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11457                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11458                        if (DEBUG_BROADCASTS) {
11459                            RuntimeException here = new RuntimeException("here");
11460                            here.fillInStackTrace();
11461                            Slog.d(TAG, "Sending to user " + id + ": "
11462                                    + intent.toShortString(false, true, false, false)
11463                                    + " " + intent.getExtras(), here);
11464                        }
11465                        am.broadcastIntent(null, intent, null, finishedReceiver,
11466                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11467                                null, finishedReceiver != null, false, id);
11468                    }
11469                } catch (RemoteException ex) {
11470                }
11471            }
11472        });
11473    }
11474
11475    /**
11476     * Check if the external storage media is available. This is true if there
11477     * is a mounted external storage medium or if the external storage is
11478     * emulated.
11479     */
11480    private boolean isExternalMediaAvailable() {
11481        return mMediaMounted || Environment.isExternalStorageEmulated();
11482    }
11483
11484    @Override
11485    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11486        // writer
11487        synchronized (mPackages) {
11488            if (!isExternalMediaAvailable()) {
11489                // If the external storage is no longer mounted at this point,
11490                // the caller may not have been able to delete all of this
11491                // packages files and can not delete any more.  Bail.
11492                return null;
11493            }
11494            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11495            if (lastPackage != null) {
11496                pkgs.remove(lastPackage);
11497            }
11498            if (pkgs.size() > 0) {
11499                return pkgs.get(0);
11500            }
11501        }
11502        return null;
11503    }
11504
11505    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11506        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11507                userId, andCode ? 1 : 0, packageName);
11508        if (mSystemReady) {
11509            msg.sendToTarget();
11510        } else {
11511            if (mPostSystemReadyMessages == null) {
11512                mPostSystemReadyMessages = new ArrayList<>();
11513            }
11514            mPostSystemReadyMessages.add(msg);
11515        }
11516    }
11517
11518    void startCleaningPackages() {
11519        // reader
11520        if (!isExternalMediaAvailable()) {
11521            return;
11522        }
11523        synchronized (mPackages) {
11524            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11525                return;
11526            }
11527        }
11528        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11529        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11530        IActivityManager am = ActivityManagerNative.getDefault();
11531        if (am != null) {
11532            try {
11533                am.startService(null, intent, null, mContext.getOpPackageName(),
11534                        UserHandle.USER_SYSTEM);
11535            } catch (RemoteException e) {
11536            }
11537        }
11538    }
11539
11540    @Override
11541    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11542            int installFlags, String installerPackageName, int userId) {
11543        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11544
11545        final int callingUid = Binder.getCallingUid();
11546        enforceCrossUserPermission(callingUid, userId,
11547                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11548
11549        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11550            try {
11551                if (observer != null) {
11552                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11553                }
11554            } catch (RemoteException re) {
11555            }
11556            return;
11557        }
11558
11559        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11560            installFlags |= PackageManager.INSTALL_FROM_ADB;
11561
11562        } else {
11563            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11564            // about installerPackageName.
11565
11566            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11567            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11568        }
11569
11570        UserHandle user;
11571        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11572            user = UserHandle.ALL;
11573        } else {
11574            user = new UserHandle(userId);
11575        }
11576
11577        // Only system components can circumvent runtime permissions when installing.
11578        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11579                && mContext.checkCallingOrSelfPermission(Manifest.permission
11580                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11581            throw new SecurityException("You need the "
11582                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11583                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11584        }
11585
11586        final File originFile = new File(originPath);
11587        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11588
11589        final Message msg = mHandler.obtainMessage(INIT_COPY);
11590        final VerificationInfo verificationInfo = new VerificationInfo(
11591                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11592        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11593                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11594                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11595                null /*certificates*/);
11596        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11597        msg.obj = params;
11598
11599        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11600                System.identityHashCode(msg.obj));
11601        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11602                System.identityHashCode(msg.obj));
11603
11604        mHandler.sendMessage(msg);
11605    }
11606
11607    void installStage(String packageName, File stagedDir, String stagedCid,
11608            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11609            String installerPackageName, int installerUid, UserHandle user,
11610            Certificate[][] certificates) {
11611        if (DEBUG_EPHEMERAL) {
11612            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11613                Slog.d(TAG, "Ephemeral install of " + packageName);
11614            }
11615        }
11616        final VerificationInfo verificationInfo = new VerificationInfo(
11617                sessionParams.originatingUri, sessionParams.referrerUri,
11618                sessionParams.originatingUid, installerUid);
11619
11620        final OriginInfo origin;
11621        if (stagedDir != null) {
11622            origin = OriginInfo.fromStagedFile(stagedDir);
11623        } else {
11624            origin = OriginInfo.fromStagedContainer(stagedCid);
11625        }
11626
11627        final Message msg = mHandler.obtainMessage(INIT_COPY);
11628        final InstallParams params = new InstallParams(origin, null, observer,
11629                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11630                verificationInfo, user, sessionParams.abiOverride,
11631                sessionParams.grantedRuntimePermissions, certificates);
11632        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11633        msg.obj = params;
11634
11635        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11636                System.identityHashCode(msg.obj));
11637        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11638                System.identityHashCode(msg.obj));
11639
11640        mHandler.sendMessage(msg);
11641    }
11642
11643    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11644            int userId) {
11645        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11646        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11647    }
11648
11649    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11650            int appId, int userId) {
11651        Bundle extras = new Bundle(1);
11652        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11653
11654        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11655                packageName, extras, 0, null, null, new int[] {userId});
11656        try {
11657            IActivityManager am = ActivityManagerNative.getDefault();
11658            if (isSystem && am.isUserRunning(userId, 0)) {
11659                // The just-installed/enabled app is bundled on the system, so presumed
11660                // to be able to run automatically without needing an explicit launch.
11661                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11662                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11663                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11664                        .setPackage(packageName);
11665                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11666                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11667            }
11668        } catch (RemoteException e) {
11669            // shouldn't happen
11670            Slog.w(TAG, "Unable to bootstrap installed package", e);
11671        }
11672    }
11673
11674    @Override
11675    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11676            int userId) {
11677        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11678        PackageSetting pkgSetting;
11679        final int uid = Binder.getCallingUid();
11680        enforceCrossUserPermission(uid, userId,
11681                true /* requireFullPermission */, true /* checkShell */,
11682                "setApplicationHiddenSetting for user " + userId);
11683
11684        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11685            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11686            return false;
11687        }
11688
11689        long callingId = Binder.clearCallingIdentity();
11690        try {
11691            boolean sendAdded = false;
11692            boolean sendRemoved = false;
11693            // writer
11694            synchronized (mPackages) {
11695                pkgSetting = mSettings.mPackages.get(packageName);
11696                if (pkgSetting == null) {
11697                    return false;
11698                }
11699                // Only allow protected packages to hide themselves.
11700                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11701                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11702                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11703                    return false;
11704                }
11705                if (pkgSetting.getHidden(userId) != hidden) {
11706                    pkgSetting.setHidden(hidden, userId);
11707                    mSettings.writePackageRestrictionsLPr(userId);
11708                    if (hidden) {
11709                        sendRemoved = true;
11710                    } else {
11711                        sendAdded = true;
11712                    }
11713                }
11714            }
11715            if (sendAdded) {
11716                sendPackageAddedForUser(packageName, pkgSetting, userId);
11717                return true;
11718            }
11719            if (sendRemoved) {
11720                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11721                        "hiding pkg");
11722                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11723                return true;
11724            }
11725        } finally {
11726            Binder.restoreCallingIdentity(callingId);
11727        }
11728        return false;
11729    }
11730
11731    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11732            int userId) {
11733        final PackageRemovedInfo info = new PackageRemovedInfo();
11734        info.removedPackage = packageName;
11735        info.removedUsers = new int[] {userId};
11736        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11737        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11738    }
11739
11740    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11741        if (pkgList.length > 0) {
11742            Bundle extras = new Bundle(1);
11743            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11744
11745            sendPackageBroadcast(
11746                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11747                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11748                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11749                    new int[] {userId});
11750        }
11751    }
11752
11753    /**
11754     * Returns true if application is not found or there was an error. Otherwise it returns
11755     * the hidden state of the package for the given user.
11756     */
11757    @Override
11758    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11759        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11760        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11761                true /* requireFullPermission */, false /* checkShell */,
11762                "getApplicationHidden for user " + userId);
11763        PackageSetting pkgSetting;
11764        long callingId = Binder.clearCallingIdentity();
11765        try {
11766            // writer
11767            synchronized (mPackages) {
11768                pkgSetting = mSettings.mPackages.get(packageName);
11769                if (pkgSetting == null) {
11770                    return true;
11771                }
11772                return pkgSetting.getHidden(userId);
11773            }
11774        } finally {
11775            Binder.restoreCallingIdentity(callingId);
11776        }
11777    }
11778
11779    /**
11780     * @hide
11781     */
11782    @Override
11783    public int installExistingPackageAsUser(String packageName, int userId) {
11784        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11785                null);
11786        PackageSetting pkgSetting;
11787        final int uid = Binder.getCallingUid();
11788        enforceCrossUserPermission(uid, userId,
11789                true /* requireFullPermission */, true /* checkShell */,
11790                "installExistingPackage for user " + userId);
11791        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11792            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11793        }
11794
11795        long callingId = Binder.clearCallingIdentity();
11796        try {
11797            boolean installed = false;
11798
11799            // writer
11800            synchronized (mPackages) {
11801                pkgSetting = mSettings.mPackages.get(packageName);
11802                if (pkgSetting == null) {
11803                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11804                }
11805                if (!pkgSetting.getInstalled(userId)) {
11806                    pkgSetting.setInstalled(true, userId);
11807                    pkgSetting.setHidden(false, userId);
11808                    mSettings.writePackageRestrictionsLPr(userId);
11809                    installed = true;
11810                }
11811            }
11812
11813            if (installed) {
11814                if (pkgSetting.pkg != null) {
11815                    synchronized (mInstallLock) {
11816                        // We don't need to freeze for a brand new install
11817                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11818                    }
11819                }
11820                sendPackageAddedForUser(packageName, pkgSetting, userId);
11821            }
11822        } finally {
11823            Binder.restoreCallingIdentity(callingId);
11824        }
11825
11826        return PackageManager.INSTALL_SUCCEEDED;
11827    }
11828
11829    boolean isUserRestricted(int userId, String restrictionKey) {
11830        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11831        if (restrictions.getBoolean(restrictionKey, false)) {
11832            Log.w(TAG, "User is restricted: " + restrictionKey);
11833            return true;
11834        }
11835        return false;
11836    }
11837
11838    @Override
11839    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11840            int userId) {
11841        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11842        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11843                true /* requireFullPermission */, true /* checkShell */,
11844                "setPackagesSuspended for user " + userId);
11845
11846        if (ArrayUtils.isEmpty(packageNames)) {
11847            return packageNames;
11848        }
11849
11850        // List of package names for whom the suspended state has changed.
11851        List<String> changedPackages = new ArrayList<>(packageNames.length);
11852        // List of package names for whom the suspended state is not set as requested in this
11853        // method.
11854        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11855        long callingId = Binder.clearCallingIdentity();
11856        try {
11857            for (int i = 0; i < packageNames.length; i++) {
11858                String packageName = packageNames[i];
11859                boolean changed = false;
11860                final int appId;
11861                synchronized (mPackages) {
11862                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11863                    if (pkgSetting == null) {
11864                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11865                                + "\". Skipping suspending/un-suspending.");
11866                        unactionedPackages.add(packageName);
11867                        continue;
11868                    }
11869                    appId = pkgSetting.appId;
11870                    if (pkgSetting.getSuspended(userId) != suspended) {
11871                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11872                            unactionedPackages.add(packageName);
11873                            continue;
11874                        }
11875                        pkgSetting.setSuspended(suspended, userId);
11876                        mSettings.writePackageRestrictionsLPr(userId);
11877                        changed = true;
11878                        changedPackages.add(packageName);
11879                    }
11880                }
11881
11882                if (changed && suspended) {
11883                    killApplication(packageName, UserHandle.getUid(userId, appId),
11884                            "suspending package");
11885                }
11886            }
11887        } finally {
11888            Binder.restoreCallingIdentity(callingId);
11889        }
11890
11891        if (!changedPackages.isEmpty()) {
11892            sendPackagesSuspendedForUser(changedPackages.toArray(
11893                    new String[changedPackages.size()]), userId, suspended);
11894        }
11895
11896        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11897    }
11898
11899    @Override
11900    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11901        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11902                true /* requireFullPermission */, false /* checkShell */,
11903                "isPackageSuspendedForUser for user " + userId);
11904        synchronized (mPackages) {
11905            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11906            if (pkgSetting == null) {
11907                throw new IllegalArgumentException("Unknown target package: " + packageName);
11908            }
11909            return pkgSetting.getSuspended(userId);
11910        }
11911    }
11912
11913    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11914        if (isPackageDeviceAdmin(packageName, userId)) {
11915            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11916                    + "\": has an active device admin");
11917            return false;
11918        }
11919
11920        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11921        if (packageName.equals(activeLauncherPackageName)) {
11922            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11923                    + "\": contains the active launcher");
11924            return false;
11925        }
11926
11927        if (packageName.equals(mRequiredInstallerPackage)) {
11928            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11929                    + "\": required for package installation");
11930            return false;
11931        }
11932
11933        if (packageName.equals(mRequiredVerifierPackage)) {
11934            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11935                    + "\": required for package verification");
11936            return false;
11937        }
11938
11939        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11940            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11941                    + "\": is the default dialer");
11942            return false;
11943        }
11944
11945        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11946            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11947                    + "\": protected package");
11948            return false;
11949        }
11950
11951        return true;
11952    }
11953
11954    private String getActiveLauncherPackageName(int userId) {
11955        Intent intent = new Intent(Intent.ACTION_MAIN);
11956        intent.addCategory(Intent.CATEGORY_HOME);
11957        ResolveInfo resolveInfo = resolveIntent(
11958                intent,
11959                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11960                PackageManager.MATCH_DEFAULT_ONLY,
11961                userId);
11962
11963        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11964    }
11965
11966    private String getDefaultDialerPackageName(int userId) {
11967        synchronized (mPackages) {
11968            return mSettings.getDefaultDialerPackageNameLPw(userId);
11969        }
11970    }
11971
11972    @Override
11973    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11974        mContext.enforceCallingOrSelfPermission(
11975                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11976                "Only package verification agents can verify applications");
11977
11978        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11979        final PackageVerificationResponse response = new PackageVerificationResponse(
11980                verificationCode, Binder.getCallingUid());
11981        msg.arg1 = id;
11982        msg.obj = response;
11983        mHandler.sendMessage(msg);
11984    }
11985
11986    @Override
11987    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11988            long millisecondsToDelay) {
11989        mContext.enforceCallingOrSelfPermission(
11990                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11991                "Only package verification agents can extend verification timeouts");
11992
11993        final PackageVerificationState state = mPendingVerification.get(id);
11994        final PackageVerificationResponse response = new PackageVerificationResponse(
11995                verificationCodeAtTimeout, Binder.getCallingUid());
11996
11997        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11998            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11999        }
12000        if (millisecondsToDelay < 0) {
12001            millisecondsToDelay = 0;
12002        }
12003        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12004                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12005            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12006        }
12007
12008        if ((state != null) && !state.timeoutExtended()) {
12009            state.extendTimeout();
12010
12011            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12012            msg.arg1 = id;
12013            msg.obj = response;
12014            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12015        }
12016    }
12017
12018    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12019            int verificationCode, UserHandle user) {
12020        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12021        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12022        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12023        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12024        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12025
12026        mContext.sendBroadcastAsUser(intent, user,
12027                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12028    }
12029
12030    private ComponentName matchComponentForVerifier(String packageName,
12031            List<ResolveInfo> receivers) {
12032        ActivityInfo targetReceiver = null;
12033
12034        final int NR = receivers.size();
12035        for (int i = 0; i < NR; i++) {
12036            final ResolveInfo info = receivers.get(i);
12037            if (info.activityInfo == null) {
12038                continue;
12039            }
12040
12041            if (packageName.equals(info.activityInfo.packageName)) {
12042                targetReceiver = info.activityInfo;
12043                break;
12044            }
12045        }
12046
12047        if (targetReceiver == null) {
12048            return null;
12049        }
12050
12051        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12052    }
12053
12054    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12055            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12056        if (pkgInfo.verifiers.length == 0) {
12057            return null;
12058        }
12059
12060        final int N = pkgInfo.verifiers.length;
12061        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12062        for (int i = 0; i < N; i++) {
12063            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12064
12065            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12066                    receivers);
12067            if (comp == null) {
12068                continue;
12069            }
12070
12071            final int verifierUid = getUidForVerifier(verifierInfo);
12072            if (verifierUid == -1) {
12073                continue;
12074            }
12075
12076            if (DEBUG_VERIFY) {
12077                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12078                        + " with the correct signature");
12079            }
12080            sufficientVerifiers.add(comp);
12081            verificationState.addSufficientVerifier(verifierUid);
12082        }
12083
12084        return sufficientVerifiers;
12085    }
12086
12087    private int getUidForVerifier(VerifierInfo verifierInfo) {
12088        synchronized (mPackages) {
12089            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12090            if (pkg == null) {
12091                return -1;
12092            } else if (pkg.mSignatures.length != 1) {
12093                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12094                        + " has more than one signature; ignoring");
12095                return -1;
12096            }
12097
12098            /*
12099             * If the public key of the package's signature does not match
12100             * our expected public key, then this is a different package and
12101             * we should skip.
12102             */
12103
12104            final byte[] expectedPublicKey;
12105            try {
12106                final Signature verifierSig = pkg.mSignatures[0];
12107                final PublicKey publicKey = verifierSig.getPublicKey();
12108                expectedPublicKey = publicKey.getEncoded();
12109            } catch (CertificateException e) {
12110                return -1;
12111            }
12112
12113            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12114
12115            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12116                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12117                        + " does not have the expected public key; ignoring");
12118                return -1;
12119            }
12120
12121            return pkg.applicationInfo.uid;
12122        }
12123    }
12124
12125    @Override
12126    public void finishPackageInstall(int token, boolean didLaunch) {
12127        enforceSystemOrRoot("Only the system is allowed to finish installs");
12128
12129        if (DEBUG_INSTALL) {
12130            Slog.v(TAG, "BM finishing package install for " + token);
12131        }
12132        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12133
12134        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12135        mHandler.sendMessage(msg);
12136    }
12137
12138    /**
12139     * Get the verification agent timeout.
12140     *
12141     * @return verification timeout in milliseconds
12142     */
12143    private long getVerificationTimeout() {
12144        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12145                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12146                DEFAULT_VERIFICATION_TIMEOUT);
12147    }
12148
12149    /**
12150     * Get the default verification agent response code.
12151     *
12152     * @return default verification response code
12153     */
12154    private int getDefaultVerificationResponse() {
12155        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12156                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12157                DEFAULT_VERIFICATION_RESPONSE);
12158    }
12159
12160    /**
12161     * Check whether or not package verification has been enabled.
12162     *
12163     * @return true if verification should be performed
12164     */
12165    private boolean isVerificationEnabled(int userId, int installFlags) {
12166        if (!DEFAULT_VERIFY_ENABLE) {
12167            return false;
12168        }
12169        // Ephemeral apps don't get the full verification treatment
12170        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12171            if (DEBUG_EPHEMERAL) {
12172                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12173            }
12174            return false;
12175        }
12176
12177        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12178
12179        // Check if installing from ADB
12180        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12181            // Do not run verification in a test harness environment
12182            if (ActivityManager.isRunningInTestHarness()) {
12183                return false;
12184            }
12185            if (ensureVerifyAppsEnabled) {
12186                return true;
12187            }
12188            // Check if the developer does not want package verification for ADB installs
12189            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12190                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12191                return false;
12192            }
12193        }
12194
12195        if (ensureVerifyAppsEnabled) {
12196            return true;
12197        }
12198
12199        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12200                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12201    }
12202
12203    @Override
12204    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12205            throws RemoteException {
12206        mContext.enforceCallingOrSelfPermission(
12207                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12208                "Only intentfilter verification agents can verify applications");
12209
12210        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12211        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12212                Binder.getCallingUid(), verificationCode, failedDomains);
12213        msg.arg1 = id;
12214        msg.obj = response;
12215        mHandler.sendMessage(msg);
12216    }
12217
12218    @Override
12219    public int getIntentVerificationStatus(String packageName, int userId) {
12220        synchronized (mPackages) {
12221            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12222        }
12223    }
12224
12225    @Override
12226    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12227        mContext.enforceCallingOrSelfPermission(
12228                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12229
12230        boolean result = false;
12231        synchronized (mPackages) {
12232            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12233        }
12234        if (result) {
12235            scheduleWritePackageRestrictionsLocked(userId);
12236        }
12237        return result;
12238    }
12239
12240    @Override
12241    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12242            String packageName) {
12243        synchronized (mPackages) {
12244            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12245        }
12246    }
12247
12248    @Override
12249    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12250        if (TextUtils.isEmpty(packageName)) {
12251            return ParceledListSlice.emptyList();
12252        }
12253        synchronized (mPackages) {
12254            PackageParser.Package pkg = mPackages.get(packageName);
12255            if (pkg == null || pkg.activities == null) {
12256                return ParceledListSlice.emptyList();
12257            }
12258            final int count = pkg.activities.size();
12259            ArrayList<IntentFilter> result = new ArrayList<>();
12260            for (int n=0; n<count; n++) {
12261                PackageParser.Activity activity = pkg.activities.get(n);
12262                if (activity.intents != null && activity.intents.size() > 0) {
12263                    result.addAll(activity.intents);
12264                }
12265            }
12266            return new ParceledListSlice<>(result);
12267        }
12268    }
12269
12270    @Override
12271    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12272        mContext.enforceCallingOrSelfPermission(
12273                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12274
12275        synchronized (mPackages) {
12276            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12277            if (packageName != null) {
12278                result |= updateIntentVerificationStatus(packageName,
12279                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12280                        userId);
12281                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12282                        packageName, userId);
12283            }
12284            return result;
12285        }
12286    }
12287
12288    @Override
12289    public String getDefaultBrowserPackageName(int userId) {
12290        synchronized (mPackages) {
12291            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12292        }
12293    }
12294
12295    /**
12296     * Get the "allow unknown sources" setting.
12297     *
12298     * @return the current "allow unknown sources" setting
12299     */
12300    private int getUnknownSourcesSettings() {
12301        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12302                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12303                -1);
12304    }
12305
12306    @Override
12307    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12308        final int uid = Binder.getCallingUid();
12309        // writer
12310        synchronized (mPackages) {
12311            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12312            if (targetPackageSetting == null) {
12313                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12314            }
12315
12316            PackageSetting installerPackageSetting;
12317            if (installerPackageName != null) {
12318                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12319                if (installerPackageSetting == null) {
12320                    throw new IllegalArgumentException("Unknown installer package: "
12321                            + installerPackageName);
12322                }
12323            } else {
12324                installerPackageSetting = null;
12325            }
12326
12327            Signature[] callerSignature;
12328            Object obj = mSettings.getUserIdLPr(uid);
12329            if (obj != null) {
12330                if (obj instanceof SharedUserSetting) {
12331                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12332                } else if (obj instanceof PackageSetting) {
12333                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12334                } else {
12335                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12336                }
12337            } else {
12338                throw new SecurityException("Unknown calling UID: " + uid);
12339            }
12340
12341            // Verify: can't set installerPackageName to a package that is
12342            // not signed with the same cert as the caller.
12343            if (installerPackageSetting != null) {
12344                if (compareSignatures(callerSignature,
12345                        installerPackageSetting.signatures.mSignatures)
12346                        != PackageManager.SIGNATURE_MATCH) {
12347                    throw new SecurityException(
12348                            "Caller does not have same cert as new installer package "
12349                            + installerPackageName);
12350                }
12351            }
12352
12353            // Verify: if target already has an installer package, it must
12354            // be signed with the same cert as the caller.
12355            if (targetPackageSetting.installerPackageName != null) {
12356                PackageSetting setting = mSettings.mPackages.get(
12357                        targetPackageSetting.installerPackageName);
12358                // If the currently set package isn't valid, then it's always
12359                // okay to change it.
12360                if (setting != null) {
12361                    if (compareSignatures(callerSignature,
12362                            setting.signatures.mSignatures)
12363                            != PackageManager.SIGNATURE_MATCH) {
12364                        throw new SecurityException(
12365                                "Caller does not have same cert as old installer package "
12366                                + targetPackageSetting.installerPackageName);
12367                    }
12368                }
12369            }
12370
12371            // Okay!
12372            targetPackageSetting.installerPackageName = installerPackageName;
12373            if (installerPackageName != null) {
12374                mSettings.mInstallerPackages.add(installerPackageName);
12375            }
12376            scheduleWriteSettingsLocked();
12377        }
12378    }
12379
12380    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12381        // Queue up an async operation since the package installation may take a little while.
12382        mHandler.post(new Runnable() {
12383            public void run() {
12384                mHandler.removeCallbacks(this);
12385                 // Result object to be returned
12386                PackageInstalledInfo res = new PackageInstalledInfo();
12387                res.setReturnCode(currentStatus);
12388                res.uid = -1;
12389                res.pkg = null;
12390                res.removedInfo = null;
12391                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12392                    args.doPreInstall(res.returnCode);
12393                    synchronized (mInstallLock) {
12394                        installPackageTracedLI(args, res);
12395                    }
12396                    args.doPostInstall(res.returnCode, res.uid);
12397                }
12398
12399                // A restore should be performed at this point if (a) the install
12400                // succeeded, (b) the operation is not an update, and (c) the new
12401                // package has not opted out of backup participation.
12402                final boolean update = res.removedInfo != null
12403                        && res.removedInfo.removedPackage != null;
12404                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12405                boolean doRestore = !update
12406                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12407
12408                // Set up the post-install work request bookkeeping.  This will be used
12409                // and cleaned up by the post-install event handling regardless of whether
12410                // there's a restore pass performed.  Token values are >= 1.
12411                int token;
12412                if (mNextInstallToken < 0) mNextInstallToken = 1;
12413                token = mNextInstallToken++;
12414
12415                PostInstallData data = new PostInstallData(args, res);
12416                mRunningInstalls.put(token, data);
12417                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12418
12419                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12420                    // Pass responsibility to the Backup Manager.  It will perform a
12421                    // restore if appropriate, then pass responsibility back to the
12422                    // Package Manager to run the post-install observer callbacks
12423                    // and broadcasts.
12424                    IBackupManager bm = IBackupManager.Stub.asInterface(
12425                            ServiceManager.getService(Context.BACKUP_SERVICE));
12426                    if (bm != null) {
12427                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12428                                + " to BM for possible restore");
12429                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12430                        try {
12431                            // TODO: http://b/22388012
12432                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12433                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12434                            } else {
12435                                doRestore = false;
12436                            }
12437                        } catch (RemoteException e) {
12438                            // can't happen; the backup manager is local
12439                        } catch (Exception e) {
12440                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12441                            doRestore = false;
12442                        }
12443                    } else {
12444                        Slog.e(TAG, "Backup Manager not found!");
12445                        doRestore = false;
12446                    }
12447                }
12448
12449                if (!doRestore) {
12450                    // No restore possible, or the Backup Manager was mysteriously not
12451                    // available -- just fire the post-install work request directly.
12452                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12453
12454                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12455
12456                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12457                    mHandler.sendMessage(msg);
12458                }
12459            }
12460        });
12461    }
12462
12463    /**
12464     * Callback from PackageSettings whenever an app is first transitioned out of the
12465     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12466     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12467     * here whether the app is the target of an ongoing install, and only send the
12468     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12469     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12470     * handling.
12471     */
12472    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12473        // Serialize this with the rest of the install-process message chain.  In the
12474        // restore-at-install case, this Runnable will necessarily run before the
12475        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12476        // are coherent.  In the non-restore case, the app has already completed install
12477        // and been launched through some other means, so it is not in a problematic
12478        // state for observers to see the FIRST_LAUNCH signal.
12479        mHandler.post(new Runnable() {
12480            @Override
12481            public void run() {
12482                for (int i = 0; i < mRunningInstalls.size(); i++) {
12483                    final PostInstallData data = mRunningInstalls.valueAt(i);
12484                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12485                        // right package; but is it for the right user?
12486                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12487                            if (userId == data.res.newUsers[uIndex]) {
12488                                if (DEBUG_BACKUP) {
12489                                    Slog.i(TAG, "Package " + pkgName
12490                                            + " being restored so deferring FIRST_LAUNCH");
12491                                }
12492                                return;
12493                            }
12494                        }
12495                    }
12496                }
12497                // didn't find it, so not being restored
12498                if (DEBUG_BACKUP) {
12499                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12500                }
12501                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12502            }
12503        });
12504    }
12505
12506    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12507        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12508                installerPkg, null, userIds);
12509    }
12510
12511    private abstract class HandlerParams {
12512        private static final int MAX_RETRIES = 4;
12513
12514        /**
12515         * Number of times startCopy() has been attempted and had a non-fatal
12516         * error.
12517         */
12518        private int mRetries = 0;
12519
12520        /** User handle for the user requesting the information or installation. */
12521        private final UserHandle mUser;
12522        String traceMethod;
12523        int traceCookie;
12524
12525        HandlerParams(UserHandle user) {
12526            mUser = user;
12527        }
12528
12529        UserHandle getUser() {
12530            return mUser;
12531        }
12532
12533        HandlerParams setTraceMethod(String traceMethod) {
12534            this.traceMethod = traceMethod;
12535            return this;
12536        }
12537
12538        HandlerParams setTraceCookie(int traceCookie) {
12539            this.traceCookie = traceCookie;
12540            return this;
12541        }
12542
12543        final boolean startCopy() {
12544            boolean res;
12545            try {
12546                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12547
12548                if (++mRetries > MAX_RETRIES) {
12549                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12550                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12551                    handleServiceError();
12552                    return false;
12553                } else {
12554                    handleStartCopy();
12555                    res = true;
12556                }
12557            } catch (RemoteException e) {
12558                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12559                mHandler.sendEmptyMessage(MCS_RECONNECT);
12560                res = false;
12561            }
12562            handleReturnCode();
12563            return res;
12564        }
12565
12566        final void serviceError() {
12567            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12568            handleServiceError();
12569            handleReturnCode();
12570        }
12571
12572        abstract void handleStartCopy() throws RemoteException;
12573        abstract void handleServiceError();
12574        abstract void handleReturnCode();
12575    }
12576
12577    class MeasureParams extends HandlerParams {
12578        private final PackageStats mStats;
12579        private boolean mSuccess;
12580
12581        private final IPackageStatsObserver mObserver;
12582
12583        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12584            super(new UserHandle(stats.userHandle));
12585            mObserver = observer;
12586            mStats = stats;
12587        }
12588
12589        @Override
12590        public String toString() {
12591            return "MeasureParams{"
12592                + Integer.toHexString(System.identityHashCode(this))
12593                + " " + mStats.packageName + "}";
12594        }
12595
12596        @Override
12597        void handleStartCopy() throws RemoteException {
12598            synchronized (mInstallLock) {
12599                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12600            }
12601
12602            if (mSuccess) {
12603                boolean mounted = false;
12604                try {
12605                    final String status = Environment.getExternalStorageState();
12606                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12607                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12608                } catch (Exception e) {
12609                }
12610
12611                if (mounted) {
12612                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12613
12614                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12615                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12616
12617                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12618                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12619
12620                    // Always subtract cache size, since it's a subdirectory
12621                    mStats.externalDataSize -= mStats.externalCacheSize;
12622
12623                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12624                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12625
12626                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12627                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12628                }
12629            }
12630        }
12631
12632        @Override
12633        void handleReturnCode() {
12634            if (mObserver != null) {
12635                try {
12636                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12637                } catch (RemoteException e) {
12638                    Slog.i(TAG, "Observer no longer exists.");
12639                }
12640            }
12641        }
12642
12643        @Override
12644        void handleServiceError() {
12645            Slog.e(TAG, "Could not measure application " + mStats.packageName
12646                            + " external storage");
12647        }
12648    }
12649
12650    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12651            throws RemoteException {
12652        long result = 0;
12653        for (File path : paths) {
12654            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12655        }
12656        return result;
12657    }
12658
12659    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12660        for (File path : paths) {
12661            try {
12662                mcs.clearDirectory(path.getAbsolutePath());
12663            } catch (RemoteException e) {
12664            }
12665        }
12666    }
12667
12668    static class OriginInfo {
12669        /**
12670         * Location where install is coming from, before it has been
12671         * copied/renamed into place. This could be a single monolithic APK
12672         * file, or a cluster directory. This location may be untrusted.
12673         */
12674        final File file;
12675        final String cid;
12676
12677        /**
12678         * Flag indicating that {@link #file} or {@link #cid} has already been
12679         * staged, meaning downstream users don't need to defensively copy the
12680         * contents.
12681         */
12682        final boolean staged;
12683
12684        /**
12685         * Flag indicating that {@link #file} or {@link #cid} is an already
12686         * installed app that is being moved.
12687         */
12688        final boolean existing;
12689
12690        final String resolvedPath;
12691        final File resolvedFile;
12692
12693        static OriginInfo fromNothing() {
12694            return new OriginInfo(null, null, false, false);
12695        }
12696
12697        static OriginInfo fromUntrustedFile(File file) {
12698            return new OriginInfo(file, null, false, false);
12699        }
12700
12701        static OriginInfo fromExistingFile(File file) {
12702            return new OriginInfo(file, null, false, true);
12703        }
12704
12705        static OriginInfo fromStagedFile(File file) {
12706            return new OriginInfo(file, null, true, false);
12707        }
12708
12709        static OriginInfo fromStagedContainer(String cid) {
12710            return new OriginInfo(null, cid, true, false);
12711        }
12712
12713        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12714            this.file = file;
12715            this.cid = cid;
12716            this.staged = staged;
12717            this.existing = existing;
12718
12719            if (cid != null) {
12720                resolvedPath = PackageHelper.getSdDir(cid);
12721                resolvedFile = new File(resolvedPath);
12722            } else if (file != null) {
12723                resolvedPath = file.getAbsolutePath();
12724                resolvedFile = file;
12725            } else {
12726                resolvedPath = null;
12727                resolvedFile = null;
12728            }
12729        }
12730    }
12731
12732    static class MoveInfo {
12733        final int moveId;
12734        final String fromUuid;
12735        final String toUuid;
12736        final String packageName;
12737        final String dataAppName;
12738        final int appId;
12739        final String seinfo;
12740        final int targetSdkVersion;
12741
12742        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12743                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12744            this.moveId = moveId;
12745            this.fromUuid = fromUuid;
12746            this.toUuid = toUuid;
12747            this.packageName = packageName;
12748            this.dataAppName = dataAppName;
12749            this.appId = appId;
12750            this.seinfo = seinfo;
12751            this.targetSdkVersion = targetSdkVersion;
12752        }
12753    }
12754
12755    static class VerificationInfo {
12756        /** A constant used to indicate that a uid value is not present. */
12757        public static final int NO_UID = -1;
12758
12759        /** URI referencing where the package was downloaded from. */
12760        final Uri originatingUri;
12761
12762        /** HTTP referrer URI associated with the originatingURI. */
12763        final Uri referrer;
12764
12765        /** UID of the application that the install request originated from. */
12766        final int originatingUid;
12767
12768        /** UID of application requesting the install */
12769        final int installerUid;
12770
12771        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12772            this.originatingUri = originatingUri;
12773            this.referrer = referrer;
12774            this.originatingUid = originatingUid;
12775            this.installerUid = installerUid;
12776        }
12777    }
12778
12779    class InstallParams extends HandlerParams {
12780        final OriginInfo origin;
12781        final MoveInfo move;
12782        final IPackageInstallObserver2 observer;
12783        int installFlags;
12784        final String installerPackageName;
12785        final String volumeUuid;
12786        private InstallArgs mArgs;
12787        private int mRet;
12788        final String packageAbiOverride;
12789        final String[] grantedRuntimePermissions;
12790        final VerificationInfo verificationInfo;
12791        final Certificate[][] certificates;
12792
12793        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12794                int installFlags, String installerPackageName, String volumeUuid,
12795                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12796                String[] grantedPermissions, Certificate[][] certificates) {
12797            super(user);
12798            this.origin = origin;
12799            this.move = move;
12800            this.observer = observer;
12801            this.installFlags = installFlags;
12802            this.installerPackageName = installerPackageName;
12803            this.volumeUuid = volumeUuid;
12804            this.verificationInfo = verificationInfo;
12805            this.packageAbiOverride = packageAbiOverride;
12806            this.grantedRuntimePermissions = grantedPermissions;
12807            this.certificates = certificates;
12808        }
12809
12810        @Override
12811        public String toString() {
12812            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12813                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12814        }
12815
12816        private int installLocationPolicy(PackageInfoLite pkgLite) {
12817            String packageName = pkgLite.packageName;
12818            int installLocation = pkgLite.installLocation;
12819            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12820            // reader
12821            synchronized (mPackages) {
12822                // Currently installed package which the new package is attempting to replace or
12823                // null if no such package is installed.
12824                PackageParser.Package installedPkg = mPackages.get(packageName);
12825                // Package which currently owns the data which the new package will own if installed.
12826                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12827                // will be null whereas dataOwnerPkg will contain information about the package
12828                // which was uninstalled while keeping its data.
12829                PackageParser.Package dataOwnerPkg = installedPkg;
12830                if (dataOwnerPkg  == null) {
12831                    PackageSetting ps = mSettings.mPackages.get(packageName);
12832                    if (ps != null) {
12833                        dataOwnerPkg = ps.pkg;
12834                    }
12835                }
12836
12837                if (dataOwnerPkg != null) {
12838                    // If installed, the package will get access to data left on the device by its
12839                    // predecessor. As a security measure, this is permited only if this is not a
12840                    // version downgrade or if the predecessor package is marked as debuggable and
12841                    // a downgrade is explicitly requested.
12842                    //
12843                    // On debuggable platform builds, downgrades are permitted even for
12844                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12845                    // not offer security guarantees and thus it's OK to disable some security
12846                    // mechanisms to make debugging/testing easier on those builds. However, even on
12847                    // debuggable builds downgrades of packages are permitted only if requested via
12848                    // installFlags. This is because we aim to keep the behavior of debuggable
12849                    // platform builds as close as possible to the behavior of non-debuggable
12850                    // platform builds.
12851                    final boolean downgradeRequested =
12852                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12853                    final boolean packageDebuggable =
12854                                (dataOwnerPkg.applicationInfo.flags
12855                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12856                    final boolean downgradePermitted =
12857                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12858                    if (!downgradePermitted) {
12859                        try {
12860                            checkDowngrade(dataOwnerPkg, pkgLite);
12861                        } catch (PackageManagerException e) {
12862                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12863                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12864                        }
12865                    }
12866                }
12867
12868                if (installedPkg != null) {
12869                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12870                        // Check for updated system application.
12871                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12872                            if (onSd) {
12873                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12874                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12875                            }
12876                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12877                        } else {
12878                            if (onSd) {
12879                                // Install flag overrides everything.
12880                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12881                            }
12882                            // If current upgrade specifies particular preference
12883                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12884                                // Application explicitly specified internal.
12885                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12886                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12887                                // App explictly prefers external. Let policy decide
12888                            } else {
12889                                // Prefer previous location
12890                                if (isExternal(installedPkg)) {
12891                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12892                                }
12893                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12894                            }
12895                        }
12896                    } else {
12897                        // Invalid install. Return error code
12898                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12899                    }
12900                }
12901            }
12902            // All the special cases have been taken care of.
12903            // Return result based on recommended install location.
12904            if (onSd) {
12905                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12906            }
12907            return pkgLite.recommendedInstallLocation;
12908        }
12909
12910        /*
12911         * Invoke remote method to get package information and install
12912         * location values. Override install location based on default
12913         * policy if needed and then create install arguments based
12914         * on the install location.
12915         */
12916        public void handleStartCopy() throws RemoteException {
12917            int ret = PackageManager.INSTALL_SUCCEEDED;
12918
12919            // If we're already staged, we've firmly committed to an install location
12920            if (origin.staged) {
12921                if (origin.file != null) {
12922                    installFlags |= PackageManager.INSTALL_INTERNAL;
12923                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12924                } else if (origin.cid != null) {
12925                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12926                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12927                } else {
12928                    throw new IllegalStateException("Invalid stage location");
12929                }
12930            }
12931
12932            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12933            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12934            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12935            PackageInfoLite pkgLite = null;
12936
12937            if (onInt && onSd) {
12938                // Check if both bits are set.
12939                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12940                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12941            } else if (onSd && ephemeral) {
12942                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12943                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12944            } else {
12945                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12946                        packageAbiOverride);
12947
12948                if (DEBUG_EPHEMERAL && ephemeral) {
12949                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12950                }
12951
12952                /*
12953                 * If we have too little free space, try to free cache
12954                 * before giving up.
12955                 */
12956                if (!origin.staged && pkgLite.recommendedInstallLocation
12957                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12958                    // TODO: focus freeing disk space on the target device
12959                    final StorageManager storage = StorageManager.from(mContext);
12960                    final long lowThreshold = storage.getStorageLowBytes(
12961                            Environment.getDataDirectory());
12962
12963                    final long sizeBytes = mContainerService.calculateInstalledSize(
12964                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12965
12966                    try {
12967                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12968                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12969                                installFlags, packageAbiOverride);
12970                    } catch (InstallerException e) {
12971                        Slog.w(TAG, "Failed to free cache", e);
12972                    }
12973
12974                    /*
12975                     * The cache free must have deleted the file we
12976                     * downloaded to install.
12977                     *
12978                     * TODO: fix the "freeCache" call to not delete
12979                     *       the file we care about.
12980                     */
12981                    if (pkgLite.recommendedInstallLocation
12982                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12983                        pkgLite.recommendedInstallLocation
12984                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12985                    }
12986                }
12987            }
12988
12989            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12990                int loc = pkgLite.recommendedInstallLocation;
12991                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12992                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12993                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12994                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12995                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12996                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12997                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12998                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12999                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13000                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13001                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13002                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13003                } else {
13004                    // Override with defaults if needed.
13005                    loc = installLocationPolicy(pkgLite);
13006                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13007                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13008                    } else if (!onSd && !onInt) {
13009                        // Override install location with flags
13010                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13011                            // Set the flag to install on external media.
13012                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13013                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13014                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13015                            if (DEBUG_EPHEMERAL) {
13016                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13017                            }
13018                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13019                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13020                                    |PackageManager.INSTALL_INTERNAL);
13021                        } else {
13022                            // Make sure the flag for installing on external
13023                            // media is unset
13024                            installFlags |= PackageManager.INSTALL_INTERNAL;
13025                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13026                        }
13027                    }
13028                }
13029            }
13030
13031            final InstallArgs args = createInstallArgs(this);
13032            mArgs = args;
13033
13034            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13035                // TODO: http://b/22976637
13036                // Apps installed for "all" users use the device owner to verify the app
13037                UserHandle verifierUser = getUser();
13038                if (verifierUser == UserHandle.ALL) {
13039                    verifierUser = UserHandle.SYSTEM;
13040                }
13041
13042                /*
13043                 * Determine if we have any installed package verifiers. If we
13044                 * do, then we'll defer to them to verify the packages.
13045                 */
13046                final int requiredUid = mRequiredVerifierPackage == null ? -1
13047                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13048                                verifierUser.getIdentifier());
13049                if (!origin.existing && requiredUid != -1
13050                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13051                    final Intent verification = new Intent(
13052                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13053                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13054                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13055                            PACKAGE_MIME_TYPE);
13056                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13057
13058                    // Query all live verifiers based on current user state
13059                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13060                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13061
13062                    if (DEBUG_VERIFY) {
13063                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13064                                + verification.toString() + " with " + pkgLite.verifiers.length
13065                                + " optional verifiers");
13066                    }
13067
13068                    final int verificationId = mPendingVerificationToken++;
13069
13070                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13071
13072                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13073                            installerPackageName);
13074
13075                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13076                            installFlags);
13077
13078                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13079                            pkgLite.packageName);
13080
13081                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13082                            pkgLite.versionCode);
13083
13084                    if (verificationInfo != null) {
13085                        if (verificationInfo.originatingUri != null) {
13086                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13087                                    verificationInfo.originatingUri);
13088                        }
13089                        if (verificationInfo.referrer != null) {
13090                            verification.putExtra(Intent.EXTRA_REFERRER,
13091                                    verificationInfo.referrer);
13092                        }
13093                        if (verificationInfo.originatingUid >= 0) {
13094                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13095                                    verificationInfo.originatingUid);
13096                        }
13097                        if (verificationInfo.installerUid >= 0) {
13098                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13099                                    verificationInfo.installerUid);
13100                        }
13101                    }
13102
13103                    final PackageVerificationState verificationState = new PackageVerificationState(
13104                            requiredUid, args);
13105
13106                    mPendingVerification.append(verificationId, verificationState);
13107
13108                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13109                            receivers, verificationState);
13110
13111                    /*
13112                     * If any sufficient verifiers were listed in the package
13113                     * manifest, attempt to ask them.
13114                     */
13115                    if (sufficientVerifiers != null) {
13116                        final int N = sufficientVerifiers.size();
13117                        if (N == 0) {
13118                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13119                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13120                        } else {
13121                            for (int i = 0; i < N; i++) {
13122                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13123
13124                                final Intent sufficientIntent = new Intent(verification);
13125                                sufficientIntent.setComponent(verifierComponent);
13126                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13127                            }
13128                        }
13129                    }
13130
13131                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13132                            mRequiredVerifierPackage, receivers);
13133                    if (ret == PackageManager.INSTALL_SUCCEEDED
13134                            && mRequiredVerifierPackage != null) {
13135                        Trace.asyncTraceBegin(
13136                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13137                        /*
13138                         * Send the intent to the required verification agent,
13139                         * but only start the verification timeout after the
13140                         * target BroadcastReceivers have run.
13141                         */
13142                        verification.setComponent(requiredVerifierComponent);
13143                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13144                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13145                                new BroadcastReceiver() {
13146                                    @Override
13147                                    public void onReceive(Context context, Intent intent) {
13148                                        final Message msg = mHandler
13149                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13150                                        msg.arg1 = verificationId;
13151                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13152                                    }
13153                                }, null, 0, null, null);
13154
13155                        /*
13156                         * We don't want the copy to proceed until verification
13157                         * succeeds, so null out this field.
13158                         */
13159                        mArgs = null;
13160                    }
13161                } else {
13162                    /*
13163                     * No package verification is enabled, so immediately start
13164                     * the remote call to initiate copy using temporary file.
13165                     */
13166                    ret = args.copyApk(mContainerService, true);
13167                }
13168            }
13169
13170            mRet = ret;
13171        }
13172
13173        @Override
13174        void handleReturnCode() {
13175            // If mArgs is null, then MCS couldn't be reached. When it
13176            // reconnects, it will try again to install. At that point, this
13177            // will succeed.
13178            if (mArgs != null) {
13179                processPendingInstall(mArgs, mRet);
13180            }
13181        }
13182
13183        @Override
13184        void handleServiceError() {
13185            mArgs = createInstallArgs(this);
13186            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13187        }
13188
13189        public boolean isForwardLocked() {
13190            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13191        }
13192    }
13193
13194    /**
13195     * Used during creation of InstallArgs
13196     *
13197     * @param installFlags package installation flags
13198     * @return true if should be installed on external storage
13199     */
13200    private static boolean installOnExternalAsec(int installFlags) {
13201        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13202            return false;
13203        }
13204        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13205            return true;
13206        }
13207        return false;
13208    }
13209
13210    /**
13211     * Used during creation of InstallArgs
13212     *
13213     * @param installFlags package installation flags
13214     * @return true if should be installed as forward locked
13215     */
13216    private static boolean installForwardLocked(int installFlags) {
13217        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13218    }
13219
13220    private InstallArgs createInstallArgs(InstallParams params) {
13221        if (params.move != null) {
13222            return new MoveInstallArgs(params);
13223        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13224            return new AsecInstallArgs(params);
13225        } else {
13226            return new FileInstallArgs(params);
13227        }
13228    }
13229
13230    /**
13231     * Create args that describe an existing installed package. Typically used
13232     * when cleaning up old installs, or used as a move source.
13233     */
13234    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13235            String resourcePath, String[] instructionSets) {
13236        final boolean isInAsec;
13237        if (installOnExternalAsec(installFlags)) {
13238            /* Apps on SD card are always in ASEC containers. */
13239            isInAsec = true;
13240        } else if (installForwardLocked(installFlags)
13241                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13242            /*
13243             * Forward-locked apps are only in ASEC containers if they're the
13244             * new style
13245             */
13246            isInAsec = true;
13247        } else {
13248            isInAsec = false;
13249        }
13250
13251        if (isInAsec) {
13252            return new AsecInstallArgs(codePath, instructionSets,
13253                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13254        } else {
13255            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13256        }
13257    }
13258
13259    static abstract class InstallArgs {
13260        /** @see InstallParams#origin */
13261        final OriginInfo origin;
13262        /** @see InstallParams#move */
13263        final MoveInfo move;
13264
13265        final IPackageInstallObserver2 observer;
13266        // Always refers to PackageManager flags only
13267        final int installFlags;
13268        final String installerPackageName;
13269        final String volumeUuid;
13270        final UserHandle user;
13271        final String abiOverride;
13272        final String[] installGrantPermissions;
13273        /** If non-null, drop an async trace when the install completes */
13274        final String traceMethod;
13275        final int traceCookie;
13276        final Certificate[][] certificates;
13277
13278        // The list of instruction sets supported by this app. This is currently
13279        // only used during the rmdex() phase to clean up resources. We can get rid of this
13280        // if we move dex files under the common app path.
13281        /* nullable */ String[] instructionSets;
13282
13283        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13284                int installFlags, String installerPackageName, String volumeUuid,
13285                UserHandle user, String[] instructionSets,
13286                String abiOverride, String[] installGrantPermissions,
13287                String traceMethod, int traceCookie, Certificate[][] certificates) {
13288            this.origin = origin;
13289            this.move = move;
13290            this.installFlags = installFlags;
13291            this.observer = observer;
13292            this.installerPackageName = installerPackageName;
13293            this.volumeUuid = volumeUuid;
13294            this.user = user;
13295            this.instructionSets = instructionSets;
13296            this.abiOverride = abiOverride;
13297            this.installGrantPermissions = installGrantPermissions;
13298            this.traceMethod = traceMethod;
13299            this.traceCookie = traceCookie;
13300            this.certificates = certificates;
13301        }
13302
13303        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13304        abstract int doPreInstall(int status);
13305
13306        /**
13307         * Rename package into final resting place. All paths on the given
13308         * scanned package should be updated to reflect the rename.
13309         */
13310        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13311        abstract int doPostInstall(int status, int uid);
13312
13313        /** @see PackageSettingBase#codePathString */
13314        abstract String getCodePath();
13315        /** @see PackageSettingBase#resourcePathString */
13316        abstract String getResourcePath();
13317
13318        // Need installer lock especially for dex file removal.
13319        abstract void cleanUpResourcesLI();
13320        abstract boolean doPostDeleteLI(boolean delete);
13321
13322        /**
13323         * Called before the source arguments are copied. This is used mostly
13324         * for MoveParams when it needs to read the source file to put it in the
13325         * destination.
13326         */
13327        int doPreCopy() {
13328            return PackageManager.INSTALL_SUCCEEDED;
13329        }
13330
13331        /**
13332         * Called after the source arguments are copied. This is used mostly for
13333         * MoveParams when it needs to read the source file to put it in the
13334         * destination.
13335         */
13336        int doPostCopy(int uid) {
13337            return PackageManager.INSTALL_SUCCEEDED;
13338        }
13339
13340        protected boolean isFwdLocked() {
13341            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13342        }
13343
13344        protected boolean isExternalAsec() {
13345            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13346        }
13347
13348        protected boolean isEphemeral() {
13349            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13350        }
13351
13352        UserHandle getUser() {
13353            return user;
13354        }
13355    }
13356
13357    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13358        if (!allCodePaths.isEmpty()) {
13359            if (instructionSets == null) {
13360                throw new IllegalStateException("instructionSet == null");
13361            }
13362            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13363            for (String codePath : allCodePaths) {
13364                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13365                    try {
13366                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13367                    } catch (InstallerException ignored) {
13368                    }
13369                }
13370            }
13371        }
13372    }
13373
13374    /**
13375     * Logic to handle installation of non-ASEC applications, including copying
13376     * and renaming logic.
13377     */
13378    class FileInstallArgs extends InstallArgs {
13379        private File codeFile;
13380        private File resourceFile;
13381
13382        // Example topology:
13383        // /data/app/com.example/base.apk
13384        // /data/app/com.example/split_foo.apk
13385        // /data/app/com.example/lib/arm/libfoo.so
13386        // /data/app/com.example/lib/arm64/libfoo.so
13387        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13388
13389        /** New install */
13390        FileInstallArgs(InstallParams params) {
13391            super(params.origin, params.move, params.observer, params.installFlags,
13392                    params.installerPackageName, params.volumeUuid,
13393                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13394                    params.grantedRuntimePermissions,
13395                    params.traceMethod, params.traceCookie, params.certificates);
13396            if (isFwdLocked()) {
13397                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13398            }
13399        }
13400
13401        /** Existing install */
13402        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13403            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13404                    null, null, null, 0, null /*certificates*/);
13405            this.codeFile = (codePath != null) ? new File(codePath) : null;
13406            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13407        }
13408
13409        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13410            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13411            try {
13412                return doCopyApk(imcs, temp);
13413            } finally {
13414                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13415            }
13416        }
13417
13418        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13419            if (origin.staged) {
13420                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13421                codeFile = origin.file;
13422                resourceFile = origin.file;
13423                return PackageManager.INSTALL_SUCCEEDED;
13424            }
13425
13426            try {
13427                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13428                final File tempDir =
13429                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13430                codeFile = tempDir;
13431                resourceFile = tempDir;
13432            } catch (IOException e) {
13433                Slog.w(TAG, "Failed to create copy file: " + e);
13434                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13435            }
13436
13437            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13438                @Override
13439                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13440                    if (!FileUtils.isValidExtFilename(name)) {
13441                        throw new IllegalArgumentException("Invalid filename: " + name);
13442                    }
13443                    try {
13444                        final File file = new File(codeFile, name);
13445                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13446                                O_RDWR | O_CREAT, 0644);
13447                        Os.chmod(file.getAbsolutePath(), 0644);
13448                        return new ParcelFileDescriptor(fd);
13449                    } catch (ErrnoException e) {
13450                        throw new RemoteException("Failed to open: " + e.getMessage());
13451                    }
13452                }
13453            };
13454
13455            int ret = PackageManager.INSTALL_SUCCEEDED;
13456            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13457            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13458                Slog.e(TAG, "Failed to copy package");
13459                return ret;
13460            }
13461
13462            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13463            NativeLibraryHelper.Handle handle = null;
13464            try {
13465                handle = NativeLibraryHelper.Handle.create(codeFile);
13466                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13467                        abiOverride);
13468            } catch (IOException e) {
13469                Slog.e(TAG, "Copying native libraries failed", e);
13470                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13471            } finally {
13472                IoUtils.closeQuietly(handle);
13473            }
13474
13475            return ret;
13476        }
13477
13478        int doPreInstall(int status) {
13479            if (status != PackageManager.INSTALL_SUCCEEDED) {
13480                cleanUp();
13481            }
13482            return status;
13483        }
13484
13485        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13486            if (status != PackageManager.INSTALL_SUCCEEDED) {
13487                cleanUp();
13488                return false;
13489            }
13490
13491            final File targetDir = codeFile.getParentFile();
13492            final File beforeCodeFile = codeFile;
13493            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13494
13495            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13496            try {
13497                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13498            } catch (ErrnoException e) {
13499                Slog.w(TAG, "Failed to rename", e);
13500                return false;
13501            }
13502
13503            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13504                Slog.w(TAG, "Failed to restorecon");
13505                return false;
13506            }
13507
13508            // Reflect the rename internally
13509            codeFile = afterCodeFile;
13510            resourceFile = afterCodeFile;
13511
13512            // Reflect the rename in scanned details
13513            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13514            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13515                    afterCodeFile, pkg.baseCodePath));
13516            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13517                    afterCodeFile, pkg.splitCodePaths));
13518
13519            // Reflect the rename in app info
13520            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13521            pkg.setApplicationInfoCodePath(pkg.codePath);
13522            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13523            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13524            pkg.setApplicationInfoResourcePath(pkg.codePath);
13525            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13526            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13527
13528            return true;
13529        }
13530
13531        int doPostInstall(int status, int uid) {
13532            if (status != PackageManager.INSTALL_SUCCEEDED) {
13533                cleanUp();
13534            }
13535            return status;
13536        }
13537
13538        @Override
13539        String getCodePath() {
13540            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13541        }
13542
13543        @Override
13544        String getResourcePath() {
13545            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13546        }
13547
13548        private boolean cleanUp() {
13549            if (codeFile == null || !codeFile.exists()) {
13550                return false;
13551            }
13552
13553            removeCodePathLI(codeFile);
13554
13555            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13556                resourceFile.delete();
13557            }
13558
13559            return true;
13560        }
13561
13562        void cleanUpResourcesLI() {
13563            // Try enumerating all code paths before deleting
13564            List<String> allCodePaths = Collections.EMPTY_LIST;
13565            if (codeFile != null && codeFile.exists()) {
13566                try {
13567                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13568                    allCodePaths = pkg.getAllCodePaths();
13569                } catch (PackageParserException e) {
13570                    // Ignored; we tried our best
13571                }
13572            }
13573
13574            cleanUp();
13575            removeDexFiles(allCodePaths, instructionSets);
13576        }
13577
13578        boolean doPostDeleteLI(boolean delete) {
13579            // XXX err, shouldn't we respect the delete flag?
13580            cleanUpResourcesLI();
13581            return true;
13582        }
13583    }
13584
13585    private boolean isAsecExternal(String cid) {
13586        final String asecPath = PackageHelper.getSdFilesystem(cid);
13587        return !asecPath.startsWith(mAsecInternalPath);
13588    }
13589
13590    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13591            PackageManagerException {
13592        if (copyRet < 0) {
13593            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13594                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13595                throw new PackageManagerException(copyRet, message);
13596            }
13597        }
13598    }
13599
13600    /**
13601     * Extract the MountService "container ID" from the full code path of an
13602     * .apk.
13603     */
13604    static String cidFromCodePath(String fullCodePath) {
13605        int eidx = fullCodePath.lastIndexOf("/");
13606        String subStr1 = fullCodePath.substring(0, eidx);
13607        int sidx = subStr1.lastIndexOf("/");
13608        return subStr1.substring(sidx+1, eidx);
13609    }
13610
13611    /**
13612     * Logic to handle installation of ASEC applications, including copying and
13613     * renaming logic.
13614     */
13615    class AsecInstallArgs extends InstallArgs {
13616        static final String RES_FILE_NAME = "pkg.apk";
13617        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13618
13619        String cid;
13620        String packagePath;
13621        String resourcePath;
13622
13623        /** New install */
13624        AsecInstallArgs(InstallParams params) {
13625            super(params.origin, params.move, params.observer, params.installFlags,
13626                    params.installerPackageName, params.volumeUuid,
13627                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13628                    params.grantedRuntimePermissions,
13629                    params.traceMethod, params.traceCookie, params.certificates);
13630        }
13631
13632        /** Existing install */
13633        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13634                        boolean isExternal, boolean isForwardLocked) {
13635            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13636              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13637                    instructionSets, null, null, null, 0, null /*certificates*/);
13638            // Hackily pretend we're still looking at a full code path
13639            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13640                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13641            }
13642
13643            // Extract cid from fullCodePath
13644            int eidx = fullCodePath.lastIndexOf("/");
13645            String subStr1 = fullCodePath.substring(0, eidx);
13646            int sidx = subStr1.lastIndexOf("/");
13647            cid = subStr1.substring(sidx+1, eidx);
13648            setMountPath(subStr1);
13649        }
13650
13651        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13652            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13653              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13654                    instructionSets, null, null, null, 0, null /*certificates*/);
13655            this.cid = cid;
13656            setMountPath(PackageHelper.getSdDir(cid));
13657        }
13658
13659        void createCopyFile() {
13660            cid = mInstallerService.allocateExternalStageCidLegacy();
13661        }
13662
13663        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13664            if (origin.staged && origin.cid != null) {
13665                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13666                cid = origin.cid;
13667                setMountPath(PackageHelper.getSdDir(cid));
13668                return PackageManager.INSTALL_SUCCEEDED;
13669            }
13670
13671            if (temp) {
13672                createCopyFile();
13673            } else {
13674                /*
13675                 * Pre-emptively destroy the container since it's destroyed if
13676                 * copying fails due to it existing anyway.
13677                 */
13678                PackageHelper.destroySdDir(cid);
13679            }
13680
13681            final String newMountPath = imcs.copyPackageToContainer(
13682                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13683                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13684
13685            if (newMountPath != null) {
13686                setMountPath(newMountPath);
13687                return PackageManager.INSTALL_SUCCEEDED;
13688            } else {
13689                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13690            }
13691        }
13692
13693        @Override
13694        String getCodePath() {
13695            return packagePath;
13696        }
13697
13698        @Override
13699        String getResourcePath() {
13700            return resourcePath;
13701        }
13702
13703        int doPreInstall(int status) {
13704            if (status != PackageManager.INSTALL_SUCCEEDED) {
13705                // Destroy container
13706                PackageHelper.destroySdDir(cid);
13707            } else {
13708                boolean mounted = PackageHelper.isContainerMounted(cid);
13709                if (!mounted) {
13710                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13711                            Process.SYSTEM_UID);
13712                    if (newMountPath != null) {
13713                        setMountPath(newMountPath);
13714                    } else {
13715                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13716                    }
13717                }
13718            }
13719            return status;
13720        }
13721
13722        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13723            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13724            String newMountPath = null;
13725            if (PackageHelper.isContainerMounted(cid)) {
13726                // Unmount the container
13727                if (!PackageHelper.unMountSdDir(cid)) {
13728                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13729                    return false;
13730                }
13731            }
13732            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13733                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13734                        " which might be stale. Will try to clean up.");
13735                // Clean up the stale container and proceed to recreate.
13736                if (!PackageHelper.destroySdDir(newCacheId)) {
13737                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13738                    return false;
13739                }
13740                // Successfully cleaned up stale container. Try to rename again.
13741                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13742                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13743                            + " inspite of cleaning it up.");
13744                    return false;
13745                }
13746            }
13747            if (!PackageHelper.isContainerMounted(newCacheId)) {
13748                Slog.w(TAG, "Mounting container " + newCacheId);
13749                newMountPath = PackageHelper.mountSdDir(newCacheId,
13750                        getEncryptKey(), Process.SYSTEM_UID);
13751            } else {
13752                newMountPath = PackageHelper.getSdDir(newCacheId);
13753            }
13754            if (newMountPath == null) {
13755                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13756                return false;
13757            }
13758            Log.i(TAG, "Succesfully renamed " + cid +
13759                    " to " + newCacheId +
13760                    " at new path: " + newMountPath);
13761            cid = newCacheId;
13762
13763            final File beforeCodeFile = new File(packagePath);
13764            setMountPath(newMountPath);
13765            final File afterCodeFile = new File(packagePath);
13766
13767            // Reflect the rename in scanned details
13768            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13769            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13770                    afterCodeFile, pkg.baseCodePath));
13771            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13772                    afterCodeFile, pkg.splitCodePaths));
13773
13774            // Reflect the rename in app info
13775            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13776            pkg.setApplicationInfoCodePath(pkg.codePath);
13777            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13778            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13779            pkg.setApplicationInfoResourcePath(pkg.codePath);
13780            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13781            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13782
13783            return true;
13784        }
13785
13786        private void setMountPath(String mountPath) {
13787            final File mountFile = new File(mountPath);
13788
13789            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13790            if (monolithicFile.exists()) {
13791                packagePath = monolithicFile.getAbsolutePath();
13792                if (isFwdLocked()) {
13793                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13794                } else {
13795                    resourcePath = packagePath;
13796                }
13797            } else {
13798                packagePath = mountFile.getAbsolutePath();
13799                resourcePath = packagePath;
13800            }
13801        }
13802
13803        int doPostInstall(int status, int uid) {
13804            if (status != PackageManager.INSTALL_SUCCEEDED) {
13805                cleanUp();
13806            } else {
13807                final int groupOwner;
13808                final String protectedFile;
13809                if (isFwdLocked()) {
13810                    groupOwner = UserHandle.getSharedAppGid(uid);
13811                    protectedFile = RES_FILE_NAME;
13812                } else {
13813                    groupOwner = -1;
13814                    protectedFile = null;
13815                }
13816
13817                if (uid < Process.FIRST_APPLICATION_UID
13818                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13819                    Slog.e(TAG, "Failed to finalize " + cid);
13820                    PackageHelper.destroySdDir(cid);
13821                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13822                }
13823
13824                boolean mounted = PackageHelper.isContainerMounted(cid);
13825                if (!mounted) {
13826                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13827                }
13828            }
13829            return status;
13830        }
13831
13832        private void cleanUp() {
13833            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13834
13835            // Destroy secure container
13836            PackageHelper.destroySdDir(cid);
13837        }
13838
13839        private List<String> getAllCodePaths() {
13840            final File codeFile = new File(getCodePath());
13841            if (codeFile != null && codeFile.exists()) {
13842                try {
13843                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13844                    return pkg.getAllCodePaths();
13845                } catch (PackageParserException e) {
13846                    // Ignored; we tried our best
13847                }
13848            }
13849            return Collections.EMPTY_LIST;
13850        }
13851
13852        void cleanUpResourcesLI() {
13853            // Enumerate all code paths before deleting
13854            cleanUpResourcesLI(getAllCodePaths());
13855        }
13856
13857        private void cleanUpResourcesLI(List<String> allCodePaths) {
13858            cleanUp();
13859            removeDexFiles(allCodePaths, instructionSets);
13860        }
13861
13862        String getPackageName() {
13863            return getAsecPackageName(cid);
13864        }
13865
13866        boolean doPostDeleteLI(boolean delete) {
13867            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13868            final List<String> allCodePaths = getAllCodePaths();
13869            boolean mounted = PackageHelper.isContainerMounted(cid);
13870            if (mounted) {
13871                // Unmount first
13872                if (PackageHelper.unMountSdDir(cid)) {
13873                    mounted = false;
13874                }
13875            }
13876            if (!mounted && delete) {
13877                cleanUpResourcesLI(allCodePaths);
13878            }
13879            return !mounted;
13880        }
13881
13882        @Override
13883        int doPreCopy() {
13884            if (isFwdLocked()) {
13885                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13886                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13887                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13888                }
13889            }
13890
13891            return PackageManager.INSTALL_SUCCEEDED;
13892        }
13893
13894        @Override
13895        int doPostCopy(int uid) {
13896            if (isFwdLocked()) {
13897                if (uid < Process.FIRST_APPLICATION_UID
13898                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13899                                RES_FILE_NAME)) {
13900                    Slog.e(TAG, "Failed to finalize " + cid);
13901                    PackageHelper.destroySdDir(cid);
13902                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13903                }
13904            }
13905
13906            return PackageManager.INSTALL_SUCCEEDED;
13907        }
13908    }
13909
13910    /**
13911     * Logic to handle movement of existing installed applications.
13912     */
13913    class MoveInstallArgs extends InstallArgs {
13914        private File codeFile;
13915        private File resourceFile;
13916
13917        /** New install */
13918        MoveInstallArgs(InstallParams params) {
13919            super(params.origin, params.move, params.observer, params.installFlags,
13920                    params.installerPackageName, params.volumeUuid,
13921                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13922                    params.grantedRuntimePermissions,
13923                    params.traceMethod, params.traceCookie, params.certificates);
13924        }
13925
13926        int copyApk(IMediaContainerService imcs, boolean temp) {
13927            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13928                    + move.fromUuid + " to " + move.toUuid);
13929            synchronized (mInstaller) {
13930                try {
13931                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13932                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13933                } catch (InstallerException e) {
13934                    Slog.w(TAG, "Failed to move app", e);
13935                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13936                }
13937            }
13938
13939            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13940            resourceFile = codeFile;
13941            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13942
13943            return PackageManager.INSTALL_SUCCEEDED;
13944        }
13945
13946        int doPreInstall(int status) {
13947            if (status != PackageManager.INSTALL_SUCCEEDED) {
13948                cleanUp(move.toUuid);
13949            }
13950            return status;
13951        }
13952
13953        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13954            if (status != PackageManager.INSTALL_SUCCEEDED) {
13955                cleanUp(move.toUuid);
13956                return false;
13957            }
13958
13959            // Reflect the move in app info
13960            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13961            pkg.setApplicationInfoCodePath(pkg.codePath);
13962            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13963            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13964            pkg.setApplicationInfoResourcePath(pkg.codePath);
13965            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13966            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13967
13968            return true;
13969        }
13970
13971        int doPostInstall(int status, int uid) {
13972            if (status == PackageManager.INSTALL_SUCCEEDED) {
13973                cleanUp(move.fromUuid);
13974            } else {
13975                cleanUp(move.toUuid);
13976            }
13977            return status;
13978        }
13979
13980        @Override
13981        String getCodePath() {
13982            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13983        }
13984
13985        @Override
13986        String getResourcePath() {
13987            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13988        }
13989
13990        private boolean cleanUp(String volumeUuid) {
13991            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13992                    move.dataAppName);
13993            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13994            final int[] userIds = sUserManager.getUserIds();
13995            synchronized (mInstallLock) {
13996                // Clean up both app data and code
13997                // All package moves are frozen until finished
13998                for (int userId : userIds) {
13999                    try {
14000                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14001                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14002                    } catch (InstallerException e) {
14003                        Slog.w(TAG, String.valueOf(e));
14004                    }
14005                }
14006                removeCodePathLI(codeFile);
14007            }
14008            return true;
14009        }
14010
14011        void cleanUpResourcesLI() {
14012            throw new UnsupportedOperationException();
14013        }
14014
14015        boolean doPostDeleteLI(boolean delete) {
14016            throw new UnsupportedOperationException();
14017        }
14018    }
14019
14020    static String getAsecPackageName(String packageCid) {
14021        int idx = packageCid.lastIndexOf("-");
14022        if (idx == -1) {
14023            return packageCid;
14024        }
14025        return packageCid.substring(0, idx);
14026    }
14027
14028    // Utility method used to create code paths based on package name and available index.
14029    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14030        String idxStr = "";
14031        int idx = 1;
14032        // Fall back to default value of idx=1 if prefix is not
14033        // part of oldCodePath
14034        if (oldCodePath != null) {
14035            String subStr = oldCodePath;
14036            // Drop the suffix right away
14037            if (suffix != null && subStr.endsWith(suffix)) {
14038                subStr = subStr.substring(0, subStr.length() - suffix.length());
14039            }
14040            // If oldCodePath already contains prefix find out the
14041            // ending index to either increment or decrement.
14042            int sidx = subStr.lastIndexOf(prefix);
14043            if (sidx != -1) {
14044                subStr = subStr.substring(sidx + prefix.length());
14045                if (subStr != null) {
14046                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14047                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14048                    }
14049                    try {
14050                        idx = Integer.parseInt(subStr);
14051                        if (idx <= 1) {
14052                            idx++;
14053                        } else {
14054                            idx--;
14055                        }
14056                    } catch(NumberFormatException e) {
14057                    }
14058                }
14059            }
14060        }
14061        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14062        return prefix + idxStr;
14063    }
14064
14065    private File getNextCodePath(File targetDir, String packageName) {
14066        int suffix = 1;
14067        File result;
14068        do {
14069            result = new File(targetDir, packageName + "-" + suffix);
14070            suffix++;
14071        } while (result.exists());
14072        return result;
14073    }
14074
14075    // Utility method that returns the relative package path with respect
14076    // to the installation directory. Like say for /data/data/com.test-1.apk
14077    // string com.test-1 is returned.
14078    static String deriveCodePathName(String codePath) {
14079        if (codePath == null) {
14080            return null;
14081        }
14082        final File codeFile = new File(codePath);
14083        final String name = codeFile.getName();
14084        if (codeFile.isDirectory()) {
14085            return name;
14086        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14087            final int lastDot = name.lastIndexOf('.');
14088            return name.substring(0, lastDot);
14089        } else {
14090            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14091            return null;
14092        }
14093    }
14094
14095    static class PackageInstalledInfo {
14096        String name;
14097        int uid;
14098        // The set of users that originally had this package installed.
14099        int[] origUsers;
14100        // The set of users that now have this package installed.
14101        int[] newUsers;
14102        PackageParser.Package pkg;
14103        int returnCode;
14104        String returnMsg;
14105        PackageRemovedInfo removedInfo;
14106        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14107
14108        public void setError(int code, String msg) {
14109            setReturnCode(code);
14110            setReturnMessage(msg);
14111            Slog.w(TAG, msg);
14112        }
14113
14114        public void setError(String msg, PackageParserException e) {
14115            setReturnCode(e.error);
14116            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14117            Slog.w(TAG, msg, e);
14118        }
14119
14120        public void setError(String msg, PackageManagerException e) {
14121            returnCode = e.error;
14122            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14123            Slog.w(TAG, msg, e);
14124        }
14125
14126        public void setReturnCode(int returnCode) {
14127            this.returnCode = returnCode;
14128            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14129            for (int i = 0; i < childCount; i++) {
14130                addedChildPackages.valueAt(i).returnCode = returnCode;
14131            }
14132        }
14133
14134        private void setReturnMessage(String returnMsg) {
14135            this.returnMsg = returnMsg;
14136            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14137            for (int i = 0; i < childCount; i++) {
14138                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14139            }
14140        }
14141
14142        // In some error cases we want to convey more info back to the observer
14143        String origPackage;
14144        String origPermission;
14145    }
14146
14147    /*
14148     * Install a non-existing package.
14149     */
14150    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14151            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14152            PackageInstalledInfo res) {
14153        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14154
14155        // Remember this for later, in case we need to rollback this install
14156        String pkgName = pkg.packageName;
14157
14158        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14159
14160        synchronized(mPackages) {
14161            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14162                // A package with the same name is already installed, though
14163                // it has been renamed to an older name.  The package we
14164                // are trying to install should be installed as an update to
14165                // the existing one, but that has not been requested, so bail.
14166                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14167                        + " without first uninstalling package running as "
14168                        + mSettings.mRenamedPackages.get(pkgName));
14169                return;
14170            }
14171            if (mPackages.containsKey(pkgName)) {
14172                // Don't allow installation over an existing package with the same name.
14173                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14174                        + " without first uninstalling.");
14175                return;
14176            }
14177        }
14178
14179        try {
14180            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14181                    System.currentTimeMillis(), user);
14182
14183            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14184
14185            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14186                prepareAppDataAfterInstallLIF(newPackage);
14187
14188            } else {
14189                // Remove package from internal structures, but keep around any
14190                // data that might have already existed
14191                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14192                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14193            }
14194        } catch (PackageManagerException e) {
14195            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14196        }
14197
14198        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14199    }
14200
14201    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14202        // Can't rotate keys during boot or if sharedUser.
14203        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14204                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14205            return false;
14206        }
14207        // app is using upgradeKeySets; make sure all are valid
14208        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14209        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14210        for (int i = 0; i < upgradeKeySets.length; i++) {
14211            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14212                Slog.wtf(TAG, "Package "
14213                         + (oldPs.name != null ? oldPs.name : "<null>")
14214                         + " contains upgrade-key-set reference to unknown key-set: "
14215                         + upgradeKeySets[i]
14216                         + " reverting to signatures check.");
14217                return false;
14218            }
14219        }
14220        return true;
14221    }
14222
14223    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14224        // Upgrade keysets are being used.  Determine if new package has a superset of the
14225        // required keys.
14226        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14227        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14228        for (int i = 0; i < upgradeKeySets.length; i++) {
14229            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14230            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14231                return true;
14232            }
14233        }
14234        return false;
14235    }
14236
14237    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14238        try (DigestInputStream digestStream =
14239                new DigestInputStream(new FileInputStream(file), digest)) {
14240            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14241        }
14242    }
14243
14244    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14245            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14246        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14247
14248        final PackageParser.Package oldPackage;
14249        final String pkgName = pkg.packageName;
14250        final int[] allUsers;
14251        final int[] installedUsers;
14252
14253        synchronized(mPackages) {
14254            oldPackage = mPackages.get(pkgName);
14255            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14256
14257            // don't allow upgrade to target a release SDK from a pre-release SDK
14258            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14259                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14260            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14261                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14262            if (oldTargetsPreRelease
14263                    && !newTargetsPreRelease
14264                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14265                Slog.w(TAG, "Can't install package targeting released sdk");
14266                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14267                return;
14268            }
14269
14270            // don't allow an upgrade from full to ephemeral
14271            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14272            if (isEphemeral && !oldIsEphemeral) {
14273                // can't downgrade from full to ephemeral
14274                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14275                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14276                return;
14277            }
14278
14279            // verify signatures are valid
14280            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14281            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14282                if (!checkUpgradeKeySetLP(ps, pkg)) {
14283                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14284                            "New package not signed by keys specified by upgrade-keysets: "
14285                                    + pkgName);
14286                    return;
14287                }
14288            } else {
14289                // default to original signature matching
14290                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14291                        != PackageManager.SIGNATURE_MATCH) {
14292                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14293                            "New package has a different signature: " + pkgName);
14294                    return;
14295                }
14296            }
14297
14298            // don't allow a system upgrade unless the upgrade hash matches
14299            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14300                byte[] digestBytes = null;
14301                try {
14302                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14303                    updateDigest(digest, new File(pkg.baseCodePath));
14304                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14305                        for (String path : pkg.splitCodePaths) {
14306                            updateDigest(digest, new File(path));
14307                        }
14308                    }
14309                    digestBytes = digest.digest();
14310                } catch (NoSuchAlgorithmException | IOException e) {
14311                    res.setError(INSTALL_FAILED_INVALID_APK,
14312                            "Could not compute hash: " + pkgName);
14313                    return;
14314                }
14315                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14316                    res.setError(INSTALL_FAILED_INVALID_APK,
14317                            "New package fails restrict-update check: " + pkgName);
14318                    return;
14319                }
14320                // retain upgrade restriction
14321                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14322            }
14323
14324            // Check for shared user id changes
14325            String invalidPackageName =
14326                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14327            if (invalidPackageName != null) {
14328                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14329                        "Package " + invalidPackageName + " tried to change user "
14330                                + oldPackage.mSharedUserId);
14331                return;
14332            }
14333
14334            // In case of rollback, remember per-user/profile install state
14335            allUsers = sUserManager.getUserIds();
14336            installedUsers = ps.queryInstalledUsers(allUsers, true);
14337        }
14338
14339        // Update what is removed
14340        res.removedInfo = new PackageRemovedInfo();
14341        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14342        res.removedInfo.removedPackage = oldPackage.packageName;
14343        res.removedInfo.isUpdate = true;
14344        res.removedInfo.origUsers = installedUsers;
14345        final int childCount = (oldPackage.childPackages != null)
14346                ? oldPackage.childPackages.size() : 0;
14347        for (int i = 0; i < childCount; i++) {
14348            boolean childPackageUpdated = false;
14349            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14350            if (res.addedChildPackages != null) {
14351                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14352                if (childRes != null) {
14353                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14354                    childRes.removedInfo.removedPackage = childPkg.packageName;
14355                    childRes.removedInfo.isUpdate = true;
14356                    childPackageUpdated = true;
14357                }
14358            }
14359            if (!childPackageUpdated) {
14360                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14361                childRemovedRes.removedPackage = childPkg.packageName;
14362                childRemovedRes.isUpdate = false;
14363                childRemovedRes.dataRemoved = true;
14364                synchronized (mPackages) {
14365                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14366                    if (childPs != null) {
14367                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14368                    }
14369                }
14370                if (res.removedInfo.removedChildPackages == null) {
14371                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14372                }
14373                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14374            }
14375        }
14376
14377        boolean sysPkg = (isSystemApp(oldPackage));
14378        if (sysPkg) {
14379            // Set the system/privileged flags as needed
14380            final boolean privileged =
14381                    (oldPackage.applicationInfo.privateFlags
14382                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14383            final int systemPolicyFlags = policyFlags
14384                    | PackageParser.PARSE_IS_SYSTEM
14385                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14386
14387            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14388                    user, allUsers, installerPackageName, res);
14389        } else {
14390            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14391                    user, allUsers, installerPackageName, res);
14392        }
14393    }
14394
14395    public List<String> getPreviousCodePaths(String packageName) {
14396        final PackageSetting ps = mSettings.mPackages.get(packageName);
14397        final List<String> result = new ArrayList<String>();
14398        if (ps != null && ps.oldCodePaths != null) {
14399            result.addAll(ps.oldCodePaths);
14400        }
14401        return result;
14402    }
14403
14404    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14405            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14406            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14407        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14408                + deletedPackage);
14409
14410        String pkgName = deletedPackage.packageName;
14411        boolean deletedPkg = true;
14412        boolean addedPkg = false;
14413        boolean updatedSettings = false;
14414        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14415        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14416                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14417
14418        final long origUpdateTime = (pkg.mExtras != null)
14419                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14420
14421        // First delete the existing package while retaining the data directory
14422        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14423                res.removedInfo, true, pkg)) {
14424            // If the existing package wasn't successfully deleted
14425            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14426            deletedPkg = false;
14427        } else {
14428            // Successfully deleted the old package; proceed with replace.
14429
14430            // If deleted package lived in a container, give users a chance to
14431            // relinquish resources before killing.
14432            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14433                if (DEBUG_INSTALL) {
14434                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14435                }
14436                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14437                final ArrayList<String> pkgList = new ArrayList<String>(1);
14438                pkgList.add(deletedPackage.applicationInfo.packageName);
14439                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14440            }
14441
14442            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14443                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14444            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14445
14446            try {
14447                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14448                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14449                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14450
14451                // Update the in-memory copy of the previous code paths.
14452                PackageSetting ps = mSettings.mPackages.get(pkgName);
14453                if (!killApp) {
14454                    if (ps.oldCodePaths == null) {
14455                        ps.oldCodePaths = new ArraySet<>();
14456                    }
14457                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14458                    if (deletedPackage.splitCodePaths != null) {
14459                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14460                    }
14461                } else {
14462                    ps.oldCodePaths = null;
14463                }
14464                if (ps.childPackageNames != null) {
14465                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14466                        final String childPkgName = ps.childPackageNames.get(i);
14467                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14468                        childPs.oldCodePaths = ps.oldCodePaths;
14469                    }
14470                }
14471                prepareAppDataAfterInstallLIF(newPackage);
14472                addedPkg = true;
14473            } catch (PackageManagerException e) {
14474                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14475            }
14476        }
14477
14478        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14479            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14480
14481            // Revert all internal state mutations and added folders for the failed install
14482            if (addedPkg) {
14483                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14484                        res.removedInfo, true, null);
14485            }
14486
14487            // Restore the old package
14488            if (deletedPkg) {
14489                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14490                File restoreFile = new File(deletedPackage.codePath);
14491                // Parse old package
14492                boolean oldExternal = isExternal(deletedPackage);
14493                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14494                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14495                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14496                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14497                try {
14498                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14499                            null);
14500                } catch (PackageManagerException e) {
14501                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14502                            + e.getMessage());
14503                    return;
14504                }
14505
14506                synchronized (mPackages) {
14507                    // Ensure the installer package name up to date
14508                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14509
14510                    // Update permissions for restored package
14511                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14512
14513                    mSettings.writeLPr();
14514                }
14515
14516                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14517            }
14518        } else {
14519            synchronized (mPackages) {
14520                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14521                if (ps != null) {
14522                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14523                    if (res.removedInfo.removedChildPackages != null) {
14524                        final int childCount = res.removedInfo.removedChildPackages.size();
14525                        // Iterate in reverse as we may modify the collection
14526                        for (int i = childCount - 1; i >= 0; i--) {
14527                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14528                            if (res.addedChildPackages.containsKey(childPackageName)) {
14529                                res.removedInfo.removedChildPackages.removeAt(i);
14530                            } else {
14531                                PackageRemovedInfo childInfo = res.removedInfo
14532                                        .removedChildPackages.valueAt(i);
14533                                childInfo.removedForAllUsers = mPackages.get(
14534                                        childInfo.removedPackage) == null;
14535                            }
14536                        }
14537                    }
14538                }
14539            }
14540        }
14541    }
14542
14543    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14544            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14545            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14546        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14547                + ", old=" + deletedPackage);
14548
14549        final boolean disabledSystem;
14550
14551        // Remove existing system package
14552        removePackageLI(deletedPackage, true);
14553
14554        synchronized (mPackages) {
14555            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14556        }
14557        if (!disabledSystem) {
14558            // We didn't need to disable the .apk as a current system package,
14559            // which means we are replacing another update that is already
14560            // installed.  We need to make sure to delete the older one's .apk.
14561            res.removedInfo.args = createInstallArgsForExisting(0,
14562                    deletedPackage.applicationInfo.getCodePath(),
14563                    deletedPackage.applicationInfo.getResourcePath(),
14564                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14565        } else {
14566            res.removedInfo.args = null;
14567        }
14568
14569        // Successfully disabled the old package. Now proceed with re-installation
14570        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14571                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14572        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14573
14574        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14575        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14576                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14577
14578        PackageParser.Package newPackage = null;
14579        try {
14580            // Add the package to the internal data structures
14581            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14582
14583            // Set the update and install times
14584            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14585            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14586                    System.currentTimeMillis());
14587
14588            // Update the package dynamic state if succeeded
14589            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14590                // Now that the install succeeded make sure we remove data
14591                // directories for any child package the update removed.
14592                final int deletedChildCount = (deletedPackage.childPackages != null)
14593                        ? deletedPackage.childPackages.size() : 0;
14594                final int newChildCount = (newPackage.childPackages != null)
14595                        ? newPackage.childPackages.size() : 0;
14596                for (int i = 0; i < deletedChildCount; i++) {
14597                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14598                    boolean childPackageDeleted = true;
14599                    for (int j = 0; j < newChildCount; j++) {
14600                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14601                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14602                            childPackageDeleted = false;
14603                            break;
14604                        }
14605                    }
14606                    if (childPackageDeleted) {
14607                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14608                                deletedChildPkg.packageName);
14609                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14610                            PackageRemovedInfo removedChildRes = res.removedInfo
14611                                    .removedChildPackages.get(deletedChildPkg.packageName);
14612                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14613                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14614                        }
14615                    }
14616                }
14617
14618                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14619                prepareAppDataAfterInstallLIF(newPackage);
14620            }
14621        } catch (PackageManagerException e) {
14622            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14623            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14624        }
14625
14626        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14627            // Re installation failed. Restore old information
14628            // Remove new pkg information
14629            if (newPackage != null) {
14630                removeInstalledPackageLI(newPackage, true);
14631            }
14632            // Add back the old system package
14633            try {
14634                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14635            } catch (PackageManagerException e) {
14636                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14637            }
14638
14639            synchronized (mPackages) {
14640                if (disabledSystem) {
14641                    enableSystemPackageLPw(deletedPackage);
14642                }
14643
14644                // Ensure the installer package name up to date
14645                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14646
14647                // Update permissions for restored package
14648                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14649
14650                mSettings.writeLPr();
14651            }
14652
14653            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14654                    + " after failed upgrade");
14655        }
14656    }
14657
14658    /**
14659     * Checks whether the parent or any of the child packages have a change shared
14660     * user. For a package to be a valid update the shred users of the parent and
14661     * the children should match. We may later support changing child shared users.
14662     * @param oldPkg The updated package.
14663     * @param newPkg The update package.
14664     * @return The shared user that change between the versions.
14665     */
14666    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14667            PackageParser.Package newPkg) {
14668        // Check parent shared user
14669        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14670            return newPkg.packageName;
14671        }
14672        // Check child shared users
14673        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14674        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14675        for (int i = 0; i < newChildCount; i++) {
14676            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14677            // If this child was present, did it have the same shared user?
14678            for (int j = 0; j < oldChildCount; j++) {
14679                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14680                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14681                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14682                    return newChildPkg.packageName;
14683                }
14684            }
14685        }
14686        return null;
14687    }
14688
14689    private void removeNativeBinariesLI(PackageSetting ps) {
14690        // Remove the lib path for the parent package
14691        if (ps != null) {
14692            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14693            // Remove the lib path for the child packages
14694            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14695            for (int i = 0; i < childCount; i++) {
14696                PackageSetting childPs = null;
14697                synchronized (mPackages) {
14698                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14699                }
14700                if (childPs != null) {
14701                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14702                            .legacyNativeLibraryPathString);
14703                }
14704            }
14705        }
14706    }
14707
14708    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14709        // Enable the parent package
14710        mSettings.enableSystemPackageLPw(pkg.packageName);
14711        // Enable the child packages
14712        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14713        for (int i = 0; i < childCount; i++) {
14714            PackageParser.Package childPkg = pkg.childPackages.get(i);
14715            mSettings.enableSystemPackageLPw(childPkg.packageName);
14716        }
14717    }
14718
14719    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14720            PackageParser.Package newPkg) {
14721        // Disable the parent package (parent always replaced)
14722        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14723        // Disable the child packages
14724        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14725        for (int i = 0; i < childCount; i++) {
14726            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14727            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14728            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14729        }
14730        return disabled;
14731    }
14732
14733    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14734            String installerPackageName) {
14735        // Enable the parent package
14736        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14737        // Enable the child packages
14738        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14739        for (int i = 0; i < childCount; i++) {
14740            PackageParser.Package childPkg = pkg.childPackages.get(i);
14741            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14742        }
14743    }
14744
14745    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14746        // Collect all used permissions in the UID
14747        ArraySet<String> usedPermissions = new ArraySet<>();
14748        final int packageCount = su.packages.size();
14749        for (int i = 0; i < packageCount; i++) {
14750            PackageSetting ps = su.packages.valueAt(i);
14751            if (ps.pkg == null) {
14752                continue;
14753            }
14754            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14755            for (int j = 0; j < requestedPermCount; j++) {
14756                String permission = ps.pkg.requestedPermissions.get(j);
14757                BasePermission bp = mSettings.mPermissions.get(permission);
14758                if (bp != null) {
14759                    usedPermissions.add(permission);
14760                }
14761            }
14762        }
14763
14764        PermissionsState permissionsState = su.getPermissionsState();
14765        // Prune install permissions
14766        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14767        final int installPermCount = installPermStates.size();
14768        for (int i = installPermCount - 1; i >= 0;  i--) {
14769            PermissionState permissionState = installPermStates.get(i);
14770            if (!usedPermissions.contains(permissionState.getName())) {
14771                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14772                if (bp != null) {
14773                    permissionsState.revokeInstallPermission(bp);
14774                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14775                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14776                }
14777            }
14778        }
14779
14780        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14781
14782        // Prune runtime permissions
14783        for (int userId : allUserIds) {
14784            List<PermissionState> runtimePermStates = permissionsState
14785                    .getRuntimePermissionStates(userId);
14786            final int runtimePermCount = runtimePermStates.size();
14787            for (int i = runtimePermCount - 1; i >= 0; i--) {
14788                PermissionState permissionState = runtimePermStates.get(i);
14789                if (!usedPermissions.contains(permissionState.getName())) {
14790                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14791                    if (bp != null) {
14792                        permissionsState.revokeRuntimePermission(bp, userId);
14793                        permissionsState.updatePermissionFlags(bp, userId,
14794                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14795                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14796                                runtimePermissionChangedUserIds, userId);
14797                    }
14798                }
14799            }
14800        }
14801
14802        return runtimePermissionChangedUserIds;
14803    }
14804
14805    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14806            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14807        // Update the parent package setting
14808        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14809                res, user);
14810        // Update the child packages setting
14811        final int childCount = (newPackage.childPackages != null)
14812                ? newPackage.childPackages.size() : 0;
14813        for (int i = 0; i < childCount; i++) {
14814            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14815            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14816            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14817                    childRes.origUsers, childRes, user);
14818        }
14819    }
14820
14821    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14822            String installerPackageName, int[] allUsers, int[] installedForUsers,
14823            PackageInstalledInfo res, UserHandle user) {
14824        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14825
14826        String pkgName = newPackage.packageName;
14827        synchronized (mPackages) {
14828            //write settings. the installStatus will be incomplete at this stage.
14829            //note that the new package setting would have already been
14830            //added to mPackages. It hasn't been persisted yet.
14831            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14832            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14833            mSettings.writeLPr();
14834            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14835        }
14836
14837        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14838        synchronized (mPackages) {
14839            updatePermissionsLPw(newPackage.packageName, newPackage,
14840                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14841                            ? UPDATE_PERMISSIONS_ALL : 0));
14842            // For system-bundled packages, we assume that installing an upgraded version
14843            // of the package implies that the user actually wants to run that new code,
14844            // so we enable the package.
14845            PackageSetting ps = mSettings.mPackages.get(pkgName);
14846            final int userId = user.getIdentifier();
14847            if (ps != null) {
14848                if (isSystemApp(newPackage)) {
14849                    if (DEBUG_INSTALL) {
14850                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14851                    }
14852                    // Enable system package for requested users
14853                    if (res.origUsers != null) {
14854                        for (int origUserId : res.origUsers) {
14855                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14856                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14857                                        origUserId, installerPackageName);
14858                            }
14859                        }
14860                    }
14861                    // Also convey the prior install/uninstall state
14862                    if (allUsers != null && installedForUsers != null) {
14863                        for (int currentUserId : allUsers) {
14864                            final boolean installed = ArrayUtils.contains(
14865                                    installedForUsers, currentUserId);
14866                            if (DEBUG_INSTALL) {
14867                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14868                            }
14869                            ps.setInstalled(installed, currentUserId);
14870                        }
14871                        // these install state changes will be persisted in the
14872                        // upcoming call to mSettings.writeLPr().
14873                    }
14874                }
14875                // It's implied that when a user requests installation, they want the app to be
14876                // installed and enabled.
14877                if (userId != UserHandle.USER_ALL) {
14878                    ps.setInstalled(true, userId);
14879                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14880                }
14881            }
14882            res.name = pkgName;
14883            res.uid = newPackage.applicationInfo.uid;
14884            res.pkg = newPackage;
14885            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14886            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14887            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14888            //to update install status
14889            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14890            mSettings.writeLPr();
14891            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14892        }
14893
14894        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14895    }
14896
14897    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14898        try {
14899            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14900            installPackageLI(args, res);
14901        } finally {
14902            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14903        }
14904    }
14905
14906    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14907        final int installFlags = args.installFlags;
14908        final String installerPackageName = args.installerPackageName;
14909        final String volumeUuid = args.volumeUuid;
14910        final File tmpPackageFile = new File(args.getCodePath());
14911        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14912        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14913                || (args.volumeUuid != null));
14914        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14915        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14916        boolean replace = false;
14917        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14918        if (args.move != null) {
14919            // moving a complete application; perform an initial scan on the new install location
14920            scanFlags |= SCAN_INITIAL;
14921        }
14922        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14923            scanFlags |= SCAN_DONT_KILL_APP;
14924        }
14925
14926        // Result object to be returned
14927        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14928
14929        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14930
14931        // Sanity check
14932        if (ephemeral && (forwardLocked || onExternal)) {
14933            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14934                    + " external=" + onExternal);
14935            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14936            return;
14937        }
14938
14939        // Retrieve PackageSettings and parse package
14940        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14941                | PackageParser.PARSE_ENFORCE_CODE
14942                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14943                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14944                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14945                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14946        PackageParser pp = new PackageParser();
14947        pp.setSeparateProcesses(mSeparateProcesses);
14948        pp.setDisplayMetrics(mMetrics);
14949
14950        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14951        final PackageParser.Package pkg;
14952        try {
14953            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14954        } catch (PackageParserException e) {
14955            res.setError("Failed parse during installPackageLI", e);
14956            return;
14957        } finally {
14958            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14959        }
14960
14961        // If we are installing a clustered package add results for the children
14962        if (pkg.childPackages != null) {
14963            synchronized (mPackages) {
14964                final int childCount = pkg.childPackages.size();
14965                for (int i = 0; i < childCount; i++) {
14966                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14967                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14968                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14969                    childRes.pkg = childPkg;
14970                    childRes.name = childPkg.packageName;
14971                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14972                    if (childPs != null) {
14973                        childRes.origUsers = childPs.queryInstalledUsers(
14974                                sUserManager.getUserIds(), true);
14975                    }
14976                    if ((mPackages.containsKey(childPkg.packageName))) {
14977                        childRes.removedInfo = new PackageRemovedInfo();
14978                        childRes.removedInfo.removedPackage = childPkg.packageName;
14979                    }
14980                    if (res.addedChildPackages == null) {
14981                        res.addedChildPackages = new ArrayMap<>();
14982                    }
14983                    res.addedChildPackages.put(childPkg.packageName, childRes);
14984                }
14985            }
14986        }
14987
14988        // If package doesn't declare API override, mark that we have an install
14989        // time CPU ABI override.
14990        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14991            pkg.cpuAbiOverride = args.abiOverride;
14992        }
14993
14994        String pkgName = res.name = pkg.packageName;
14995        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14996            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14997                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14998                return;
14999            }
15000        }
15001
15002        try {
15003            // either use what we've been given or parse directly from the APK
15004            if (args.certificates != null) {
15005                try {
15006                    PackageParser.populateCertificates(pkg, args.certificates);
15007                } catch (PackageParserException e) {
15008                    // there was something wrong with the certificates we were given;
15009                    // try to pull them from the APK
15010                    PackageParser.collectCertificates(pkg, parseFlags);
15011                }
15012            } else {
15013                PackageParser.collectCertificates(pkg, parseFlags);
15014            }
15015        } catch (PackageParserException e) {
15016            res.setError("Failed collect during installPackageLI", e);
15017            return;
15018        }
15019
15020        // Get rid of all references to package scan path via parser.
15021        pp = null;
15022        String oldCodePath = null;
15023        boolean systemApp = false;
15024        synchronized (mPackages) {
15025            // Check if installing already existing package
15026            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15027                String oldName = mSettings.mRenamedPackages.get(pkgName);
15028                if (pkg.mOriginalPackages != null
15029                        && pkg.mOriginalPackages.contains(oldName)
15030                        && mPackages.containsKey(oldName)) {
15031                    // This package is derived from an original package,
15032                    // and this device has been updating from that original
15033                    // name.  We must continue using the original name, so
15034                    // rename the new package here.
15035                    pkg.setPackageName(oldName);
15036                    pkgName = pkg.packageName;
15037                    replace = true;
15038                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15039                            + oldName + " pkgName=" + pkgName);
15040                } else if (mPackages.containsKey(pkgName)) {
15041                    // This package, under its official name, already exists
15042                    // on the device; we should replace it.
15043                    replace = true;
15044                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15045                }
15046
15047                // Child packages are installed through the parent package
15048                if (pkg.parentPackage != null) {
15049                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15050                            "Package " + pkg.packageName + " is child of package "
15051                                    + pkg.parentPackage.parentPackage + ". Child packages "
15052                                    + "can be updated only through the parent package.");
15053                    return;
15054                }
15055
15056                if (replace) {
15057                    // Prevent apps opting out from runtime permissions
15058                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15059                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15060                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15061                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15062                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15063                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15064                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15065                                        + " doesn't support runtime permissions but the old"
15066                                        + " target SDK " + oldTargetSdk + " does.");
15067                        return;
15068                    }
15069
15070                    // Prevent installing of child packages
15071                    if (oldPackage.parentPackage != null) {
15072                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15073                                "Package " + pkg.packageName + " is child of package "
15074                                        + oldPackage.parentPackage + ". Child packages "
15075                                        + "can be updated only through the parent package.");
15076                        return;
15077                    }
15078                }
15079            }
15080
15081            PackageSetting ps = mSettings.mPackages.get(pkgName);
15082            if (ps != null) {
15083                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15084
15085                // Quick sanity check that we're signed correctly if updating;
15086                // we'll check this again later when scanning, but we want to
15087                // bail early here before tripping over redefined permissions.
15088                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15089                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15090                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15091                                + pkg.packageName + " upgrade keys do not match the "
15092                                + "previously installed version");
15093                        return;
15094                    }
15095                } else {
15096                    try {
15097                        verifySignaturesLP(ps, pkg);
15098                    } catch (PackageManagerException e) {
15099                        res.setError(e.error, e.getMessage());
15100                        return;
15101                    }
15102                }
15103
15104                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15105                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15106                    systemApp = (ps.pkg.applicationInfo.flags &
15107                            ApplicationInfo.FLAG_SYSTEM) != 0;
15108                }
15109                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15110            }
15111
15112            // Check whether the newly-scanned package wants to define an already-defined perm
15113            int N = pkg.permissions.size();
15114            for (int i = N-1; i >= 0; i--) {
15115                PackageParser.Permission perm = pkg.permissions.get(i);
15116                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15117                if (bp != null) {
15118                    // If the defining package is signed with our cert, it's okay.  This
15119                    // also includes the "updating the same package" case, of course.
15120                    // "updating same package" could also involve key-rotation.
15121                    final boolean sigsOk;
15122                    if (bp.sourcePackage.equals(pkg.packageName)
15123                            && (bp.packageSetting instanceof PackageSetting)
15124                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15125                                    scanFlags))) {
15126                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15127                    } else {
15128                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15129                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15130                    }
15131                    if (!sigsOk) {
15132                        // If the owning package is the system itself, we log but allow
15133                        // install to proceed; we fail the install on all other permission
15134                        // redefinitions.
15135                        if (!bp.sourcePackage.equals("android")) {
15136                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15137                                    + pkg.packageName + " attempting to redeclare permission "
15138                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15139                            res.origPermission = perm.info.name;
15140                            res.origPackage = bp.sourcePackage;
15141                            return;
15142                        } else {
15143                            Slog.w(TAG, "Package " + pkg.packageName
15144                                    + " attempting to redeclare system permission "
15145                                    + perm.info.name + "; ignoring new declaration");
15146                            pkg.permissions.remove(i);
15147                        }
15148                    }
15149                }
15150            }
15151        }
15152
15153        if (systemApp) {
15154            if (onExternal) {
15155                // Abort update; system app can't be replaced with app on sdcard
15156                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15157                        "Cannot install updates to system apps on sdcard");
15158                return;
15159            } else if (ephemeral) {
15160                // Abort update; system app can't be replaced with an ephemeral app
15161                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15162                        "Cannot update a system app with an ephemeral app");
15163                return;
15164            }
15165        }
15166
15167        if (args.move != null) {
15168            // We did an in-place move, so dex is ready to roll
15169            scanFlags |= SCAN_NO_DEX;
15170            scanFlags |= SCAN_MOVE;
15171
15172            synchronized (mPackages) {
15173                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15174                if (ps == null) {
15175                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15176                            "Missing settings for moved package " + pkgName);
15177                }
15178
15179                // We moved the entire application as-is, so bring over the
15180                // previously derived ABI information.
15181                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15182                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15183            }
15184
15185        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15186            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15187            scanFlags |= SCAN_NO_DEX;
15188
15189            try {
15190                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15191                    args.abiOverride : pkg.cpuAbiOverride);
15192                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15193                        true /* extract libs */);
15194            } catch (PackageManagerException pme) {
15195                Slog.e(TAG, "Error deriving application ABI", pme);
15196                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15197                return;
15198            }
15199
15200            // Shared libraries for the package need to be updated.
15201            synchronized (mPackages) {
15202                try {
15203                    updateSharedLibrariesLPw(pkg, null);
15204                } catch (PackageManagerException e) {
15205                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15206                }
15207            }
15208            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15209            // Do not run PackageDexOptimizer through the local performDexOpt
15210            // method because `pkg` may not be in `mPackages` yet.
15211            //
15212            // Also, don't fail application installs if the dexopt step fails.
15213            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15214                    null /* instructionSets */, false /* checkProfiles */,
15215                    getCompilerFilterForReason(REASON_INSTALL));
15216            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15217
15218            // Notify BackgroundDexOptService that the package has been changed.
15219            // If this is an update of a package which used to fail to compile,
15220            // BDOS will remove it from its blacklist.
15221            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15222        }
15223
15224        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15225            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15226            return;
15227        }
15228
15229        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15230
15231        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15232                "installPackageLI")) {
15233            if (replace) {
15234                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15235                        installerPackageName, res);
15236            } else {
15237                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15238                        args.user, installerPackageName, volumeUuid, res);
15239            }
15240        }
15241        synchronized (mPackages) {
15242            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15243            if (ps != null) {
15244                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15245            }
15246
15247            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15248            for (int i = 0; i < childCount; i++) {
15249                PackageParser.Package childPkg = pkg.childPackages.get(i);
15250                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15251                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15252                if (childPs != null) {
15253                    childRes.newUsers = childPs.queryInstalledUsers(
15254                            sUserManager.getUserIds(), true);
15255                }
15256            }
15257        }
15258    }
15259
15260    private void startIntentFilterVerifications(int userId, boolean replacing,
15261            PackageParser.Package pkg) {
15262        if (mIntentFilterVerifierComponent == null) {
15263            Slog.w(TAG, "No IntentFilter verification will not be done as "
15264                    + "there is no IntentFilterVerifier available!");
15265            return;
15266        }
15267
15268        final int verifierUid = getPackageUid(
15269                mIntentFilterVerifierComponent.getPackageName(),
15270                MATCH_DEBUG_TRIAGED_MISSING,
15271                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15272
15273        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15274        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15275        mHandler.sendMessage(msg);
15276
15277        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15278        for (int i = 0; i < childCount; i++) {
15279            PackageParser.Package childPkg = pkg.childPackages.get(i);
15280            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15281            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15282            mHandler.sendMessage(msg);
15283        }
15284    }
15285
15286    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15287            PackageParser.Package pkg) {
15288        int size = pkg.activities.size();
15289        if (size == 0) {
15290            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15291                    "No activity, so no need to verify any IntentFilter!");
15292            return;
15293        }
15294
15295        final boolean hasDomainURLs = hasDomainURLs(pkg);
15296        if (!hasDomainURLs) {
15297            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15298                    "No domain URLs, so no need to verify any IntentFilter!");
15299            return;
15300        }
15301
15302        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15303                + " if any IntentFilter from the " + size
15304                + " Activities needs verification ...");
15305
15306        int count = 0;
15307        final String packageName = pkg.packageName;
15308
15309        synchronized (mPackages) {
15310            // If this is a new install and we see that we've already run verification for this
15311            // package, we have nothing to do: it means the state was restored from backup.
15312            if (!replacing) {
15313                IntentFilterVerificationInfo ivi =
15314                        mSettings.getIntentFilterVerificationLPr(packageName);
15315                if (ivi != null) {
15316                    if (DEBUG_DOMAIN_VERIFICATION) {
15317                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15318                                + ivi.getStatusString());
15319                    }
15320                    return;
15321                }
15322            }
15323
15324            // If any filters need to be verified, then all need to be.
15325            boolean needToVerify = false;
15326            for (PackageParser.Activity a : pkg.activities) {
15327                for (ActivityIntentInfo filter : a.intents) {
15328                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15329                        if (DEBUG_DOMAIN_VERIFICATION) {
15330                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15331                        }
15332                        needToVerify = true;
15333                        break;
15334                    }
15335                }
15336            }
15337
15338            if (needToVerify) {
15339                final int verificationId = mIntentFilterVerificationToken++;
15340                for (PackageParser.Activity a : pkg.activities) {
15341                    for (ActivityIntentInfo filter : a.intents) {
15342                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15343                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15344                                    "Verification needed for IntentFilter:" + filter.toString());
15345                            mIntentFilterVerifier.addOneIntentFilterVerification(
15346                                    verifierUid, userId, verificationId, filter, packageName);
15347                            count++;
15348                        }
15349                    }
15350                }
15351            }
15352        }
15353
15354        if (count > 0) {
15355            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15356                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15357                    +  " for userId:" + userId);
15358            mIntentFilterVerifier.startVerifications(userId);
15359        } else {
15360            if (DEBUG_DOMAIN_VERIFICATION) {
15361                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15362            }
15363        }
15364    }
15365
15366    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15367        final ComponentName cn  = filter.activity.getComponentName();
15368        final String packageName = cn.getPackageName();
15369
15370        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15371                packageName);
15372        if (ivi == null) {
15373            return true;
15374        }
15375        int status = ivi.getStatus();
15376        switch (status) {
15377            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15378            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15379                return true;
15380
15381            default:
15382                // Nothing to do
15383                return false;
15384        }
15385    }
15386
15387    private static boolean isMultiArch(ApplicationInfo info) {
15388        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15389    }
15390
15391    private static boolean isExternal(PackageParser.Package pkg) {
15392        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15393    }
15394
15395    private static boolean isExternal(PackageSetting ps) {
15396        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15397    }
15398
15399    private static boolean isEphemeral(PackageParser.Package pkg) {
15400        return pkg.applicationInfo.isEphemeralApp();
15401    }
15402
15403    private static boolean isEphemeral(PackageSetting ps) {
15404        return ps.pkg != null && isEphemeral(ps.pkg);
15405    }
15406
15407    private static boolean isSystemApp(PackageParser.Package pkg) {
15408        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15409    }
15410
15411    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15412        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15413    }
15414
15415    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15416        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15417    }
15418
15419    private static boolean isSystemApp(PackageSetting ps) {
15420        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15421    }
15422
15423    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15424        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15425    }
15426
15427    private int packageFlagsToInstallFlags(PackageSetting ps) {
15428        int installFlags = 0;
15429        if (isEphemeral(ps)) {
15430            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15431        }
15432        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15433            // This existing package was an external ASEC install when we have
15434            // the external flag without a UUID
15435            installFlags |= PackageManager.INSTALL_EXTERNAL;
15436        }
15437        if (ps.isForwardLocked()) {
15438            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15439        }
15440        return installFlags;
15441    }
15442
15443    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15444        if (isExternal(pkg)) {
15445            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15446                return StorageManager.UUID_PRIMARY_PHYSICAL;
15447            } else {
15448                return pkg.volumeUuid;
15449            }
15450        } else {
15451            return StorageManager.UUID_PRIVATE_INTERNAL;
15452        }
15453    }
15454
15455    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15456        if (isExternal(pkg)) {
15457            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15458                return mSettings.getExternalVersion();
15459            } else {
15460                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15461            }
15462        } else {
15463            return mSettings.getInternalVersion();
15464        }
15465    }
15466
15467    private void deleteTempPackageFiles() {
15468        final FilenameFilter filter = new FilenameFilter() {
15469            public boolean accept(File dir, String name) {
15470                return name.startsWith("vmdl") && name.endsWith(".tmp");
15471            }
15472        };
15473        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15474            file.delete();
15475        }
15476    }
15477
15478    @Override
15479    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15480            int flags) {
15481        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15482                flags);
15483    }
15484
15485    @Override
15486    public void deletePackage(final String packageName,
15487            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15488        mContext.enforceCallingOrSelfPermission(
15489                android.Manifest.permission.DELETE_PACKAGES, null);
15490        Preconditions.checkNotNull(packageName);
15491        Preconditions.checkNotNull(observer);
15492        final int uid = Binder.getCallingUid();
15493        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15494        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15495        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15496            mContext.enforceCallingOrSelfPermission(
15497                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15498                    "deletePackage for user " + userId);
15499        }
15500
15501        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15502            try {
15503                observer.onPackageDeleted(packageName,
15504                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15505            } catch (RemoteException re) {
15506            }
15507            return;
15508        }
15509
15510        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15511            try {
15512                observer.onPackageDeleted(packageName,
15513                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15514            } catch (RemoteException re) {
15515            }
15516            return;
15517        }
15518
15519        if (DEBUG_REMOVE) {
15520            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15521                    + " deleteAllUsers: " + deleteAllUsers );
15522        }
15523        // Queue up an async operation since the package deletion may take a little while.
15524        mHandler.post(new Runnable() {
15525            public void run() {
15526                mHandler.removeCallbacks(this);
15527                int returnCode;
15528                if (!deleteAllUsers) {
15529                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15530                } else {
15531                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15532                    // If nobody is blocking uninstall, proceed with delete for all users
15533                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15534                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15535                    } else {
15536                        // Otherwise uninstall individually for users with blockUninstalls=false
15537                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15538                        for (int userId : users) {
15539                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15540                                returnCode = deletePackageX(packageName, userId, userFlags);
15541                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15542                                    Slog.w(TAG, "Package delete failed for user " + userId
15543                                            + ", returnCode " + returnCode);
15544                                }
15545                            }
15546                        }
15547                        // The app has only been marked uninstalled for certain users.
15548                        // We still need to report that delete was blocked
15549                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15550                    }
15551                }
15552                try {
15553                    observer.onPackageDeleted(packageName, returnCode, null);
15554                } catch (RemoteException e) {
15555                    Log.i(TAG, "Observer no longer exists.");
15556                } //end catch
15557            } //end run
15558        });
15559    }
15560
15561    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15562        int[] result = EMPTY_INT_ARRAY;
15563        for (int userId : userIds) {
15564            if (getBlockUninstallForUser(packageName, userId)) {
15565                result = ArrayUtils.appendInt(result, userId);
15566            }
15567        }
15568        return result;
15569    }
15570
15571    @Override
15572    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15573        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15574    }
15575
15576    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15577        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15578                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15579        try {
15580            if (dpm != null) {
15581                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15582                        /* callingUserOnly =*/ false);
15583                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15584                        : deviceOwnerComponentName.getPackageName();
15585                // Does the package contains the device owner?
15586                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15587                // this check is probably not needed, since DO should be registered as a device
15588                // admin on some user too. (Original bug for this: b/17657954)
15589                if (packageName.equals(deviceOwnerPackageName)) {
15590                    return true;
15591                }
15592                // Does it contain a device admin for any user?
15593                int[] users;
15594                if (userId == UserHandle.USER_ALL) {
15595                    users = sUserManager.getUserIds();
15596                } else {
15597                    users = new int[]{userId};
15598                }
15599                for (int i = 0; i < users.length; ++i) {
15600                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15601                        return true;
15602                    }
15603                }
15604            }
15605        } catch (RemoteException e) {
15606        }
15607        return false;
15608    }
15609
15610    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15611        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15612    }
15613
15614    /**
15615     *  This method is an internal method that could be get invoked either
15616     *  to delete an installed package or to clean up a failed installation.
15617     *  After deleting an installed package, a broadcast is sent to notify any
15618     *  listeners that the package has been removed. For cleaning up a failed
15619     *  installation, the broadcast is not necessary since the package's
15620     *  installation wouldn't have sent the initial broadcast either
15621     *  The key steps in deleting a package are
15622     *  deleting the package information in internal structures like mPackages,
15623     *  deleting the packages base directories through installd
15624     *  updating mSettings to reflect current status
15625     *  persisting settings for later use
15626     *  sending a broadcast if necessary
15627     */
15628    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15629        final PackageRemovedInfo info = new PackageRemovedInfo();
15630        final boolean res;
15631
15632        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15633                ? UserHandle.USER_ALL : userId;
15634
15635        if (isPackageDeviceAdmin(packageName, removeUser)) {
15636            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15637            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15638        }
15639
15640        PackageSetting uninstalledPs = null;
15641
15642        // for the uninstall-updates case and restricted profiles, remember the per-
15643        // user handle installed state
15644        int[] allUsers;
15645        synchronized (mPackages) {
15646            uninstalledPs = mSettings.mPackages.get(packageName);
15647            if (uninstalledPs == null) {
15648                Slog.w(TAG, "Not removing non-existent package " + packageName);
15649                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15650            }
15651            allUsers = sUserManager.getUserIds();
15652            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15653        }
15654
15655        final int freezeUser;
15656        if (isUpdatedSystemApp(uninstalledPs)
15657                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15658            // We're downgrading a system app, which will apply to all users, so
15659            // freeze them all during the downgrade
15660            freezeUser = UserHandle.USER_ALL;
15661        } else {
15662            freezeUser = removeUser;
15663        }
15664
15665        synchronized (mInstallLock) {
15666            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15667            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15668                    deleteFlags, "deletePackageX")) {
15669                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15670                        deleteFlags | REMOVE_CHATTY, info, true, null);
15671            }
15672            synchronized (mPackages) {
15673                if (res) {
15674                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15675                }
15676            }
15677        }
15678
15679        if (res) {
15680            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15681            info.sendPackageRemovedBroadcasts(killApp);
15682            info.sendSystemPackageUpdatedBroadcasts();
15683            info.sendSystemPackageAppearedBroadcasts();
15684        }
15685        // Force a gc here.
15686        Runtime.getRuntime().gc();
15687        // Delete the resources here after sending the broadcast to let
15688        // other processes clean up before deleting resources.
15689        if (info.args != null) {
15690            synchronized (mInstallLock) {
15691                info.args.doPostDeleteLI(true);
15692            }
15693        }
15694
15695        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15696    }
15697
15698    class PackageRemovedInfo {
15699        String removedPackage;
15700        int uid = -1;
15701        int removedAppId = -1;
15702        int[] origUsers;
15703        int[] removedUsers = null;
15704        boolean isRemovedPackageSystemUpdate = false;
15705        boolean isUpdate;
15706        boolean dataRemoved;
15707        boolean removedForAllUsers;
15708        // Clean up resources deleted packages.
15709        InstallArgs args = null;
15710        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15711        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15712
15713        void sendPackageRemovedBroadcasts(boolean killApp) {
15714            sendPackageRemovedBroadcastInternal(killApp);
15715            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15716            for (int i = 0; i < childCount; i++) {
15717                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15718                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15719            }
15720        }
15721
15722        void sendSystemPackageUpdatedBroadcasts() {
15723            if (isRemovedPackageSystemUpdate) {
15724                sendSystemPackageUpdatedBroadcastsInternal();
15725                final int childCount = (removedChildPackages != null)
15726                        ? removedChildPackages.size() : 0;
15727                for (int i = 0; i < childCount; i++) {
15728                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15729                    if (childInfo.isRemovedPackageSystemUpdate) {
15730                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15731                    }
15732                }
15733            }
15734        }
15735
15736        void sendSystemPackageAppearedBroadcasts() {
15737            final int packageCount = (appearedChildPackages != null)
15738                    ? appearedChildPackages.size() : 0;
15739            for (int i = 0; i < packageCount; i++) {
15740                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15741                for (int userId : installedInfo.newUsers) {
15742                    sendPackageAddedForUser(installedInfo.name, true,
15743                            UserHandle.getAppId(installedInfo.uid), userId);
15744                }
15745            }
15746        }
15747
15748        private void sendSystemPackageUpdatedBroadcastsInternal() {
15749            Bundle extras = new Bundle(2);
15750            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15751            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15752            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15753                    extras, 0, null, null, null);
15754            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15755                    extras, 0, null, null, null);
15756            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15757                    null, 0, removedPackage, null, null);
15758        }
15759
15760        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15761            Bundle extras = new Bundle(2);
15762            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15763            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15764            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15765            if (isUpdate || isRemovedPackageSystemUpdate) {
15766                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15767            }
15768            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15769            if (removedPackage != null) {
15770                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15771                        extras, 0, null, null, removedUsers);
15772                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15773                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15774                            removedPackage, extras, 0, null, null, removedUsers);
15775                }
15776            }
15777            if (removedAppId >= 0) {
15778                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15779                        removedUsers);
15780            }
15781        }
15782    }
15783
15784    /*
15785     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15786     * flag is not set, the data directory is removed as well.
15787     * make sure this flag is set for partially installed apps. If not its meaningless to
15788     * delete a partially installed application.
15789     */
15790    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15791            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15792        String packageName = ps.name;
15793        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15794        // Retrieve object to delete permissions for shared user later on
15795        final PackageParser.Package deletedPkg;
15796        final PackageSetting deletedPs;
15797        // reader
15798        synchronized (mPackages) {
15799            deletedPkg = mPackages.get(packageName);
15800            deletedPs = mSettings.mPackages.get(packageName);
15801            if (outInfo != null) {
15802                outInfo.removedPackage = packageName;
15803                outInfo.removedUsers = deletedPs != null
15804                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15805                        : null;
15806            }
15807        }
15808
15809        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15810
15811        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15812            final PackageParser.Package resolvedPkg;
15813            if (deletedPkg != null) {
15814                resolvedPkg = deletedPkg;
15815            } else {
15816                // We don't have a parsed package when it lives on an ejected
15817                // adopted storage device, so fake something together
15818                resolvedPkg = new PackageParser.Package(ps.name);
15819                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15820            }
15821            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15822                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15823            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15824            if (outInfo != null) {
15825                outInfo.dataRemoved = true;
15826            }
15827            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15828        }
15829
15830        // writer
15831        synchronized (mPackages) {
15832            if (deletedPs != null) {
15833                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15834                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15835                    clearDefaultBrowserIfNeeded(packageName);
15836                    if (outInfo != null) {
15837                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15838                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15839                    }
15840                    updatePermissionsLPw(deletedPs.name, null, 0);
15841                    if (deletedPs.sharedUser != null) {
15842                        // Remove permissions associated with package. Since runtime
15843                        // permissions are per user we have to kill the removed package
15844                        // or packages running under the shared user of the removed
15845                        // package if revoking the permissions requested only by the removed
15846                        // package is successful and this causes a change in gids.
15847                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15848                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15849                                    userId);
15850                            if (userIdToKill == UserHandle.USER_ALL
15851                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15852                                // If gids changed for this user, kill all affected packages.
15853                                mHandler.post(new Runnable() {
15854                                    @Override
15855                                    public void run() {
15856                                        // This has to happen with no lock held.
15857                                        killApplication(deletedPs.name, deletedPs.appId,
15858                                                KILL_APP_REASON_GIDS_CHANGED);
15859                                    }
15860                                });
15861                                break;
15862                            }
15863                        }
15864                    }
15865                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15866                }
15867                // make sure to preserve per-user disabled state if this removal was just
15868                // a downgrade of a system app to the factory package
15869                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15870                    if (DEBUG_REMOVE) {
15871                        Slog.d(TAG, "Propagating install state across downgrade");
15872                    }
15873                    for (int userId : allUserHandles) {
15874                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15875                        if (DEBUG_REMOVE) {
15876                            Slog.d(TAG, "    user " + userId + " => " + installed);
15877                        }
15878                        ps.setInstalled(installed, userId);
15879                    }
15880                }
15881            }
15882            // can downgrade to reader
15883            if (writeSettings) {
15884                // Save settings now
15885                mSettings.writeLPr();
15886            }
15887        }
15888        if (outInfo != null) {
15889            // A user ID was deleted here. Go through all users and remove it
15890            // from KeyStore.
15891            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15892        }
15893    }
15894
15895    static boolean locationIsPrivileged(File path) {
15896        try {
15897            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15898                    .getCanonicalPath();
15899            return path.getCanonicalPath().startsWith(privilegedAppDir);
15900        } catch (IOException e) {
15901            Slog.e(TAG, "Unable to access code path " + path);
15902        }
15903        return false;
15904    }
15905
15906    /*
15907     * Tries to delete system package.
15908     */
15909    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15910            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15911            boolean writeSettings) {
15912        if (deletedPs.parentPackageName != null) {
15913            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15914            return false;
15915        }
15916
15917        final boolean applyUserRestrictions
15918                = (allUserHandles != null) && (outInfo.origUsers != null);
15919        final PackageSetting disabledPs;
15920        // Confirm if the system package has been updated
15921        // An updated system app can be deleted. This will also have to restore
15922        // the system pkg from system partition
15923        // reader
15924        synchronized (mPackages) {
15925            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15926        }
15927
15928        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15929                + " disabledPs=" + disabledPs);
15930
15931        if (disabledPs == null) {
15932            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15933            return false;
15934        } else if (DEBUG_REMOVE) {
15935            Slog.d(TAG, "Deleting system pkg from data partition");
15936        }
15937
15938        if (DEBUG_REMOVE) {
15939            if (applyUserRestrictions) {
15940                Slog.d(TAG, "Remembering install states:");
15941                for (int userId : allUserHandles) {
15942                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15943                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15944                }
15945            }
15946        }
15947
15948        // Delete the updated package
15949        outInfo.isRemovedPackageSystemUpdate = true;
15950        if (outInfo.removedChildPackages != null) {
15951            final int childCount = (deletedPs.childPackageNames != null)
15952                    ? deletedPs.childPackageNames.size() : 0;
15953            for (int i = 0; i < childCount; i++) {
15954                String childPackageName = deletedPs.childPackageNames.get(i);
15955                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15956                        .contains(childPackageName)) {
15957                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15958                            childPackageName);
15959                    if (childInfo != null) {
15960                        childInfo.isRemovedPackageSystemUpdate = true;
15961                    }
15962                }
15963            }
15964        }
15965
15966        if (disabledPs.versionCode < deletedPs.versionCode) {
15967            // Delete data for downgrades
15968            flags &= ~PackageManager.DELETE_KEEP_DATA;
15969        } else {
15970            // Preserve data by setting flag
15971            flags |= PackageManager.DELETE_KEEP_DATA;
15972        }
15973
15974        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15975                outInfo, writeSettings, disabledPs.pkg);
15976        if (!ret) {
15977            return false;
15978        }
15979
15980        // writer
15981        synchronized (mPackages) {
15982            // Reinstate the old system package
15983            enableSystemPackageLPw(disabledPs.pkg);
15984            // Remove any native libraries from the upgraded package.
15985            removeNativeBinariesLI(deletedPs);
15986        }
15987
15988        // Install the system package
15989        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15990        int parseFlags = mDefParseFlags
15991                | PackageParser.PARSE_MUST_BE_APK
15992                | PackageParser.PARSE_IS_SYSTEM
15993                | PackageParser.PARSE_IS_SYSTEM_DIR;
15994        if (locationIsPrivileged(disabledPs.codePath)) {
15995            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15996        }
15997
15998        final PackageParser.Package newPkg;
15999        try {
16000            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16001        } catch (PackageManagerException e) {
16002            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16003                    + e.getMessage());
16004            return false;
16005        }
16006
16007        prepareAppDataAfterInstallLIF(newPkg);
16008
16009        // writer
16010        synchronized (mPackages) {
16011            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16012
16013            // Propagate the permissions state as we do not want to drop on the floor
16014            // runtime permissions. The update permissions method below will take
16015            // care of removing obsolete permissions and grant install permissions.
16016            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16017            updatePermissionsLPw(newPkg.packageName, newPkg,
16018                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16019
16020            if (applyUserRestrictions) {
16021                if (DEBUG_REMOVE) {
16022                    Slog.d(TAG, "Propagating install state across reinstall");
16023                }
16024                for (int userId : allUserHandles) {
16025                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16026                    if (DEBUG_REMOVE) {
16027                        Slog.d(TAG, "    user " + userId + " => " + installed);
16028                    }
16029                    ps.setInstalled(installed, userId);
16030
16031                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16032                }
16033                // Regardless of writeSettings we need to ensure that this restriction
16034                // state propagation is persisted
16035                mSettings.writeAllUsersPackageRestrictionsLPr();
16036            }
16037            // can downgrade to reader here
16038            if (writeSettings) {
16039                mSettings.writeLPr();
16040            }
16041        }
16042        return true;
16043    }
16044
16045    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16046            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16047            PackageRemovedInfo outInfo, boolean writeSettings,
16048            PackageParser.Package replacingPackage) {
16049        synchronized (mPackages) {
16050            if (outInfo != null) {
16051                outInfo.uid = ps.appId;
16052            }
16053
16054            if (outInfo != null && outInfo.removedChildPackages != null) {
16055                final int childCount = (ps.childPackageNames != null)
16056                        ? ps.childPackageNames.size() : 0;
16057                for (int i = 0; i < childCount; i++) {
16058                    String childPackageName = ps.childPackageNames.get(i);
16059                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16060                    if (childPs == null) {
16061                        return false;
16062                    }
16063                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16064                            childPackageName);
16065                    if (childInfo != null) {
16066                        childInfo.uid = childPs.appId;
16067                    }
16068                }
16069            }
16070        }
16071
16072        // Delete package data from internal structures and also remove data if flag is set
16073        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16074
16075        // Delete the child packages data
16076        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16077        for (int i = 0; i < childCount; i++) {
16078            PackageSetting childPs;
16079            synchronized (mPackages) {
16080                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16081            }
16082            if (childPs != null) {
16083                PackageRemovedInfo childOutInfo = (outInfo != null
16084                        && outInfo.removedChildPackages != null)
16085                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16086                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16087                        && (replacingPackage != null
16088                        && !replacingPackage.hasChildPackage(childPs.name))
16089                        ? flags & ~DELETE_KEEP_DATA : flags;
16090                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16091                        deleteFlags, writeSettings);
16092            }
16093        }
16094
16095        // Delete application code and resources only for parent packages
16096        if (ps.parentPackageName == null) {
16097            if (deleteCodeAndResources && (outInfo != null)) {
16098                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16099                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16100                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16101            }
16102        }
16103
16104        return true;
16105    }
16106
16107    @Override
16108    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16109            int userId) {
16110        mContext.enforceCallingOrSelfPermission(
16111                android.Manifest.permission.DELETE_PACKAGES, null);
16112        synchronized (mPackages) {
16113            PackageSetting ps = mSettings.mPackages.get(packageName);
16114            if (ps == null) {
16115                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16116                return false;
16117            }
16118            if (!ps.getInstalled(userId)) {
16119                // Can't block uninstall for an app that is not installed or enabled.
16120                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16121                return false;
16122            }
16123            ps.setBlockUninstall(blockUninstall, userId);
16124            mSettings.writePackageRestrictionsLPr(userId);
16125        }
16126        return true;
16127    }
16128
16129    @Override
16130    public boolean getBlockUninstallForUser(String packageName, int userId) {
16131        synchronized (mPackages) {
16132            PackageSetting ps = mSettings.mPackages.get(packageName);
16133            if (ps == null) {
16134                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16135                return false;
16136            }
16137            return ps.getBlockUninstall(userId);
16138        }
16139    }
16140
16141    @Override
16142    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16143        int callingUid = Binder.getCallingUid();
16144        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16145            throw new SecurityException(
16146                    "setRequiredForSystemUser can only be run by the system or root");
16147        }
16148        synchronized (mPackages) {
16149            PackageSetting ps = mSettings.mPackages.get(packageName);
16150            if (ps == null) {
16151                Log.w(TAG, "Package doesn't exist: " + packageName);
16152                return false;
16153            }
16154            if (systemUserApp) {
16155                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16156            } else {
16157                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16158            }
16159            mSettings.writeLPr();
16160        }
16161        return true;
16162    }
16163
16164    /*
16165     * This method handles package deletion in general
16166     */
16167    private boolean deletePackageLIF(String packageName, UserHandle user,
16168            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16169            PackageRemovedInfo outInfo, boolean writeSettings,
16170            PackageParser.Package replacingPackage) {
16171        if (packageName == null) {
16172            Slog.w(TAG, "Attempt to delete null packageName.");
16173            return false;
16174        }
16175
16176        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16177
16178        PackageSetting ps;
16179
16180        synchronized (mPackages) {
16181            ps = mSettings.mPackages.get(packageName);
16182            if (ps == null) {
16183                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16184                return false;
16185            }
16186
16187            if (ps.parentPackageName != null && (!isSystemApp(ps)
16188                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16189                if (DEBUG_REMOVE) {
16190                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16191                            + ((user == null) ? UserHandle.USER_ALL : user));
16192                }
16193                final int removedUserId = (user != null) ? user.getIdentifier()
16194                        : UserHandle.USER_ALL;
16195                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16196                    return false;
16197                }
16198                markPackageUninstalledForUserLPw(ps, user);
16199                scheduleWritePackageRestrictionsLocked(user);
16200                return true;
16201            }
16202        }
16203
16204        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16205                && user.getIdentifier() != UserHandle.USER_ALL)) {
16206            // The caller is asking that the package only be deleted for a single
16207            // user.  To do this, we just mark its uninstalled state and delete
16208            // its data. If this is a system app, we only allow this to happen if
16209            // they have set the special DELETE_SYSTEM_APP which requests different
16210            // semantics than normal for uninstalling system apps.
16211            markPackageUninstalledForUserLPw(ps, user);
16212
16213            if (!isSystemApp(ps)) {
16214                // Do not uninstall the APK if an app should be cached
16215                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16216                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16217                    // Other user still have this package installed, so all
16218                    // we need to do is clear this user's data and save that
16219                    // it is uninstalled.
16220                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16221                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16222                        return false;
16223                    }
16224                    scheduleWritePackageRestrictionsLocked(user);
16225                    return true;
16226                } else {
16227                    // We need to set it back to 'installed' so the uninstall
16228                    // broadcasts will be sent correctly.
16229                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16230                    ps.setInstalled(true, user.getIdentifier());
16231                }
16232            } else {
16233                // This is a system app, so we assume that the
16234                // other users still have this package installed, so all
16235                // we need to do is clear this user's data and save that
16236                // it is uninstalled.
16237                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16238                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16239                    return false;
16240                }
16241                scheduleWritePackageRestrictionsLocked(user);
16242                return true;
16243            }
16244        }
16245
16246        // If we are deleting a composite package for all users, keep track
16247        // of result for each child.
16248        if (ps.childPackageNames != null && outInfo != null) {
16249            synchronized (mPackages) {
16250                final int childCount = ps.childPackageNames.size();
16251                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16252                for (int i = 0; i < childCount; i++) {
16253                    String childPackageName = ps.childPackageNames.get(i);
16254                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16255                    childInfo.removedPackage = childPackageName;
16256                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16257                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16258                    if (childPs != null) {
16259                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16260                    }
16261                }
16262            }
16263        }
16264
16265        boolean ret = false;
16266        if (isSystemApp(ps)) {
16267            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16268            // When an updated system application is deleted we delete the existing resources
16269            // as well and fall back to existing code in system partition
16270            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16271        } else {
16272            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16273            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16274                    outInfo, writeSettings, replacingPackage);
16275        }
16276
16277        // Take a note whether we deleted the package for all users
16278        if (outInfo != null) {
16279            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16280            if (outInfo.removedChildPackages != null) {
16281                synchronized (mPackages) {
16282                    final int childCount = outInfo.removedChildPackages.size();
16283                    for (int i = 0; i < childCount; i++) {
16284                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16285                        if (childInfo != null) {
16286                            childInfo.removedForAllUsers = mPackages.get(
16287                                    childInfo.removedPackage) == null;
16288                        }
16289                    }
16290                }
16291            }
16292            // If we uninstalled an update to a system app there may be some
16293            // child packages that appeared as they are declared in the system
16294            // app but were not declared in the update.
16295            if (isSystemApp(ps)) {
16296                synchronized (mPackages) {
16297                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16298                    final int childCount = (updatedPs.childPackageNames != null)
16299                            ? updatedPs.childPackageNames.size() : 0;
16300                    for (int i = 0; i < childCount; i++) {
16301                        String childPackageName = updatedPs.childPackageNames.get(i);
16302                        if (outInfo.removedChildPackages == null
16303                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16304                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16305                            if (childPs == null) {
16306                                continue;
16307                            }
16308                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16309                            installRes.name = childPackageName;
16310                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16311                            installRes.pkg = mPackages.get(childPackageName);
16312                            installRes.uid = childPs.pkg.applicationInfo.uid;
16313                            if (outInfo.appearedChildPackages == null) {
16314                                outInfo.appearedChildPackages = new ArrayMap<>();
16315                            }
16316                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16317                        }
16318                    }
16319                }
16320            }
16321        }
16322
16323        return ret;
16324    }
16325
16326    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16327        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16328                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16329        for (int nextUserId : userIds) {
16330            if (DEBUG_REMOVE) {
16331                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16332            }
16333            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16334                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16335                    false /*hidden*/, false /*suspended*/, null, null, null,
16336                    false /*blockUninstall*/,
16337                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16338        }
16339    }
16340
16341    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16342            PackageRemovedInfo outInfo) {
16343        final PackageParser.Package pkg;
16344        synchronized (mPackages) {
16345            pkg = mPackages.get(ps.name);
16346        }
16347
16348        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16349                : new int[] {userId};
16350        for (int nextUserId : userIds) {
16351            if (DEBUG_REMOVE) {
16352                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16353                        + nextUserId);
16354            }
16355
16356            destroyAppDataLIF(pkg, userId,
16357                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16358            destroyAppProfilesLIF(pkg, userId);
16359            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16360            schedulePackageCleaning(ps.name, nextUserId, false);
16361            synchronized (mPackages) {
16362                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16363                    scheduleWritePackageRestrictionsLocked(nextUserId);
16364                }
16365                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16366            }
16367        }
16368
16369        if (outInfo != null) {
16370            outInfo.removedPackage = ps.name;
16371            outInfo.removedAppId = ps.appId;
16372            outInfo.removedUsers = userIds;
16373        }
16374
16375        return true;
16376    }
16377
16378    private final class ClearStorageConnection implements ServiceConnection {
16379        IMediaContainerService mContainerService;
16380
16381        @Override
16382        public void onServiceConnected(ComponentName name, IBinder service) {
16383            synchronized (this) {
16384                mContainerService = IMediaContainerService.Stub.asInterface(service);
16385                notifyAll();
16386            }
16387        }
16388
16389        @Override
16390        public void onServiceDisconnected(ComponentName name) {
16391        }
16392    }
16393
16394    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16395        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16396
16397        final boolean mounted;
16398        if (Environment.isExternalStorageEmulated()) {
16399            mounted = true;
16400        } else {
16401            final String status = Environment.getExternalStorageState();
16402
16403            mounted = status.equals(Environment.MEDIA_MOUNTED)
16404                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16405        }
16406
16407        if (!mounted) {
16408            return;
16409        }
16410
16411        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16412        int[] users;
16413        if (userId == UserHandle.USER_ALL) {
16414            users = sUserManager.getUserIds();
16415        } else {
16416            users = new int[] { userId };
16417        }
16418        final ClearStorageConnection conn = new ClearStorageConnection();
16419        if (mContext.bindServiceAsUser(
16420                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16421            try {
16422                for (int curUser : users) {
16423                    long timeout = SystemClock.uptimeMillis() + 5000;
16424                    synchronized (conn) {
16425                        long now;
16426                        while (conn.mContainerService == null &&
16427                                (now = SystemClock.uptimeMillis()) < timeout) {
16428                            try {
16429                                conn.wait(timeout - now);
16430                            } catch (InterruptedException e) {
16431                            }
16432                        }
16433                    }
16434                    if (conn.mContainerService == null) {
16435                        return;
16436                    }
16437
16438                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16439                    clearDirectory(conn.mContainerService,
16440                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16441                    if (allData) {
16442                        clearDirectory(conn.mContainerService,
16443                                userEnv.buildExternalStorageAppDataDirs(packageName));
16444                        clearDirectory(conn.mContainerService,
16445                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16446                    }
16447                }
16448            } finally {
16449                mContext.unbindService(conn);
16450            }
16451        }
16452    }
16453
16454    @Override
16455    public void clearApplicationProfileData(String packageName) {
16456        enforceSystemOrRoot("Only the system can clear all profile data");
16457
16458        final PackageParser.Package pkg;
16459        synchronized (mPackages) {
16460            pkg = mPackages.get(packageName);
16461        }
16462
16463        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16464            synchronized (mInstallLock) {
16465                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16466                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16467                        true /* removeBaseMarker */);
16468            }
16469        }
16470    }
16471
16472    @Override
16473    public void clearApplicationUserData(final String packageName,
16474            final IPackageDataObserver observer, final int userId) {
16475        mContext.enforceCallingOrSelfPermission(
16476                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16477
16478        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16479                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16480
16481        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16482            throw new SecurityException("Cannot clear data for a protected package: "
16483                    + packageName);
16484        }
16485        // Queue up an async operation since the package deletion may take a little while.
16486        mHandler.post(new Runnable() {
16487            public void run() {
16488                mHandler.removeCallbacks(this);
16489                final boolean succeeded;
16490                try (PackageFreezer freezer = freezePackage(packageName,
16491                        "clearApplicationUserData")) {
16492                    synchronized (mInstallLock) {
16493                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16494                    }
16495                    clearExternalStorageDataSync(packageName, userId, true);
16496                }
16497                if (succeeded) {
16498                    // invoke DeviceStorageMonitor's update method to clear any notifications
16499                    DeviceStorageMonitorInternal dsm = LocalServices
16500                            .getService(DeviceStorageMonitorInternal.class);
16501                    if (dsm != null) {
16502                        dsm.checkMemory();
16503                    }
16504                }
16505                if(observer != null) {
16506                    try {
16507                        observer.onRemoveCompleted(packageName, succeeded);
16508                    } catch (RemoteException e) {
16509                        Log.i(TAG, "Observer no longer exists.");
16510                    }
16511                } //end if observer
16512            } //end run
16513        });
16514    }
16515
16516    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16517        if (packageName == null) {
16518            Slog.w(TAG, "Attempt to delete null packageName.");
16519            return false;
16520        }
16521
16522        // Try finding details about the requested package
16523        PackageParser.Package pkg;
16524        synchronized (mPackages) {
16525            pkg = mPackages.get(packageName);
16526            if (pkg == null) {
16527                final PackageSetting ps = mSettings.mPackages.get(packageName);
16528                if (ps != null) {
16529                    pkg = ps.pkg;
16530                }
16531            }
16532
16533            if (pkg == null) {
16534                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16535                return false;
16536            }
16537
16538            PackageSetting ps = (PackageSetting) pkg.mExtras;
16539            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16540        }
16541
16542        clearAppDataLIF(pkg, userId,
16543                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16544
16545        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16546        removeKeystoreDataIfNeeded(userId, appId);
16547
16548        UserManagerInternal umInternal = getUserManagerInternal();
16549        final int flags;
16550        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16551            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16552        } else if (umInternal.isUserRunning(userId)) {
16553            flags = StorageManager.FLAG_STORAGE_DE;
16554        } else {
16555            flags = 0;
16556        }
16557        prepareAppDataContentsLIF(pkg, userId, flags);
16558
16559        return true;
16560    }
16561
16562    /**
16563     * Reverts user permission state changes (permissions and flags) in
16564     * all packages for a given user.
16565     *
16566     * @param userId The device user for which to do a reset.
16567     */
16568    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16569        final int packageCount = mPackages.size();
16570        for (int i = 0; i < packageCount; i++) {
16571            PackageParser.Package pkg = mPackages.valueAt(i);
16572            PackageSetting ps = (PackageSetting) pkg.mExtras;
16573            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16574        }
16575    }
16576
16577    private void resetNetworkPolicies(int userId) {
16578        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16579    }
16580
16581    /**
16582     * Reverts user permission state changes (permissions and flags).
16583     *
16584     * @param ps The package for which to reset.
16585     * @param userId The device user for which to do a reset.
16586     */
16587    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16588            final PackageSetting ps, final int userId) {
16589        if (ps.pkg == null) {
16590            return;
16591        }
16592
16593        // These are flags that can change base on user actions.
16594        final int userSettableMask = FLAG_PERMISSION_USER_SET
16595                | FLAG_PERMISSION_USER_FIXED
16596                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16597                | FLAG_PERMISSION_REVIEW_REQUIRED;
16598
16599        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16600                | FLAG_PERMISSION_POLICY_FIXED;
16601
16602        boolean writeInstallPermissions = false;
16603        boolean writeRuntimePermissions = false;
16604
16605        final int permissionCount = ps.pkg.requestedPermissions.size();
16606        for (int i = 0; i < permissionCount; i++) {
16607            String permission = ps.pkg.requestedPermissions.get(i);
16608
16609            BasePermission bp = mSettings.mPermissions.get(permission);
16610            if (bp == null) {
16611                continue;
16612            }
16613
16614            // If shared user we just reset the state to which only this app contributed.
16615            if (ps.sharedUser != null) {
16616                boolean used = false;
16617                final int packageCount = ps.sharedUser.packages.size();
16618                for (int j = 0; j < packageCount; j++) {
16619                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16620                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16621                            && pkg.pkg.requestedPermissions.contains(permission)) {
16622                        used = true;
16623                        break;
16624                    }
16625                }
16626                if (used) {
16627                    continue;
16628                }
16629            }
16630
16631            PermissionsState permissionsState = ps.getPermissionsState();
16632
16633            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16634
16635            // Always clear the user settable flags.
16636            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16637                    bp.name) != null;
16638            // If permission review is enabled and this is a legacy app, mark the
16639            // permission as requiring a review as this is the initial state.
16640            int flags = 0;
16641            if (Build.PERMISSIONS_REVIEW_REQUIRED
16642                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16643                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16644            }
16645            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16646                if (hasInstallState) {
16647                    writeInstallPermissions = true;
16648                } else {
16649                    writeRuntimePermissions = true;
16650                }
16651            }
16652
16653            // Below is only runtime permission handling.
16654            if (!bp.isRuntime()) {
16655                continue;
16656            }
16657
16658            // Never clobber system or policy.
16659            if ((oldFlags & policyOrSystemFlags) != 0) {
16660                continue;
16661            }
16662
16663            // If this permission was granted by default, make sure it is.
16664            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16665                if (permissionsState.grantRuntimePermission(bp, userId)
16666                        != PERMISSION_OPERATION_FAILURE) {
16667                    writeRuntimePermissions = true;
16668                }
16669            // If permission review is enabled the permissions for a legacy apps
16670            // are represented as constantly granted runtime ones, so don't revoke.
16671            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16672                // Otherwise, reset the permission.
16673                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16674                switch (revokeResult) {
16675                    case PERMISSION_OPERATION_SUCCESS:
16676                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16677                        writeRuntimePermissions = true;
16678                        final int appId = ps.appId;
16679                        mHandler.post(new Runnable() {
16680                            @Override
16681                            public void run() {
16682                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16683                            }
16684                        });
16685                    } break;
16686                }
16687            }
16688        }
16689
16690        // Synchronously write as we are taking permissions away.
16691        if (writeRuntimePermissions) {
16692            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16693        }
16694
16695        // Synchronously write as we are taking permissions away.
16696        if (writeInstallPermissions) {
16697            mSettings.writeLPr();
16698        }
16699    }
16700
16701    /**
16702     * Remove entries from the keystore daemon. Will only remove it if the
16703     * {@code appId} is valid.
16704     */
16705    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16706        if (appId < 0) {
16707            return;
16708        }
16709
16710        final KeyStore keyStore = KeyStore.getInstance();
16711        if (keyStore != null) {
16712            if (userId == UserHandle.USER_ALL) {
16713                for (final int individual : sUserManager.getUserIds()) {
16714                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16715                }
16716            } else {
16717                keyStore.clearUid(UserHandle.getUid(userId, appId));
16718            }
16719        } else {
16720            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16721        }
16722    }
16723
16724    @Override
16725    public void deleteApplicationCacheFiles(final String packageName,
16726            final IPackageDataObserver observer) {
16727        final int userId = UserHandle.getCallingUserId();
16728        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16729    }
16730
16731    @Override
16732    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16733            final IPackageDataObserver observer) {
16734        mContext.enforceCallingOrSelfPermission(
16735                android.Manifest.permission.DELETE_CACHE_FILES, null);
16736        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16737                /* requireFullPermission= */ true, /* checkShell= */ false,
16738                "delete application cache files");
16739
16740        final PackageParser.Package pkg;
16741        synchronized (mPackages) {
16742            pkg = mPackages.get(packageName);
16743        }
16744
16745        // Queue up an async operation since the package deletion may take a little while.
16746        mHandler.post(new Runnable() {
16747            public void run() {
16748                synchronized (mInstallLock) {
16749                    final int flags = StorageManager.FLAG_STORAGE_DE
16750                            | StorageManager.FLAG_STORAGE_CE;
16751                    // We're only clearing cache files, so we don't care if the
16752                    // app is unfrozen and still able to run
16753                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16754                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16755                }
16756                clearExternalStorageDataSync(packageName, userId, false);
16757                if (observer != null) {
16758                    try {
16759                        observer.onRemoveCompleted(packageName, true);
16760                    } catch (RemoteException e) {
16761                        Log.i(TAG, "Observer no longer exists.");
16762                    }
16763                }
16764            }
16765        });
16766    }
16767
16768    @Override
16769    public void getPackageSizeInfo(final String packageName, int userHandle,
16770            final IPackageStatsObserver observer) {
16771        mContext.enforceCallingOrSelfPermission(
16772                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16773        if (packageName == null) {
16774            throw new IllegalArgumentException("Attempt to get size of null packageName");
16775        }
16776
16777        PackageStats stats = new PackageStats(packageName, userHandle);
16778
16779        /*
16780         * Queue up an async operation since the package measurement may take a
16781         * little while.
16782         */
16783        Message msg = mHandler.obtainMessage(INIT_COPY);
16784        msg.obj = new MeasureParams(stats, observer);
16785        mHandler.sendMessage(msg);
16786    }
16787
16788    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16789        final PackageSetting ps;
16790        synchronized (mPackages) {
16791            ps = mSettings.mPackages.get(packageName);
16792            if (ps == null) {
16793                Slog.w(TAG, "Failed to find settings for " + packageName);
16794                return false;
16795            }
16796        }
16797        try {
16798            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16799                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16800                    ps.getCeDataInode(userId), ps.codePathString, stats);
16801        } catch (InstallerException e) {
16802            Slog.w(TAG, String.valueOf(e));
16803            return false;
16804        }
16805
16806        // For now, ignore code size of packages on system partition
16807        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16808            stats.codeSize = 0;
16809        }
16810
16811        return true;
16812    }
16813
16814    private int getUidTargetSdkVersionLockedLPr(int uid) {
16815        Object obj = mSettings.getUserIdLPr(uid);
16816        if (obj instanceof SharedUserSetting) {
16817            final SharedUserSetting sus = (SharedUserSetting) obj;
16818            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16819            final Iterator<PackageSetting> it = sus.packages.iterator();
16820            while (it.hasNext()) {
16821                final PackageSetting ps = it.next();
16822                if (ps.pkg != null) {
16823                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16824                    if (v < vers) vers = v;
16825                }
16826            }
16827            return vers;
16828        } else if (obj instanceof PackageSetting) {
16829            final PackageSetting ps = (PackageSetting) obj;
16830            if (ps.pkg != null) {
16831                return ps.pkg.applicationInfo.targetSdkVersion;
16832            }
16833        }
16834        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16835    }
16836
16837    @Override
16838    public void addPreferredActivity(IntentFilter filter, int match,
16839            ComponentName[] set, ComponentName activity, int userId) {
16840        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16841                "Adding preferred");
16842    }
16843
16844    private void addPreferredActivityInternal(IntentFilter filter, int match,
16845            ComponentName[] set, ComponentName activity, boolean always, int userId,
16846            String opname) {
16847        // writer
16848        int callingUid = Binder.getCallingUid();
16849        enforceCrossUserPermission(callingUid, userId,
16850                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16851        if (filter.countActions() == 0) {
16852            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16853            return;
16854        }
16855        synchronized (mPackages) {
16856            if (mContext.checkCallingOrSelfPermission(
16857                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16858                    != PackageManager.PERMISSION_GRANTED) {
16859                if (getUidTargetSdkVersionLockedLPr(callingUid)
16860                        < Build.VERSION_CODES.FROYO) {
16861                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16862                            + callingUid);
16863                    return;
16864                }
16865                mContext.enforceCallingOrSelfPermission(
16866                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16867            }
16868
16869            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16870            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16871                    + userId + ":");
16872            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16873            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16874            scheduleWritePackageRestrictionsLocked(userId);
16875        }
16876    }
16877
16878    @Override
16879    public void replacePreferredActivity(IntentFilter filter, int match,
16880            ComponentName[] set, ComponentName activity, int userId) {
16881        if (filter.countActions() != 1) {
16882            throw new IllegalArgumentException(
16883                    "replacePreferredActivity expects filter to have only 1 action.");
16884        }
16885        if (filter.countDataAuthorities() != 0
16886                || filter.countDataPaths() != 0
16887                || filter.countDataSchemes() > 1
16888                || filter.countDataTypes() != 0) {
16889            throw new IllegalArgumentException(
16890                    "replacePreferredActivity expects filter to have no data authorities, " +
16891                    "paths, or types; and at most one scheme.");
16892        }
16893
16894        final int callingUid = Binder.getCallingUid();
16895        enforceCrossUserPermission(callingUid, userId,
16896                true /* requireFullPermission */, false /* checkShell */,
16897                "replace preferred activity");
16898        synchronized (mPackages) {
16899            if (mContext.checkCallingOrSelfPermission(
16900                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16901                    != PackageManager.PERMISSION_GRANTED) {
16902                if (getUidTargetSdkVersionLockedLPr(callingUid)
16903                        < Build.VERSION_CODES.FROYO) {
16904                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16905                            + Binder.getCallingUid());
16906                    return;
16907                }
16908                mContext.enforceCallingOrSelfPermission(
16909                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16910            }
16911
16912            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16913            if (pir != null) {
16914                // Get all of the existing entries that exactly match this filter.
16915                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16916                if (existing != null && existing.size() == 1) {
16917                    PreferredActivity cur = existing.get(0);
16918                    if (DEBUG_PREFERRED) {
16919                        Slog.i(TAG, "Checking replace of preferred:");
16920                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16921                        if (!cur.mPref.mAlways) {
16922                            Slog.i(TAG, "  -- CUR; not mAlways!");
16923                        } else {
16924                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16925                            Slog.i(TAG, "  -- CUR: mSet="
16926                                    + Arrays.toString(cur.mPref.mSetComponents));
16927                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16928                            Slog.i(TAG, "  -- NEW: mMatch="
16929                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16930                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16931                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16932                        }
16933                    }
16934                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16935                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16936                            && cur.mPref.sameSet(set)) {
16937                        // Setting the preferred activity to what it happens to be already
16938                        if (DEBUG_PREFERRED) {
16939                            Slog.i(TAG, "Replacing with same preferred activity "
16940                                    + cur.mPref.mShortComponent + " for user "
16941                                    + userId + ":");
16942                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16943                        }
16944                        return;
16945                    }
16946                }
16947
16948                if (existing != null) {
16949                    if (DEBUG_PREFERRED) {
16950                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16951                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16952                    }
16953                    for (int i = 0; i < existing.size(); i++) {
16954                        PreferredActivity pa = existing.get(i);
16955                        if (DEBUG_PREFERRED) {
16956                            Slog.i(TAG, "Removing existing preferred activity "
16957                                    + pa.mPref.mComponent + ":");
16958                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16959                        }
16960                        pir.removeFilter(pa);
16961                    }
16962                }
16963            }
16964            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16965                    "Replacing preferred");
16966        }
16967    }
16968
16969    @Override
16970    public void clearPackagePreferredActivities(String packageName) {
16971        final int uid = Binder.getCallingUid();
16972        // writer
16973        synchronized (mPackages) {
16974            PackageParser.Package pkg = mPackages.get(packageName);
16975            if (pkg == null || pkg.applicationInfo.uid != uid) {
16976                if (mContext.checkCallingOrSelfPermission(
16977                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16978                        != PackageManager.PERMISSION_GRANTED) {
16979                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16980                            < Build.VERSION_CODES.FROYO) {
16981                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16982                                + Binder.getCallingUid());
16983                        return;
16984                    }
16985                    mContext.enforceCallingOrSelfPermission(
16986                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16987                }
16988            }
16989
16990            int user = UserHandle.getCallingUserId();
16991            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16992                scheduleWritePackageRestrictionsLocked(user);
16993            }
16994        }
16995    }
16996
16997    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16998    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16999        ArrayList<PreferredActivity> removed = null;
17000        boolean changed = false;
17001        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17002            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17003            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17004            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17005                continue;
17006            }
17007            Iterator<PreferredActivity> it = pir.filterIterator();
17008            while (it.hasNext()) {
17009                PreferredActivity pa = it.next();
17010                // Mark entry for removal only if it matches the package name
17011                // and the entry is of type "always".
17012                if (packageName == null ||
17013                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17014                                && pa.mPref.mAlways)) {
17015                    if (removed == null) {
17016                        removed = new ArrayList<PreferredActivity>();
17017                    }
17018                    removed.add(pa);
17019                }
17020            }
17021            if (removed != null) {
17022                for (int j=0; j<removed.size(); j++) {
17023                    PreferredActivity pa = removed.get(j);
17024                    pir.removeFilter(pa);
17025                }
17026                changed = true;
17027            }
17028        }
17029        return changed;
17030    }
17031
17032    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17033    private void clearIntentFilterVerificationsLPw(int userId) {
17034        final int packageCount = mPackages.size();
17035        for (int i = 0; i < packageCount; i++) {
17036            PackageParser.Package pkg = mPackages.valueAt(i);
17037            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17038        }
17039    }
17040
17041    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17042    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17043        if (userId == UserHandle.USER_ALL) {
17044            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17045                    sUserManager.getUserIds())) {
17046                for (int oneUserId : sUserManager.getUserIds()) {
17047                    scheduleWritePackageRestrictionsLocked(oneUserId);
17048                }
17049            }
17050        } else {
17051            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17052                scheduleWritePackageRestrictionsLocked(userId);
17053            }
17054        }
17055    }
17056
17057    void clearDefaultBrowserIfNeeded(String packageName) {
17058        for (int oneUserId : sUserManager.getUserIds()) {
17059            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17060            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17061            if (packageName.equals(defaultBrowserPackageName)) {
17062                setDefaultBrowserPackageName(null, oneUserId);
17063            }
17064        }
17065    }
17066
17067    @Override
17068    public void resetApplicationPreferences(int userId) {
17069        mContext.enforceCallingOrSelfPermission(
17070                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17071        final long identity = Binder.clearCallingIdentity();
17072        // writer
17073        try {
17074            synchronized (mPackages) {
17075                clearPackagePreferredActivitiesLPw(null, userId);
17076                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17077                // TODO: We have to reset the default SMS and Phone. This requires
17078                // significant refactoring to keep all default apps in the package
17079                // manager (cleaner but more work) or have the services provide
17080                // callbacks to the package manager to request a default app reset.
17081                applyFactoryDefaultBrowserLPw(userId);
17082                clearIntentFilterVerificationsLPw(userId);
17083                primeDomainVerificationsLPw(userId);
17084                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17085                scheduleWritePackageRestrictionsLocked(userId);
17086            }
17087            resetNetworkPolicies(userId);
17088        } finally {
17089            Binder.restoreCallingIdentity(identity);
17090        }
17091    }
17092
17093    @Override
17094    public int getPreferredActivities(List<IntentFilter> outFilters,
17095            List<ComponentName> outActivities, String packageName) {
17096
17097        int num = 0;
17098        final int userId = UserHandle.getCallingUserId();
17099        // reader
17100        synchronized (mPackages) {
17101            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17102            if (pir != null) {
17103                final Iterator<PreferredActivity> it = pir.filterIterator();
17104                while (it.hasNext()) {
17105                    final PreferredActivity pa = it.next();
17106                    if (packageName == null
17107                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17108                                    && pa.mPref.mAlways)) {
17109                        if (outFilters != null) {
17110                            outFilters.add(new IntentFilter(pa));
17111                        }
17112                        if (outActivities != null) {
17113                            outActivities.add(pa.mPref.mComponent);
17114                        }
17115                    }
17116                }
17117            }
17118        }
17119
17120        return num;
17121    }
17122
17123    @Override
17124    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17125            int userId) {
17126        int callingUid = Binder.getCallingUid();
17127        if (callingUid != Process.SYSTEM_UID) {
17128            throw new SecurityException(
17129                    "addPersistentPreferredActivity can only be run by the system");
17130        }
17131        if (filter.countActions() == 0) {
17132            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17133            return;
17134        }
17135        synchronized (mPackages) {
17136            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17137                    ":");
17138            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17139            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17140                    new PersistentPreferredActivity(filter, activity));
17141            scheduleWritePackageRestrictionsLocked(userId);
17142        }
17143    }
17144
17145    @Override
17146    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17147        int callingUid = Binder.getCallingUid();
17148        if (callingUid != Process.SYSTEM_UID) {
17149            throw new SecurityException(
17150                    "clearPackagePersistentPreferredActivities can only be run by the system");
17151        }
17152        ArrayList<PersistentPreferredActivity> removed = null;
17153        boolean changed = false;
17154        synchronized (mPackages) {
17155            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17156                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17157                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17158                        .valueAt(i);
17159                if (userId != thisUserId) {
17160                    continue;
17161                }
17162                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17163                while (it.hasNext()) {
17164                    PersistentPreferredActivity ppa = it.next();
17165                    // Mark entry for removal only if it matches the package name.
17166                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17167                        if (removed == null) {
17168                            removed = new ArrayList<PersistentPreferredActivity>();
17169                        }
17170                        removed.add(ppa);
17171                    }
17172                }
17173                if (removed != null) {
17174                    for (int j=0; j<removed.size(); j++) {
17175                        PersistentPreferredActivity ppa = removed.get(j);
17176                        ppir.removeFilter(ppa);
17177                    }
17178                    changed = true;
17179                }
17180            }
17181
17182            if (changed) {
17183                scheduleWritePackageRestrictionsLocked(userId);
17184            }
17185        }
17186    }
17187
17188    /**
17189     * Common machinery for picking apart a restored XML blob and passing
17190     * it to a caller-supplied functor to be applied to the running system.
17191     */
17192    private void restoreFromXml(XmlPullParser parser, int userId,
17193            String expectedStartTag, BlobXmlRestorer functor)
17194            throws IOException, XmlPullParserException {
17195        int type;
17196        while ((type = parser.next()) != XmlPullParser.START_TAG
17197                && type != XmlPullParser.END_DOCUMENT) {
17198        }
17199        if (type != XmlPullParser.START_TAG) {
17200            // oops didn't find a start tag?!
17201            if (DEBUG_BACKUP) {
17202                Slog.e(TAG, "Didn't find start tag during restore");
17203            }
17204            return;
17205        }
17206Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17207        // this is supposed to be TAG_PREFERRED_BACKUP
17208        if (!expectedStartTag.equals(parser.getName())) {
17209            if (DEBUG_BACKUP) {
17210                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17211            }
17212            return;
17213        }
17214
17215        // skip interfering stuff, then we're aligned with the backing implementation
17216        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17217Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17218        functor.apply(parser, userId);
17219    }
17220
17221    private interface BlobXmlRestorer {
17222        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17223    }
17224
17225    /**
17226     * Non-Binder method, support for the backup/restore mechanism: write the
17227     * full set of preferred activities in its canonical XML format.  Returns the
17228     * XML output as a byte array, or null if there is none.
17229     */
17230    @Override
17231    public byte[] getPreferredActivityBackup(int userId) {
17232        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17233            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17234        }
17235
17236        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17237        try {
17238            final XmlSerializer serializer = new FastXmlSerializer();
17239            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17240            serializer.startDocument(null, true);
17241            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17242
17243            synchronized (mPackages) {
17244                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17245            }
17246
17247            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17248            serializer.endDocument();
17249            serializer.flush();
17250        } catch (Exception e) {
17251            if (DEBUG_BACKUP) {
17252                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17253            }
17254            return null;
17255        }
17256
17257        return dataStream.toByteArray();
17258    }
17259
17260    @Override
17261    public void restorePreferredActivities(byte[] backup, int userId) {
17262        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17263            throw new SecurityException("Only the system may call restorePreferredActivities()");
17264        }
17265
17266        try {
17267            final XmlPullParser parser = Xml.newPullParser();
17268            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17269            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17270                    new BlobXmlRestorer() {
17271                        @Override
17272                        public void apply(XmlPullParser parser, int userId)
17273                                throws XmlPullParserException, IOException {
17274                            synchronized (mPackages) {
17275                                mSettings.readPreferredActivitiesLPw(parser, userId);
17276                            }
17277                        }
17278                    } );
17279        } catch (Exception e) {
17280            if (DEBUG_BACKUP) {
17281                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17282            }
17283        }
17284    }
17285
17286    /**
17287     * Non-Binder method, support for the backup/restore mechanism: write the
17288     * default browser (etc) settings in its canonical XML format.  Returns the default
17289     * browser XML representation as a byte array, or null if there is none.
17290     */
17291    @Override
17292    public byte[] getDefaultAppsBackup(int userId) {
17293        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17294            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17295        }
17296
17297        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17298        try {
17299            final XmlSerializer serializer = new FastXmlSerializer();
17300            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17301            serializer.startDocument(null, true);
17302            serializer.startTag(null, TAG_DEFAULT_APPS);
17303
17304            synchronized (mPackages) {
17305                mSettings.writeDefaultAppsLPr(serializer, userId);
17306            }
17307
17308            serializer.endTag(null, TAG_DEFAULT_APPS);
17309            serializer.endDocument();
17310            serializer.flush();
17311        } catch (Exception e) {
17312            if (DEBUG_BACKUP) {
17313                Slog.e(TAG, "Unable to write default apps for backup", e);
17314            }
17315            return null;
17316        }
17317
17318        return dataStream.toByteArray();
17319    }
17320
17321    @Override
17322    public void restoreDefaultApps(byte[] backup, int userId) {
17323        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17324            throw new SecurityException("Only the system may call restoreDefaultApps()");
17325        }
17326
17327        try {
17328            final XmlPullParser parser = Xml.newPullParser();
17329            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17330            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17331                    new BlobXmlRestorer() {
17332                        @Override
17333                        public void apply(XmlPullParser parser, int userId)
17334                                throws XmlPullParserException, IOException {
17335                            synchronized (mPackages) {
17336                                mSettings.readDefaultAppsLPw(parser, userId);
17337                            }
17338                        }
17339                    } );
17340        } catch (Exception e) {
17341            if (DEBUG_BACKUP) {
17342                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17343            }
17344        }
17345    }
17346
17347    @Override
17348    public byte[] getIntentFilterVerificationBackup(int userId) {
17349        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17350            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17351        }
17352
17353        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17354        try {
17355            final XmlSerializer serializer = new FastXmlSerializer();
17356            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17357            serializer.startDocument(null, true);
17358            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17359
17360            synchronized (mPackages) {
17361                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17362            }
17363
17364            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17365            serializer.endDocument();
17366            serializer.flush();
17367        } catch (Exception e) {
17368            if (DEBUG_BACKUP) {
17369                Slog.e(TAG, "Unable to write default apps for backup", e);
17370            }
17371            return null;
17372        }
17373
17374        return dataStream.toByteArray();
17375    }
17376
17377    @Override
17378    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17379        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17380            throw new SecurityException("Only the system may call restorePreferredActivities()");
17381        }
17382
17383        try {
17384            final XmlPullParser parser = Xml.newPullParser();
17385            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17386            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17387                    new BlobXmlRestorer() {
17388                        @Override
17389                        public void apply(XmlPullParser parser, int userId)
17390                                throws XmlPullParserException, IOException {
17391                            synchronized (mPackages) {
17392                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17393                                mSettings.writeLPr();
17394                            }
17395                        }
17396                    } );
17397        } catch (Exception e) {
17398            if (DEBUG_BACKUP) {
17399                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17400            }
17401        }
17402    }
17403
17404    @Override
17405    public byte[] getPermissionGrantBackup(int userId) {
17406        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17407            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17408        }
17409
17410        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17411        try {
17412            final XmlSerializer serializer = new FastXmlSerializer();
17413            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17414            serializer.startDocument(null, true);
17415            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17416
17417            synchronized (mPackages) {
17418                serializeRuntimePermissionGrantsLPr(serializer, userId);
17419            }
17420
17421            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17422            serializer.endDocument();
17423            serializer.flush();
17424        } catch (Exception e) {
17425            if (DEBUG_BACKUP) {
17426                Slog.e(TAG, "Unable to write default apps for backup", e);
17427            }
17428            return null;
17429        }
17430
17431        return dataStream.toByteArray();
17432    }
17433
17434    @Override
17435    public void restorePermissionGrants(byte[] backup, int userId) {
17436        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17437            throw new SecurityException("Only the system may call restorePermissionGrants()");
17438        }
17439
17440        try {
17441            final XmlPullParser parser = Xml.newPullParser();
17442            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17443            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17444                    new BlobXmlRestorer() {
17445                        @Override
17446                        public void apply(XmlPullParser parser, int userId)
17447                                throws XmlPullParserException, IOException {
17448                            synchronized (mPackages) {
17449                                processRestoredPermissionGrantsLPr(parser, userId);
17450                            }
17451                        }
17452                    } );
17453        } catch (Exception e) {
17454            if (DEBUG_BACKUP) {
17455                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17456            }
17457        }
17458    }
17459
17460    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17461            throws IOException {
17462        serializer.startTag(null, TAG_ALL_GRANTS);
17463
17464        final int N = mSettings.mPackages.size();
17465        for (int i = 0; i < N; i++) {
17466            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17467            boolean pkgGrantsKnown = false;
17468
17469            PermissionsState packagePerms = ps.getPermissionsState();
17470
17471            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17472                final int grantFlags = state.getFlags();
17473                // only look at grants that are not system/policy fixed
17474                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17475                    final boolean isGranted = state.isGranted();
17476                    // And only back up the user-twiddled state bits
17477                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17478                        final String packageName = mSettings.mPackages.keyAt(i);
17479                        if (!pkgGrantsKnown) {
17480                            serializer.startTag(null, TAG_GRANT);
17481                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17482                            pkgGrantsKnown = true;
17483                        }
17484
17485                        final boolean userSet =
17486                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17487                        final boolean userFixed =
17488                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17489                        final boolean revoke =
17490                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17491
17492                        serializer.startTag(null, TAG_PERMISSION);
17493                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17494                        if (isGranted) {
17495                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17496                        }
17497                        if (userSet) {
17498                            serializer.attribute(null, ATTR_USER_SET, "true");
17499                        }
17500                        if (userFixed) {
17501                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17502                        }
17503                        if (revoke) {
17504                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17505                        }
17506                        serializer.endTag(null, TAG_PERMISSION);
17507                    }
17508                }
17509            }
17510
17511            if (pkgGrantsKnown) {
17512                serializer.endTag(null, TAG_GRANT);
17513            }
17514        }
17515
17516        serializer.endTag(null, TAG_ALL_GRANTS);
17517    }
17518
17519    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17520            throws XmlPullParserException, IOException {
17521        String pkgName = null;
17522        int outerDepth = parser.getDepth();
17523        int type;
17524        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17525                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17526            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17527                continue;
17528            }
17529
17530            final String tagName = parser.getName();
17531            if (tagName.equals(TAG_GRANT)) {
17532                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17533                if (DEBUG_BACKUP) {
17534                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17535                }
17536            } else if (tagName.equals(TAG_PERMISSION)) {
17537
17538                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17539                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17540
17541                int newFlagSet = 0;
17542                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17543                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17544                }
17545                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17546                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17547                }
17548                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17549                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17550                }
17551                if (DEBUG_BACKUP) {
17552                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17553                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17554                }
17555                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17556                if (ps != null) {
17557                    // Already installed so we apply the grant immediately
17558                    if (DEBUG_BACKUP) {
17559                        Slog.v(TAG, "        + already installed; applying");
17560                    }
17561                    PermissionsState perms = ps.getPermissionsState();
17562                    BasePermission bp = mSettings.mPermissions.get(permName);
17563                    if (bp != null) {
17564                        if (isGranted) {
17565                            perms.grantRuntimePermission(bp, userId);
17566                        }
17567                        if (newFlagSet != 0) {
17568                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17569                        }
17570                    }
17571                } else {
17572                    // Need to wait for post-restore install to apply the grant
17573                    if (DEBUG_BACKUP) {
17574                        Slog.v(TAG, "        - not yet installed; saving for later");
17575                    }
17576                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17577                            isGranted, newFlagSet, userId);
17578                }
17579            } else {
17580                PackageManagerService.reportSettingsProblem(Log.WARN,
17581                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17582                XmlUtils.skipCurrentTag(parser);
17583            }
17584        }
17585
17586        scheduleWriteSettingsLocked();
17587        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17588    }
17589
17590    @Override
17591    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17592            int sourceUserId, int targetUserId, int flags) {
17593        mContext.enforceCallingOrSelfPermission(
17594                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17595        int callingUid = Binder.getCallingUid();
17596        enforceOwnerRights(ownerPackage, callingUid);
17597        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17598        if (intentFilter.countActions() == 0) {
17599            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17600            return;
17601        }
17602        synchronized (mPackages) {
17603            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17604                    ownerPackage, targetUserId, flags);
17605            CrossProfileIntentResolver resolver =
17606                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17607            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17608            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17609            if (existing != null) {
17610                int size = existing.size();
17611                for (int i = 0; i < size; i++) {
17612                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17613                        return;
17614                    }
17615                }
17616            }
17617            resolver.addFilter(newFilter);
17618            scheduleWritePackageRestrictionsLocked(sourceUserId);
17619        }
17620    }
17621
17622    @Override
17623    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17624        mContext.enforceCallingOrSelfPermission(
17625                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17626        int callingUid = Binder.getCallingUid();
17627        enforceOwnerRights(ownerPackage, callingUid);
17628        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17629        synchronized (mPackages) {
17630            CrossProfileIntentResolver resolver =
17631                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17632            ArraySet<CrossProfileIntentFilter> set =
17633                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17634            for (CrossProfileIntentFilter filter : set) {
17635                if (filter.getOwnerPackage().equals(ownerPackage)) {
17636                    resolver.removeFilter(filter);
17637                }
17638            }
17639            scheduleWritePackageRestrictionsLocked(sourceUserId);
17640        }
17641    }
17642
17643    // Enforcing that callingUid is owning pkg on userId
17644    private void enforceOwnerRights(String pkg, int callingUid) {
17645        // The system owns everything.
17646        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17647            return;
17648        }
17649        int callingUserId = UserHandle.getUserId(callingUid);
17650        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17651        if (pi == null) {
17652            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17653                    + callingUserId);
17654        }
17655        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17656            throw new SecurityException("Calling uid " + callingUid
17657                    + " does not own package " + pkg);
17658        }
17659    }
17660
17661    @Override
17662    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17663        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17664    }
17665
17666    private Intent getHomeIntent() {
17667        Intent intent = new Intent(Intent.ACTION_MAIN);
17668        intent.addCategory(Intent.CATEGORY_HOME);
17669        intent.addCategory(Intent.CATEGORY_DEFAULT);
17670        return intent;
17671    }
17672
17673    private IntentFilter getHomeFilter() {
17674        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17675        filter.addCategory(Intent.CATEGORY_HOME);
17676        filter.addCategory(Intent.CATEGORY_DEFAULT);
17677        return filter;
17678    }
17679
17680    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17681            int userId) {
17682        Intent intent  = getHomeIntent();
17683        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17684                PackageManager.GET_META_DATA, userId);
17685        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17686                true, false, false, userId);
17687
17688        allHomeCandidates.clear();
17689        if (list != null) {
17690            for (ResolveInfo ri : list) {
17691                allHomeCandidates.add(ri);
17692            }
17693        }
17694        return (preferred == null || preferred.activityInfo == null)
17695                ? null
17696                : new ComponentName(preferred.activityInfo.packageName,
17697                        preferred.activityInfo.name);
17698    }
17699
17700    @Override
17701    public void setHomeActivity(ComponentName comp, int userId) {
17702        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17703        getHomeActivitiesAsUser(homeActivities, userId);
17704
17705        boolean found = false;
17706
17707        final int size = homeActivities.size();
17708        final ComponentName[] set = new ComponentName[size];
17709        for (int i = 0; i < size; i++) {
17710            final ResolveInfo candidate = homeActivities.get(i);
17711            final ActivityInfo info = candidate.activityInfo;
17712            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17713            set[i] = activityName;
17714            if (!found && activityName.equals(comp)) {
17715                found = true;
17716            }
17717        }
17718        if (!found) {
17719            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17720                    + userId);
17721        }
17722        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17723                set, comp, userId);
17724    }
17725
17726    private @Nullable String getSetupWizardPackageName() {
17727        final Intent intent = new Intent(Intent.ACTION_MAIN);
17728        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17729
17730        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17731                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17732                        | MATCH_DISABLED_COMPONENTS,
17733                UserHandle.myUserId());
17734        if (matches.size() == 1) {
17735            return matches.get(0).getComponentInfo().packageName;
17736        } else {
17737            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17738                    + ": matches=" + matches);
17739            return null;
17740        }
17741    }
17742
17743    @Override
17744    public void setApplicationEnabledSetting(String appPackageName,
17745            int newState, int flags, int userId, String callingPackage) {
17746        if (!sUserManager.exists(userId)) return;
17747        if (callingPackage == null) {
17748            callingPackage = Integer.toString(Binder.getCallingUid());
17749        }
17750        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17751    }
17752
17753    @Override
17754    public void setComponentEnabledSetting(ComponentName componentName,
17755            int newState, int flags, int userId) {
17756        if (!sUserManager.exists(userId)) return;
17757        setEnabledSetting(componentName.getPackageName(),
17758                componentName.getClassName(), newState, flags, userId, null);
17759    }
17760
17761    private void setEnabledSetting(final String packageName, String className, int newState,
17762            final int flags, int userId, String callingPackage) {
17763        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17764              || newState == COMPONENT_ENABLED_STATE_ENABLED
17765              || newState == COMPONENT_ENABLED_STATE_DISABLED
17766              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17767              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17768            throw new IllegalArgumentException("Invalid new component state: "
17769                    + newState);
17770        }
17771        PackageSetting pkgSetting;
17772        final int uid = Binder.getCallingUid();
17773        final int permission;
17774        if (uid == Process.SYSTEM_UID) {
17775            permission = PackageManager.PERMISSION_GRANTED;
17776        } else {
17777            permission = mContext.checkCallingOrSelfPermission(
17778                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17779        }
17780        enforceCrossUserPermission(uid, userId,
17781                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17782        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17783        boolean sendNow = false;
17784        boolean isApp = (className == null);
17785        String componentName = isApp ? packageName : className;
17786        int packageUid = -1;
17787        ArrayList<String> components;
17788
17789        // writer
17790        synchronized (mPackages) {
17791            pkgSetting = mSettings.mPackages.get(packageName);
17792            if (pkgSetting == null) {
17793                if (className == null) {
17794                    throw new IllegalArgumentException("Unknown package: " + packageName);
17795                }
17796                throw new IllegalArgumentException(
17797                        "Unknown component: " + packageName + "/" + className);
17798            }
17799        }
17800
17801        // Limit who can change which apps
17802        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17803            // Don't allow apps that don't have permission to modify other apps
17804            if (!allowedByPermission) {
17805                throw new SecurityException(
17806                        "Permission Denial: attempt to change component state from pid="
17807                        + Binder.getCallingPid()
17808                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17809            }
17810            // Don't allow changing protected packages.
17811            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17812                throw new SecurityException("Cannot disable a protected package: " + packageName);
17813            }
17814        }
17815
17816        synchronized (mPackages) {
17817            if (uid == Process.SHELL_UID) {
17818                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17819                int oldState = pkgSetting.getEnabled(userId);
17820                if (className == null
17821                    &&
17822                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17823                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17824                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17825                    &&
17826                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17827                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17828                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17829                    // ok
17830                } else {
17831                    throw new SecurityException(
17832                            "Shell cannot change component state for " + packageName + "/"
17833                            + className + " to " + newState);
17834                }
17835            }
17836            if (className == null) {
17837                // We're dealing with an application/package level state change
17838                if (pkgSetting.getEnabled(userId) == newState) {
17839                    // Nothing to do
17840                    return;
17841                }
17842                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17843                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17844                    // Don't care about who enables an app.
17845                    callingPackage = null;
17846                }
17847                pkgSetting.setEnabled(newState, userId, callingPackage);
17848                // pkgSetting.pkg.mSetEnabled = newState;
17849            } else {
17850                // We're dealing with a component level state change
17851                // First, verify that this is a valid class name.
17852                PackageParser.Package pkg = pkgSetting.pkg;
17853                if (pkg == null || !pkg.hasComponentClassName(className)) {
17854                    if (pkg != null &&
17855                            pkg.applicationInfo.targetSdkVersion >=
17856                                    Build.VERSION_CODES.JELLY_BEAN) {
17857                        throw new IllegalArgumentException("Component class " + className
17858                                + " does not exist in " + packageName);
17859                    } else {
17860                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17861                                + className + " does not exist in " + packageName);
17862                    }
17863                }
17864                switch (newState) {
17865                case COMPONENT_ENABLED_STATE_ENABLED:
17866                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17867                        return;
17868                    }
17869                    break;
17870                case COMPONENT_ENABLED_STATE_DISABLED:
17871                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17872                        return;
17873                    }
17874                    break;
17875                case COMPONENT_ENABLED_STATE_DEFAULT:
17876                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17877                        return;
17878                    }
17879                    break;
17880                default:
17881                    Slog.e(TAG, "Invalid new component state: " + newState);
17882                    return;
17883                }
17884            }
17885            scheduleWritePackageRestrictionsLocked(userId);
17886            components = mPendingBroadcasts.get(userId, packageName);
17887            final boolean newPackage = components == null;
17888            if (newPackage) {
17889                components = new ArrayList<String>();
17890            }
17891            if (!components.contains(componentName)) {
17892                components.add(componentName);
17893            }
17894            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17895                sendNow = true;
17896                // Purge entry from pending broadcast list if another one exists already
17897                // since we are sending one right away.
17898                mPendingBroadcasts.remove(userId, packageName);
17899            } else {
17900                if (newPackage) {
17901                    mPendingBroadcasts.put(userId, packageName, components);
17902                }
17903                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17904                    // Schedule a message
17905                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17906                }
17907            }
17908        }
17909
17910        long callingId = Binder.clearCallingIdentity();
17911        try {
17912            if (sendNow) {
17913                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17914                sendPackageChangedBroadcast(packageName,
17915                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17916            }
17917        } finally {
17918            Binder.restoreCallingIdentity(callingId);
17919        }
17920    }
17921
17922    @Override
17923    public void flushPackageRestrictionsAsUser(int userId) {
17924        if (!sUserManager.exists(userId)) {
17925            return;
17926        }
17927        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17928                false /* checkShell */, "flushPackageRestrictions");
17929        synchronized (mPackages) {
17930            mSettings.writePackageRestrictionsLPr(userId);
17931            mDirtyUsers.remove(userId);
17932            if (mDirtyUsers.isEmpty()) {
17933                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17934            }
17935        }
17936    }
17937
17938    private void sendPackageChangedBroadcast(String packageName,
17939            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17940        if (DEBUG_INSTALL)
17941            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17942                    + componentNames);
17943        Bundle extras = new Bundle(4);
17944        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17945        String nameList[] = new String[componentNames.size()];
17946        componentNames.toArray(nameList);
17947        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17948        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17949        extras.putInt(Intent.EXTRA_UID, packageUid);
17950        // If this is not reporting a change of the overall package, then only send it
17951        // to registered receivers.  We don't want to launch a swath of apps for every
17952        // little component state change.
17953        final int flags = !componentNames.contains(packageName)
17954                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17955        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17956                new int[] {UserHandle.getUserId(packageUid)});
17957    }
17958
17959    @Override
17960    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17961        if (!sUserManager.exists(userId)) return;
17962        final int uid = Binder.getCallingUid();
17963        final int permission = mContext.checkCallingOrSelfPermission(
17964                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17965        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17966        enforceCrossUserPermission(uid, userId,
17967                true /* requireFullPermission */, true /* checkShell */, "stop package");
17968        // writer
17969        synchronized (mPackages) {
17970            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17971                    allowedByPermission, uid, userId)) {
17972                scheduleWritePackageRestrictionsLocked(userId);
17973            }
17974        }
17975    }
17976
17977    @Override
17978    public String getInstallerPackageName(String packageName) {
17979        // reader
17980        synchronized (mPackages) {
17981            return mSettings.getInstallerPackageNameLPr(packageName);
17982        }
17983    }
17984
17985    public boolean isOrphaned(String packageName) {
17986        // reader
17987        synchronized (mPackages) {
17988            return mSettings.isOrphaned(packageName);
17989        }
17990    }
17991
17992    @Override
17993    public int getApplicationEnabledSetting(String packageName, int userId) {
17994        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17995        int uid = Binder.getCallingUid();
17996        enforceCrossUserPermission(uid, userId,
17997                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17998        // reader
17999        synchronized (mPackages) {
18000            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18001        }
18002    }
18003
18004    @Override
18005    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18006        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18007        int uid = Binder.getCallingUid();
18008        enforceCrossUserPermission(uid, userId,
18009                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18010        // reader
18011        synchronized (mPackages) {
18012            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18013        }
18014    }
18015
18016    @Override
18017    public void enterSafeMode() {
18018        enforceSystemOrRoot("Only the system can request entering safe mode");
18019
18020        if (!mSystemReady) {
18021            mSafeMode = true;
18022        }
18023    }
18024
18025    @Override
18026    public void systemReady() {
18027        mSystemReady = true;
18028
18029        // Read the compatibilty setting when the system is ready.
18030        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18031                mContext.getContentResolver(),
18032                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18033        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18034        if (DEBUG_SETTINGS) {
18035            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18036        }
18037
18038        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18039
18040        synchronized (mPackages) {
18041            // Verify that all of the preferred activity components actually
18042            // exist.  It is possible for applications to be updated and at
18043            // that point remove a previously declared activity component that
18044            // had been set as a preferred activity.  We try to clean this up
18045            // the next time we encounter that preferred activity, but it is
18046            // possible for the user flow to never be able to return to that
18047            // situation so here we do a sanity check to make sure we haven't
18048            // left any junk around.
18049            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18050            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18051                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18052                removed.clear();
18053                for (PreferredActivity pa : pir.filterSet()) {
18054                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18055                        removed.add(pa);
18056                    }
18057                }
18058                if (removed.size() > 0) {
18059                    for (int r=0; r<removed.size(); r++) {
18060                        PreferredActivity pa = removed.get(r);
18061                        Slog.w(TAG, "Removing dangling preferred activity: "
18062                                + pa.mPref.mComponent);
18063                        pir.removeFilter(pa);
18064                    }
18065                    mSettings.writePackageRestrictionsLPr(
18066                            mSettings.mPreferredActivities.keyAt(i));
18067                }
18068            }
18069
18070            for (int userId : UserManagerService.getInstance().getUserIds()) {
18071                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18072                    grantPermissionsUserIds = ArrayUtils.appendInt(
18073                            grantPermissionsUserIds, userId);
18074                }
18075            }
18076        }
18077        sUserManager.systemReady();
18078
18079        // If we upgraded grant all default permissions before kicking off.
18080        for (int userId : grantPermissionsUserIds) {
18081            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18082        }
18083
18084        // Kick off any messages waiting for system ready
18085        if (mPostSystemReadyMessages != null) {
18086            for (Message msg : mPostSystemReadyMessages) {
18087                msg.sendToTarget();
18088            }
18089            mPostSystemReadyMessages = null;
18090        }
18091
18092        // Watch for external volumes that come and go over time
18093        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18094        storage.registerListener(mStorageListener);
18095
18096        mInstallerService.systemReady();
18097        mPackageDexOptimizer.systemReady();
18098
18099        MountServiceInternal mountServiceInternal = LocalServices.getService(
18100                MountServiceInternal.class);
18101        mountServiceInternal.addExternalStoragePolicy(
18102                new MountServiceInternal.ExternalStorageMountPolicy() {
18103            @Override
18104            public int getMountMode(int uid, String packageName) {
18105                if (Process.isIsolated(uid)) {
18106                    return Zygote.MOUNT_EXTERNAL_NONE;
18107                }
18108                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18109                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18110                }
18111                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18112                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18113                }
18114                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18115                    return Zygote.MOUNT_EXTERNAL_READ;
18116                }
18117                return Zygote.MOUNT_EXTERNAL_WRITE;
18118            }
18119
18120            @Override
18121            public boolean hasExternalStorage(int uid, String packageName) {
18122                return true;
18123            }
18124        });
18125
18126        // Now that we're mostly running, clean up stale users and apps
18127        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18128        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18129    }
18130
18131    @Override
18132    public boolean isSafeMode() {
18133        return mSafeMode;
18134    }
18135
18136    @Override
18137    public boolean hasSystemUidErrors() {
18138        return mHasSystemUidErrors;
18139    }
18140
18141    static String arrayToString(int[] array) {
18142        StringBuffer buf = new StringBuffer(128);
18143        buf.append('[');
18144        if (array != null) {
18145            for (int i=0; i<array.length; i++) {
18146                if (i > 0) buf.append(", ");
18147                buf.append(array[i]);
18148            }
18149        }
18150        buf.append(']');
18151        return buf.toString();
18152    }
18153
18154    static class DumpState {
18155        public static final int DUMP_LIBS = 1 << 0;
18156        public static final int DUMP_FEATURES = 1 << 1;
18157        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18158        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18159        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18160        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18161        public static final int DUMP_PERMISSIONS = 1 << 6;
18162        public static final int DUMP_PACKAGES = 1 << 7;
18163        public static final int DUMP_SHARED_USERS = 1 << 8;
18164        public static final int DUMP_MESSAGES = 1 << 9;
18165        public static final int DUMP_PROVIDERS = 1 << 10;
18166        public static final int DUMP_VERIFIERS = 1 << 11;
18167        public static final int DUMP_PREFERRED = 1 << 12;
18168        public static final int DUMP_PREFERRED_XML = 1 << 13;
18169        public static final int DUMP_KEYSETS = 1 << 14;
18170        public static final int DUMP_VERSION = 1 << 15;
18171        public static final int DUMP_INSTALLS = 1 << 16;
18172        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18173        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18174        public static final int DUMP_FROZEN = 1 << 19;
18175        public static final int DUMP_DEXOPT = 1 << 20;
18176
18177        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18178
18179        private int mTypes;
18180
18181        private int mOptions;
18182
18183        private boolean mTitlePrinted;
18184
18185        private SharedUserSetting mSharedUser;
18186
18187        public boolean isDumping(int type) {
18188            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18189                return true;
18190            }
18191
18192            return (mTypes & type) != 0;
18193        }
18194
18195        public void setDump(int type) {
18196            mTypes |= type;
18197        }
18198
18199        public boolean isOptionEnabled(int option) {
18200            return (mOptions & option) != 0;
18201        }
18202
18203        public void setOptionEnabled(int option) {
18204            mOptions |= option;
18205        }
18206
18207        public boolean onTitlePrinted() {
18208            final boolean printed = mTitlePrinted;
18209            mTitlePrinted = true;
18210            return printed;
18211        }
18212
18213        public boolean getTitlePrinted() {
18214            return mTitlePrinted;
18215        }
18216
18217        public void setTitlePrinted(boolean enabled) {
18218            mTitlePrinted = enabled;
18219        }
18220
18221        public SharedUserSetting getSharedUser() {
18222            return mSharedUser;
18223        }
18224
18225        public void setSharedUser(SharedUserSetting user) {
18226            mSharedUser = user;
18227        }
18228    }
18229
18230    @Override
18231    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18232            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18233        (new PackageManagerShellCommand(this)).exec(
18234                this, in, out, err, args, resultReceiver);
18235    }
18236
18237    @Override
18238    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18239        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18240                != PackageManager.PERMISSION_GRANTED) {
18241            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18242                    + Binder.getCallingPid()
18243                    + ", uid=" + Binder.getCallingUid()
18244                    + " without permission "
18245                    + android.Manifest.permission.DUMP);
18246            return;
18247        }
18248
18249        DumpState dumpState = new DumpState();
18250        boolean fullPreferred = false;
18251        boolean checkin = false;
18252
18253        String packageName = null;
18254        ArraySet<String> permissionNames = null;
18255
18256        int opti = 0;
18257        while (opti < args.length) {
18258            String opt = args[opti];
18259            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18260                break;
18261            }
18262            opti++;
18263
18264            if ("-a".equals(opt)) {
18265                // Right now we only know how to print all.
18266            } else if ("-h".equals(opt)) {
18267                pw.println("Package manager dump options:");
18268                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18269                pw.println("    --checkin: dump for a checkin");
18270                pw.println("    -f: print details of intent filters");
18271                pw.println("    -h: print this help");
18272                pw.println("  cmd may be one of:");
18273                pw.println("    l[ibraries]: list known shared libraries");
18274                pw.println("    f[eatures]: list device features");
18275                pw.println("    k[eysets]: print known keysets");
18276                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18277                pw.println("    perm[issions]: dump permissions");
18278                pw.println("    permission [name ...]: dump declaration and use of given permission");
18279                pw.println("    pref[erred]: print preferred package settings");
18280                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18281                pw.println("    prov[iders]: dump content providers");
18282                pw.println("    p[ackages]: dump installed packages");
18283                pw.println("    s[hared-users]: dump shared user IDs");
18284                pw.println("    m[essages]: print collected runtime messages");
18285                pw.println("    v[erifiers]: print package verifier info");
18286                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18287                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18288                pw.println("    version: print database version info");
18289                pw.println("    write: write current settings now");
18290                pw.println("    installs: details about install sessions");
18291                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18292                pw.println("    dexopt: dump dexopt state");
18293                pw.println("    <package.name>: info about given package");
18294                return;
18295            } else if ("--checkin".equals(opt)) {
18296                checkin = true;
18297            } else if ("-f".equals(opt)) {
18298                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18299            } else {
18300                pw.println("Unknown argument: " + opt + "; use -h for help");
18301            }
18302        }
18303
18304        // Is the caller requesting to dump a particular piece of data?
18305        if (opti < args.length) {
18306            String cmd = args[opti];
18307            opti++;
18308            // Is this a package name?
18309            if ("android".equals(cmd) || cmd.contains(".")) {
18310                packageName = cmd;
18311                // When dumping a single package, we always dump all of its
18312                // filter information since the amount of data will be reasonable.
18313                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18314            } else if ("check-permission".equals(cmd)) {
18315                if (opti >= args.length) {
18316                    pw.println("Error: check-permission missing permission argument");
18317                    return;
18318                }
18319                String perm = args[opti];
18320                opti++;
18321                if (opti >= args.length) {
18322                    pw.println("Error: check-permission missing package argument");
18323                    return;
18324                }
18325                String pkg = args[opti];
18326                opti++;
18327                int user = UserHandle.getUserId(Binder.getCallingUid());
18328                if (opti < args.length) {
18329                    try {
18330                        user = Integer.parseInt(args[opti]);
18331                    } catch (NumberFormatException e) {
18332                        pw.println("Error: check-permission user argument is not a number: "
18333                                + args[opti]);
18334                        return;
18335                    }
18336                }
18337                pw.println(checkPermission(perm, pkg, user));
18338                return;
18339            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18340                dumpState.setDump(DumpState.DUMP_LIBS);
18341            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18342                dumpState.setDump(DumpState.DUMP_FEATURES);
18343            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18344                if (opti >= args.length) {
18345                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18346                            | DumpState.DUMP_SERVICE_RESOLVERS
18347                            | DumpState.DUMP_RECEIVER_RESOLVERS
18348                            | DumpState.DUMP_CONTENT_RESOLVERS);
18349                } else {
18350                    while (opti < args.length) {
18351                        String name = args[opti];
18352                        if ("a".equals(name) || "activity".equals(name)) {
18353                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18354                        } else if ("s".equals(name) || "service".equals(name)) {
18355                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18356                        } else if ("r".equals(name) || "receiver".equals(name)) {
18357                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18358                        } else if ("c".equals(name) || "content".equals(name)) {
18359                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18360                        } else {
18361                            pw.println("Error: unknown resolver table type: " + name);
18362                            return;
18363                        }
18364                        opti++;
18365                    }
18366                }
18367            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18368                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18369            } else if ("permission".equals(cmd)) {
18370                if (opti >= args.length) {
18371                    pw.println("Error: permission requires permission name");
18372                    return;
18373                }
18374                permissionNames = new ArraySet<>();
18375                while (opti < args.length) {
18376                    permissionNames.add(args[opti]);
18377                    opti++;
18378                }
18379                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18380                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18381            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18382                dumpState.setDump(DumpState.DUMP_PREFERRED);
18383            } else if ("preferred-xml".equals(cmd)) {
18384                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18385                if (opti < args.length && "--full".equals(args[opti])) {
18386                    fullPreferred = true;
18387                    opti++;
18388                }
18389            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18390                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18391            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18392                dumpState.setDump(DumpState.DUMP_PACKAGES);
18393            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18394                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18395            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18396                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18397            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18398                dumpState.setDump(DumpState.DUMP_MESSAGES);
18399            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18400                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18401            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18402                    || "intent-filter-verifiers".equals(cmd)) {
18403                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18404            } else if ("version".equals(cmd)) {
18405                dumpState.setDump(DumpState.DUMP_VERSION);
18406            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18407                dumpState.setDump(DumpState.DUMP_KEYSETS);
18408            } else if ("installs".equals(cmd)) {
18409                dumpState.setDump(DumpState.DUMP_INSTALLS);
18410            } else if ("frozen".equals(cmd)) {
18411                dumpState.setDump(DumpState.DUMP_FROZEN);
18412            } else if ("dexopt".equals(cmd)) {
18413                dumpState.setDump(DumpState.DUMP_DEXOPT);
18414            } else if ("write".equals(cmd)) {
18415                synchronized (mPackages) {
18416                    mSettings.writeLPr();
18417                    pw.println("Settings written.");
18418                    return;
18419                }
18420            }
18421        }
18422
18423        if (checkin) {
18424            pw.println("vers,1");
18425        }
18426
18427        // reader
18428        synchronized (mPackages) {
18429            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18430                if (!checkin) {
18431                    if (dumpState.onTitlePrinted())
18432                        pw.println();
18433                    pw.println("Database versions:");
18434                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18435                }
18436            }
18437
18438            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18439                if (!checkin) {
18440                    if (dumpState.onTitlePrinted())
18441                        pw.println();
18442                    pw.println("Verifiers:");
18443                    pw.print("  Required: ");
18444                    pw.print(mRequiredVerifierPackage);
18445                    pw.print(" (uid=");
18446                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18447                            UserHandle.USER_SYSTEM));
18448                    pw.println(")");
18449                } else if (mRequiredVerifierPackage != null) {
18450                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18451                    pw.print(",");
18452                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18453                            UserHandle.USER_SYSTEM));
18454                }
18455            }
18456
18457            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18458                    packageName == null) {
18459                if (mIntentFilterVerifierComponent != null) {
18460                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18461                    if (!checkin) {
18462                        if (dumpState.onTitlePrinted())
18463                            pw.println();
18464                        pw.println("Intent Filter Verifier:");
18465                        pw.print("  Using: ");
18466                        pw.print(verifierPackageName);
18467                        pw.print(" (uid=");
18468                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18469                                UserHandle.USER_SYSTEM));
18470                        pw.println(")");
18471                    } else if (verifierPackageName != null) {
18472                        pw.print("ifv,"); pw.print(verifierPackageName);
18473                        pw.print(",");
18474                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18475                                UserHandle.USER_SYSTEM));
18476                    }
18477                } else {
18478                    pw.println();
18479                    pw.println("No Intent Filter Verifier available!");
18480                }
18481            }
18482
18483            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18484                boolean printedHeader = false;
18485                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18486                while (it.hasNext()) {
18487                    String name = it.next();
18488                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18489                    if (!checkin) {
18490                        if (!printedHeader) {
18491                            if (dumpState.onTitlePrinted())
18492                                pw.println();
18493                            pw.println("Libraries:");
18494                            printedHeader = true;
18495                        }
18496                        pw.print("  ");
18497                    } else {
18498                        pw.print("lib,");
18499                    }
18500                    pw.print(name);
18501                    if (!checkin) {
18502                        pw.print(" -> ");
18503                    }
18504                    if (ent.path != null) {
18505                        if (!checkin) {
18506                            pw.print("(jar) ");
18507                            pw.print(ent.path);
18508                        } else {
18509                            pw.print(",jar,");
18510                            pw.print(ent.path);
18511                        }
18512                    } else {
18513                        if (!checkin) {
18514                            pw.print("(apk) ");
18515                            pw.print(ent.apk);
18516                        } else {
18517                            pw.print(",apk,");
18518                            pw.print(ent.apk);
18519                        }
18520                    }
18521                    pw.println();
18522                }
18523            }
18524
18525            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18526                if (dumpState.onTitlePrinted())
18527                    pw.println();
18528                if (!checkin) {
18529                    pw.println("Features:");
18530                }
18531
18532                for (FeatureInfo feat : mAvailableFeatures.values()) {
18533                    if (checkin) {
18534                        pw.print("feat,");
18535                        pw.print(feat.name);
18536                        pw.print(",");
18537                        pw.println(feat.version);
18538                    } else {
18539                        pw.print("  ");
18540                        pw.print(feat.name);
18541                        if (feat.version > 0) {
18542                            pw.print(" version=");
18543                            pw.print(feat.version);
18544                        }
18545                        pw.println();
18546                    }
18547                }
18548            }
18549
18550            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18551                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18552                        : "Activity Resolver Table:", "  ", packageName,
18553                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18554                    dumpState.setTitlePrinted(true);
18555                }
18556            }
18557            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18558                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18559                        : "Receiver Resolver Table:", "  ", packageName,
18560                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18561                    dumpState.setTitlePrinted(true);
18562                }
18563            }
18564            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18565                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18566                        : "Service Resolver Table:", "  ", packageName,
18567                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18568                    dumpState.setTitlePrinted(true);
18569                }
18570            }
18571            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18572                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18573                        : "Provider Resolver Table:", "  ", packageName,
18574                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18575                    dumpState.setTitlePrinted(true);
18576                }
18577            }
18578
18579            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18580                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18581                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18582                    int user = mSettings.mPreferredActivities.keyAt(i);
18583                    if (pir.dump(pw,
18584                            dumpState.getTitlePrinted()
18585                                ? "\nPreferred Activities User " + user + ":"
18586                                : "Preferred Activities User " + user + ":", "  ",
18587                            packageName, true, false)) {
18588                        dumpState.setTitlePrinted(true);
18589                    }
18590                }
18591            }
18592
18593            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18594                pw.flush();
18595                FileOutputStream fout = new FileOutputStream(fd);
18596                BufferedOutputStream str = new BufferedOutputStream(fout);
18597                XmlSerializer serializer = new FastXmlSerializer();
18598                try {
18599                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18600                    serializer.startDocument(null, true);
18601                    serializer.setFeature(
18602                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18603                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18604                    serializer.endDocument();
18605                    serializer.flush();
18606                } catch (IllegalArgumentException e) {
18607                    pw.println("Failed writing: " + e);
18608                } catch (IllegalStateException e) {
18609                    pw.println("Failed writing: " + e);
18610                } catch (IOException e) {
18611                    pw.println("Failed writing: " + e);
18612                }
18613            }
18614
18615            if (!checkin
18616                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18617                    && packageName == null) {
18618                pw.println();
18619                int count = mSettings.mPackages.size();
18620                if (count == 0) {
18621                    pw.println("No applications!");
18622                    pw.println();
18623                } else {
18624                    final String prefix = "  ";
18625                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18626                    if (allPackageSettings.size() == 0) {
18627                        pw.println("No domain preferred apps!");
18628                        pw.println();
18629                    } else {
18630                        pw.println("App verification status:");
18631                        pw.println();
18632                        count = 0;
18633                        for (PackageSetting ps : allPackageSettings) {
18634                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18635                            if (ivi == null || ivi.getPackageName() == null) continue;
18636                            pw.println(prefix + "Package: " + ivi.getPackageName());
18637                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18638                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18639                            pw.println();
18640                            count++;
18641                        }
18642                        if (count == 0) {
18643                            pw.println(prefix + "No app verification established.");
18644                            pw.println();
18645                        }
18646                        for (int userId : sUserManager.getUserIds()) {
18647                            pw.println("App linkages for user " + userId + ":");
18648                            pw.println();
18649                            count = 0;
18650                            for (PackageSetting ps : allPackageSettings) {
18651                                final long status = ps.getDomainVerificationStatusForUser(userId);
18652                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18653                                    continue;
18654                                }
18655                                pw.println(prefix + "Package: " + ps.name);
18656                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18657                                String statusStr = IntentFilterVerificationInfo.
18658                                        getStatusStringFromValue(status);
18659                                pw.println(prefix + "Status:  " + statusStr);
18660                                pw.println();
18661                                count++;
18662                            }
18663                            if (count == 0) {
18664                                pw.println(prefix + "No configured app linkages.");
18665                                pw.println();
18666                            }
18667                        }
18668                    }
18669                }
18670            }
18671
18672            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18673                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18674                if (packageName == null && permissionNames == null) {
18675                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18676                        if (iperm == 0) {
18677                            if (dumpState.onTitlePrinted())
18678                                pw.println();
18679                            pw.println("AppOp Permissions:");
18680                        }
18681                        pw.print("  AppOp Permission ");
18682                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18683                        pw.println(":");
18684                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18685                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18686                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18687                        }
18688                    }
18689                }
18690            }
18691
18692            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18693                boolean printedSomething = false;
18694                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18695                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18696                        continue;
18697                    }
18698                    if (!printedSomething) {
18699                        if (dumpState.onTitlePrinted())
18700                            pw.println();
18701                        pw.println("Registered ContentProviders:");
18702                        printedSomething = true;
18703                    }
18704                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18705                    pw.print("    "); pw.println(p.toString());
18706                }
18707                printedSomething = false;
18708                for (Map.Entry<String, PackageParser.Provider> entry :
18709                        mProvidersByAuthority.entrySet()) {
18710                    PackageParser.Provider p = entry.getValue();
18711                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18712                        continue;
18713                    }
18714                    if (!printedSomething) {
18715                        if (dumpState.onTitlePrinted())
18716                            pw.println();
18717                        pw.println("ContentProvider Authorities:");
18718                        printedSomething = true;
18719                    }
18720                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18721                    pw.print("    "); pw.println(p.toString());
18722                    if (p.info != null && p.info.applicationInfo != null) {
18723                        final String appInfo = p.info.applicationInfo.toString();
18724                        pw.print("      applicationInfo="); pw.println(appInfo);
18725                    }
18726                }
18727            }
18728
18729            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18730                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18731            }
18732
18733            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18734                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18735            }
18736
18737            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18738                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18739            }
18740
18741            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18742                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18743            }
18744
18745            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18746                // XXX should handle packageName != null by dumping only install data that
18747                // the given package is involved with.
18748                if (dumpState.onTitlePrinted()) pw.println();
18749                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18750            }
18751
18752            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18753                // XXX should handle packageName != null by dumping only install data that
18754                // the given package is involved with.
18755                if (dumpState.onTitlePrinted()) pw.println();
18756
18757                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18758                ipw.println();
18759                ipw.println("Frozen packages:");
18760                ipw.increaseIndent();
18761                if (mFrozenPackages.size() == 0) {
18762                    ipw.println("(none)");
18763                } else {
18764                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18765                        ipw.println(mFrozenPackages.valueAt(i));
18766                    }
18767                }
18768                ipw.decreaseIndent();
18769            }
18770
18771            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18772                if (dumpState.onTitlePrinted()) pw.println();
18773                dumpDexoptStateLPr(pw, packageName);
18774            }
18775
18776            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18777                if (dumpState.onTitlePrinted()) pw.println();
18778                mSettings.dumpReadMessagesLPr(pw, dumpState);
18779
18780                pw.println();
18781                pw.println("Package warning messages:");
18782                BufferedReader in = null;
18783                String line = null;
18784                try {
18785                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18786                    while ((line = in.readLine()) != null) {
18787                        if (line.contains("ignored: updated version")) continue;
18788                        pw.println(line);
18789                    }
18790                } catch (IOException ignored) {
18791                } finally {
18792                    IoUtils.closeQuietly(in);
18793                }
18794            }
18795
18796            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18797                BufferedReader in = null;
18798                String line = null;
18799                try {
18800                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18801                    while ((line = in.readLine()) != null) {
18802                        if (line.contains("ignored: updated version")) continue;
18803                        pw.print("msg,");
18804                        pw.println(line);
18805                    }
18806                } catch (IOException ignored) {
18807                } finally {
18808                    IoUtils.closeQuietly(in);
18809                }
18810            }
18811        }
18812    }
18813
18814    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18815        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18816        ipw.println();
18817        ipw.println("Dexopt state:");
18818        ipw.increaseIndent();
18819        Collection<PackageParser.Package> packages = null;
18820        if (packageName != null) {
18821            PackageParser.Package targetPackage = mPackages.get(packageName);
18822            if (targetPackage != null) {
18823                packages = Collections.singletonList(targetPackage);
18824            } else {
18825                ipw.println("Unable to find package: " + packageName);
18826                return;
18827            }
18828        } else {
18829            packages = mPackages.values();
18830        }
18831
18832        for (PackageParser.Package pkg : packages) {
18833            ipw.println("[" + pkg.packageName + "]");
18834            ipw.increaseIndent();
18835            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18836            ipw.decreaseIndent();
18837        }
18838    }
18839
18840    private String dumpDomainString(String packageName) {
18841        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18842                .getList();
18843        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18844
18845        ArraySet<String> result = new ArraySet<>();
18846        if (iviList.size() > 0) {
18847            for (IntentFilterVerificationInfo ivi : iviList) {
18848                for (String host : ivi.getDomains()) {
18849                    result.add(host);
18850                }
18851            }
18852        }
18853        if (filters != null && filters.size() > 0) {
18854            for (IntentFilter filter : filters) {
18855                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18856                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18857                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18858                    result.addAll(filter.getHostsList());
18859                }
18860            }
18861        }
18862
18863        StringBuilder sb = new StringBuilder(result.size() * 16);
18864        for (String domain : result) {
18865            if (sb.length() > 0) sb.append(" ");
18866            sb.append(domain);
18867        }
18868        return sb.toString();
18869    }
18870
18871    // ------- apps on sdcard specific code -------
18872    static final boolean DEBUG_SD_INSTALL = false;
18873
18874    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18875
18876    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18877
18878    private boolean mMediaMounted = false;
18879
18880    static String getEncryptKey() {
18881        try {
18882            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18883                    SD_ENCRYPTION_KEYSTORE_NAME);
18884            if (sdEncKey == null) {
18885                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18886                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18887                if (sdEncKey == null) {
18888                    Slog.e(TAG, "Failed to create encryption keys");
18889                    return null;
18890                }
18891            }
18892            return sdEncKey;
18893        } catch (NoSuchAlgorithmException nsae) {
18894            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18895            return null;
18896        } catch (IOException ioe) {
18897            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18898            return null;
18899        }
18900    }
18901
18902    /*
18903     * Update media status on PackageManager.
18904     */
18905    @Override
18906    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18907        int callingUid = Binder.getCallingUid();
18908        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18909            throw new SecurityException("Media status can only be updated by the system");
18910        }
18911        // reader; this apparently protects mMediaMounted, but should probably
18912        // be a different lock in that case.
18913        synchronized (mPackages) {
18914            Log.i(TAG, "Updating external media status from "
18915                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18916                    + (mediaStatus ? "mounted" : "unmounted"));
18917            if (DEBUG_SD_INSTALL)
18918                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18919                        + ", mMediaMounted=" + mMediaMounted);
18920            if (mediaStatus == mMediaMounted) {
18921                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18922                        : 0, -1);
18923                mHandler.sendMessage(msg);
18924                return;
18925            }
18926            mMediaMounted = mediaStatus;
18927        }
18928        // Queue up an async operation since the package installation may take a
18929        // little while.
18930        mHandler.post(new Runnable() {
18931            public void run() {
18932                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18933            }
18934        });
18935    }
18936
18937    /**
18938     * Called by MountService when the initial ASECs to scan are available.
18939     * Should block until all the ASEC containers are finished being scanned.
18940     */
18941    public void scanAvailableAsecs() {
18942        updateExternalMediaStatusInner(true, false, false);
18943    }
18944
18945    /*
18946     * Collect information of applications on external media, map them against
18947     * existing containers and update information based on current mount status.
18948     * Please note that we always have to report status if reportStatus has been
18949     * set to true especially when unloading packages.
18950     */
18951    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18952            boolean externalStorage) {
18953        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18954        int[] uidArr = EmptyArray.INT;
18955
18956        final String[] list = PackageHelper.getSecureContainerList();
18957        if (ArrayUtils.isEmpty(list)) {
18958            Log.i(TAG, "No secure containers found");
18959        } else {
18960            // Process list of secure containers and categorize them
18961            // as active or stale based on their package internal state.
18962
18963            // reader
18964            synchronized (mPackages) {
18965                for (String cid : list) {
18966                    // Leave stages untouched for now; installer service owns them
18967                    if (PackageInstallerService.isStageName(cid)) continue;
18968
18969                    if (DEBUG_SD_INSTALL)
18970                        Log.i(TAG, "Processing container " + cid);
18971                    String pkgName = getAsecPackageName(cid);
18972                    if (pkgName == null) {
18973                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18974                        continue;
18975                    }
18976                    if (DEBUG_SD_INSTALL)
18977                        Log.i(TAG, "Looking for pkg : " + pkgName);
18978
18979                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18980                    if (ps == null) {
18981                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18982                        continue;
18983                    }
18984
18985                    /*
18986                     * Skip packages that are not external if we're unmounting
18987                     * external storage.
18988                     */
18989                    if (externalStorage && !isMounted && !isExternal(ps)) {
18990                        continue;
18991                    }
18992
18993                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18994                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18995                    // The package status is changed only if the code path
18996                    // matches between settings and the container id.
18997                    if (ps.codePathString != null
18998                            && ps.codePathString.startsWith(args.getCodePath())) {
18999                        if (DEBUG_SD_INSTALL) {
19000                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19001                                    + " at code path: " + ps.codePathString);
19002                        }
19003
19004                        // We do have a valid package installed on sdcard
19005                        processCids.put(args, ps.codePathString);
19006                        final int uid = ps.appId;
19007                        if (uid != -1) {
19008                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19009                        }
19010                    } else {
19011                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19012                                + ps.codePathString);
19013                    }
19014                }
19015            }
19016
19017            Arrays.sort(uidArr);
19018        }
19019
19020        // Process packages with valid entries.
19021        if (isMounted) {
19022            if (DEBUG_SD_INSTALL)
19023                Log.i(TAG, "Loading packages");
19024            loadMediaPackages(processCids, uidArr, externalStorage);
19025            startCleaningPackages();
19026            mInstallerService.onSecureContainersAvailable();
19027        } else {
19028            if (DEBUG_SD_INSTALL)
19029                Log.i(TAG, "Unloading packages");
19030            unloadMediaPackages(processCids, uidArr, reportStatus);
19031        }
19032    }
19033
19034    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19035            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19036        final int size = infos.size();
19037        final String[] packageNames = new String[size];
19038        final int[] packageUids = new int[size];
19039        for (int i = 0; i < size; i++) {
19040            final ApplicationInfo info = infos.get(i);
19041            packageNames[i] = info.packageName;
19042            packageUids[i] = info.uid;
19043        }
19044        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19045                finishedReceiver);
19046    }
19047
19048    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19049            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19050        sendResourcesChangedBroadcast(mediaStatus, replacing,
19051                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19052    }
19053
19054    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19055            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19056        int size = pkgList.length;
19057        if (size > 0) {
19058            // Send broadcasts here
19059            Bundle extras = new Bundle();
19060            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19061            if (uidArr != null) {
19062                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19063            }
19064            if (replacing) {
19065                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19066            }
19067            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19068                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19069            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19070        }
19071    }
19072
19073   /*
19074     * Look at potentially valid container ids from processCids If package
19075     * information doesn't match the one on record or package scanning fails,
19076     * the cid is added to list of removeCids. We currently don't delete stale
19077     * containers.
19078     */
19079    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19080            boolean externalStorage) {
19081        ArrayList<String> pkgList = new ArrayList<String>();
19082        Set<AsecInstallArgs> keys = processCids.keySet();
19083
19084        for (AsecInstallArgs args : keys) {
19085            String codePath = processCids.get(args);
19086            if (DEBUG_SD_INSTALL)
19087                Log.i(TAG, "Loading container : " + args.cid);
19088            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19089            try {
19090                // Make sure there are no container errors first.
19091                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19092                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19093                            + " when installing from sdcard");
19094                    continue;
19095                }
19096                // Check code path here.
19097                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19098                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19099                            + " does not match one in settings " + codePath);
19100                    continue;
19101                }
19102                // Parse package
19103                int parseFlags = mDefParseFlags;
19104                if (args.isExternalAsec()) {
19105                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19106                }
19107                if (args.isFwdLocked()) {
19108                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19109                }
19110
19111                synchronized (mInstallLock) {
19112                    PackageParser.Package pkg = null;
19113                    try {
19114                        // Sadly we don't know the package name yet to freeze it
19115                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19116                                SCAN_IGNORE_FROZEN, 0, null);
19117                    } catch (PackageManagerException e) {
19118                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19119                    }
19120                    // Scan the package
19121                    if (pkg != null) {
19122                        /*
19123                         * TODO why is the lock being held? doPostInstall is
19124                         * called in other places without the lock. This needs
19125                         * to be straightened out.
19126                         */
19127                        // writer
19128                        synchronized (mPackages) {
19129                            retCode = PackageManager.INSTALL_SUCCEEDED;
19130                            pkgList.add(pkg.packageName);
19131                            // Post process args
19132                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19133                                    pkg.applicationInfo.uid);
19134                        }
19135                    } else {
19136                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19137                    }
19138                }
19139
19140            } finally {
19141                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19142                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19143                }
19144            }
19145        }
19146        // writer
19147        synchronized (mPackages) {
19148            // If the platform SDK has changed since the last time we booted,
19149            // we need to re-grant app permission to catch any new ones that
19150            // appear. This is really a hack, and means that apps can in some
19151            // cases get permissions that the user didn't initially explicitly
19152            // allow... it would be nice to have some better way to handle
19153            // this situation.
19154            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19155                    : mSettings.getInternalVersion();
19156            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19157                    : StorageManager.UUID_PRIVATE_INTERNAL;
19158
19159            int updateFlags = UPDATE_PERMISSIONS_ALL;
19160            if (ver.sdkVersion != mSdkVersion) {
19161                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19162                        + mSdkVersion + "; regranting permissions for external");
19163                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19164            }
19165            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19166
19167            // Yay, everything is now upgraded
19168            ver.forceCurrent();
19169
19170            // can downgrade to reader
19171            // Persist settings
19172            mSettings.writeLPr();
19173        }
19174        // Send a broadcast to let everyone know we are done processing
19175        if (pkgList.size() > 0) {
19176            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19177        }
19178    }
19179
19180   /*
19181     * Utility method to unload a list of specified containers
19182     */
19183    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19184        // Just unmount all valid containers.
19185        for (AsecInstallArgs arg : cidArgs) {
19186            synchronized (mInstallLock) {
19187                arg.doPostDeleteLI(false);
19188           }
19189       }
19190   }
19191
19192    /*
19193     * Unload packages mounted on external media. This involves deleting package
19194     * data from internal structures, sending broadcasts about disabled packages,
19195     * gc'ing to free up references, unmounting all secure containers
19196     * corresponding to packages on external media, and posting a
19197     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19198     * that we always have to post this message if status has been requested no
19199     * matter what.
19200     */
19201    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19202            final boolean reportStatus) {
19203        if (DEBUG_SD_INSTALL)
19204            Log.i(TAG, "unloading media packages");
19205        ArrayList<String> pkgList = new ArrayList<String>();
19206        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19207        final Set<AsecInstallArgs> keys = processCids.keySet();
19208        for (AsecInstallArgs args : keys) {
19209            String pkgName = args.getPackageName();
19210            if (DEBUG_SD_INSTALL)
19211                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19212            // Delete package internally
19213            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19214            synchronized (mInstallLock) {
19215                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19216                final boolean res;
19217                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19218                        "unloadMediaPackages")) {
19219                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19220                            null);
19221                }
19222                if (res) {
19223                    pkgList.add(pkgName);
19224                } else {
19225                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19226                    failedList.add(args);
19227                }
19228            }
19229        }
19230
19231        // reader
19232        synchronized (mPackages) {
19233            // We didn't update the settings after removing each package;
19234            // write them now for all packages.
19235            mSettings.writeLPr();
19236        }
19237
19238        // We have to absolutely send UPDATED_MEDIA_STATUS only
19239        // after confirming that all the receivers processed the ordered
19240        // broadcast when packages get disabled, force a gc to clean things up.
19241        // and unload all the containers.
19242        if (pkgList.size() > 0) {
19243            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19244                    new IIntentReceiver.Stub() {
19245                public void performReceive(Intent intent, int resultCode, String data,
19246                        Bundle extras, boolean ordered, boolean sticky,
19247                        int sendingUser) throws RemoteException {
19248                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19249                            reportStatus ? 1 : 0, 1, keys);
19250                    mHandler.sendMessage(msg);
19251                }
19252            });
19253        } else {
19254            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19255                    keys);
19256            mHandler.sendMessage(msg);
19257        }
19258    }
19259
19260    private void loadPrivatePackages(final VolumeInfo vol) {
19261        mHandler.post(new Runnable() {
19262            @Override
19263            public void run() {
19264                loadPrivatePackagesInner(vol);
19265            }
19266        });
19267    }
19268
19269    private void loadPrivatePackagesInner(VolumeInfo vol) {
19270        final String volumeUuid = vol.fsUuid;
19271        if (TextUtils.isEmpty(volumeUuid)) {
19272            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19273            return;
19274        }
19275
19276        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19277        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19278        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19279
19280        final VersionInfo ver;
19281        final List<PackageSetting> packages;
19282        synchronized (mPackages) {
19283            ver = mSettings.findOrCreateVersion(volumeUuid);
19284            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19285        }
19286
19287        for (PackageSetting ps : packages) {
19288            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19289            synchronized (mInstallLock) {
19290                final PackageParser.Package pkg;
19291                try {
19292                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19293                    loaded.add(pkg.applicationInfo);
19294
19295                } catch (PackageManagerException e) {
19296                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19297                }
19298
19299                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19300                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19301                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19302                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19303                }
19304            }
19305        }
19306
19307        // Reconcile app data for all started/unlocked users
19308        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19309        final UserManager um = mContext.getSystemService(UserManager.class);
19310        UserManagerInternal umInternal = getUserManagerInternal();
19311        for (UserInfo user : um.getUsers()) {
19312            final int flags;
19313            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19314                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19315            } else if (umInternal.isUserRunning(user.id)) {
19316                flags = StorageManager.FLAG_STORAGE_DE;
19317            } else {
19318                continue;
19319            }
19320
19321            try {
19322                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19323                synchronized (mInstallLock) {
19324                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19325                }
19326            } catch (IllegalStateException e) {
19327                // Device was probably ejected, and we'll process that event momentarily
19328                Slog.w(TAG, "Failed to prepare storage: " + e);
19329            }
19330        }
19331
19332        synchronized (mPackages) {
19333            int updateFlags = UPDATE_PERMISSIONS_ALL;
19334            if (ver.sdkVersion != mSdkVersion) {
19335                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19336                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19337                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19338            }
19339            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19340
19341            // Yay, everything is now upgraded
19342            ver.forceCurrent();
19343
19344            mSettings.writeLPr();
19345        }
19346
19347        for (PackageFreezer freezer : freezers) {
19348            freezer.close();
19349        }
19350
19351        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19352        sendResourcesChangedBroadcast(true, false, loaded, null);
19353    }
19354
19355    private void unloadPrivatePackages(final VolumeInfo vol) {
19356        mHandler.post(new Runnable() {
19357            @Override
19358            public void run() {
19359                unloadPrivatePackagesInner(vol);
19360            }
19361        });
19362    }
19363
19364    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19365        final String volumeUuid = vol.fsUuid;
19366        if (TextUtils.isEmpty(volumeUuid)) {
19367            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19368            return;
19369        }
19370
19371        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19372        synchronized (mInstallLock) {
19373        synchronized (mPackages) {
19374            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19375            for (PackageSetting ps : packages) {
19376                if (ps.pkg == null) continue;
19377
19378                final ApplicationInfo info = ps.pkg.applicationInfo;
19379                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19380                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19381
19382                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19383                        "unloadPrivatePackagesInner")) {
19384                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19385                            false, null)) {
19386                        unloaded.add(info);
19387                    } else {
19388                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19389                    }
19390                }
19391
19392                // Try very hard to release any references to this package
19393                // so we don't risk the system server being killed due to
19394                // open FDs
19395                AttributeCache.instance().removePackage(ps.name);
19396            }
19397
19398            mSettings.writeLPr();
19399        }
19400        }
19401
19402        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19403        sendResourcesChangedBroadcast(false, false, unloaded, null);
19404
19405        // Try very hard to release any references to this path so we don't risk
19406        // the system server being killed due to open FDs
19407        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19408
19409        for (int i = 0; i < 3; i++) {
19410            System.gc();
19411            System.runFinalization();
19412        }
19413    }
19414
19415    /**
19416     * Prepare storage areas for given user on all mounted devices.
19417     */
19418    void prepareUserData(int userId, int userSerial, int flags) {
19419        synchronized (mInstallLock) {
19420            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19421            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19422                final String volumeUuid = vol.getFsUuid();
19423                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19424            }
19425        }
19426    }
19427
19428    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19429            boolean allowRecover) {
19430        // Prepare storage and verify that serial numbers are consistent; if
19431        // there's a mismatch we need to destroy to avoid leaking data
19432        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19433        try {
19434            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19435
19436            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19437                UserManagerService.enforceSerialNumber(
19438                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19439                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19440                    UserManagerService.enforceSerialNumber(
19441                            Environment.getDataSystemDeDirectory(userId), userSerial);
19442                }
19443            }
19444            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19445                UserManagerService.enforceSerialNumber(
19446                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19447                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19448                    UserManagerService.enforceSerialNumber(
19449                            Environment.getDataSystemCeDirectory(userId), userSerial);
19450                }
19451            }
19452
19453            synchronized (mInstallLock) {
19454                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19455            }
19456        } catch (Exception e) {
19457            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19458                    + " because we failed to prepare: " + e);
19459            destroyUserDataLI(volumeUuid, userId,
19460                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19461
19462            if (allowRecover) {
19463                // Try one last time; if we fail again we're really in trouble
19464                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19465            }
19466        }
19467    }
19468
19469    /**
19470     * Destroy storage areas for given user on all mounted devices.
19471     */
19472    void destroyUserData(int userId, int flags) {
19473        synchronized (mInstallLock) {
19474            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19475            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19476                final String volumeUuid = vol.getFsUuid();
19477                destroyUserDataLI(volumeUuid, userId, flags);
19478            }
19479        }
19480    }
19481
19482    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19483        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19484        try {
19485            // Clean up app data, profile data, and media data
19486            mInstaller.destroyUserData(volumeUuid, userId, flags);
19487
19488            // Clean up system data
19489            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19490                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19491                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19492                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19493                }
19494                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19495                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19496                }
19497            }
19498
19499            // Data with special labels is now gone, so finish the job
19500            storage.destroyUserStorage(volumeUuid, userId, flags);
19501
19502        } catch (Exception e) {
19503            logCriticalInfo(Log.WARN,
19504                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19505        }
19506    }
19507
19508    /**
19509     * Examine all users present on given mounted volume, and destroy data
19510     * belonging to users that are no longer valid, or whose user ID has been
19511     * recycled.
19512     */
19513    private void reconcileUsers(String volumeUuid) {
19514        final List<File> files = new ArrayList<>();
19515        Collections.addAll(files, FileUtils
19516                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19517        Collections.addAll(files, FileUtils
19518                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19519        Collections.addAll(files, FileUtils
19520                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19521        Collections.addAll(files, FileUtils
19522                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19523        for (File file : files) {
19524            if (!file.isDirectory()) continue;
19525
19526            final int userId;
19527            final UserInfo info;
19528            try {
19529                userId = Integer.parseInt(file.getName());
19530                info = sUserManager.getUserInfo(userId);
19531            } catch (NumberFormatException e) {
19532                Slog.w(TAG, "Invalid user directory " + file);
19533                continue;
19534            }
19535
19536            boolean destroyUser = false;
19537            if (info == null) {
19538                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19539                        + " because no matching user was found");
19540                destroyUser = true;
19541            } else if (!mOnlyCore) {
19542                try {
19543                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19544                } catch (IOException e) {
19545                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19546                            + " because we failed to enforce serial number: " + e);
19547                    destroyUser = true;
19548                }
19549            }
19550
19551            if (destroyUser) {
19552                synchronized (mInstallLock) {
19553                    destroyUserDataLI(volumeUuid, userId,
19554                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19555                }
19556            }
19557        }
19558    }
19559
19560    private void assertPackageKnown(String volumeUuid, String packageName)
19561            throws PackageManagerException {
19562        synchronized (mPackages) {
19563            final PackageSetting ps = mSettings.mPackages.get(packageName);
19564            if (ps == null) {
19565                throw new PackageManagerException("Package " + packageName + " is unknown");
19566            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19567                throw new PackageManagerException(
19568                        "Package " + packageName + " found on unknown volume " + volumeUuid
19569                                + "; expected volume " + ps.volumeUuid);
19570            }
19571        }
19572    }
19573
19574    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19575            throws PackageManagerException {
19576        synchronized (mPackages) {
19577            final PackageSetting ps = mSettings.mPackages.get(packageName);
19578            if (ps == null) {
19579                throw new PackageManagerException("Package " + packageName + " is unknown");
19580            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19581                throw new PackageManagerException(
19582                        "Package " + packageName + " found on unknown volume " + volumeUuid
19583                                + "; expected volume " + ps.volumeUuid);
19584            } else if (!ps.getInstalled(userId)) {
19585                throw new PackageManagerException(
19586                        "Package " + packageName + " not installed for user " + userId);
19587            }
19588        }
19589    }
19590
19591    /**
19592     * Examine all apps present on given mounted volume, and destroy apps that
19593     * aren't expected, either due to uninstallation or reinstallation on
19594     * another volume.
19595     */
19596    private void reconcileApps(String volumeUuid) {
19597        final File[] files = FileUtils
19598                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19599        for (File file : files) {
19600            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19601                    && !PackageInstallerService.isStageName(file.getName());
19602            if (!isPackage) {
19603                // Ignore entries which are not packages
19604                continue;
19605            }
19606
19607            try {
19608                final PackageLite pkg = PackageParser.parsePackageLite(file,
19609                        PackageParser.PARSE_MUST_BE_APK);
19610                assertPackageKnown(volumeUuid, pkg.packageName);
19611
19612            } catch (PackageParserException | PackageManagerException e) {
19613                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19614                synchronized (mInstallLock) {
19615                    removeCodePathLI(file);
19616                }
19617            }
19618        }
19619    }
19620
19621    /**
19622     * Reconcile all app data for the given user.
19623     * <p>
19624     * Verifies that directories exist and that ownership and labeling is
19625     * correct for all installed apps on all mounted volumes.
19626     */
19627    void reconcileAppsData(int userId, int flags) {
19628        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19629        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19630            final String volumeUuid = vol.getFsUuid();
19631            synchronized (mInstallLock) {
19632                reconcileAppsDataLI(volumeUuid, userId, flags);
19633            }
19634        }
19635    }
19636
19637    /**
19638     * Reconcile all app data on given mounted volume.
19639     * <p>
19640     * Destroys app data that isn't expected, either due to uninstallation or
19641     * reinstallation on another volume.
19642     * <p>
19643     * Verifies that directories exist and that ownership and labeling is
19644     * correct for all installed apps.
19645     */
19646    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19647        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19648                + Integer.toHexString(flags));
19649
19650        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19651        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19652
19653        boolean restoreconNeeded = false;
19654
19655        // First look for stale data that doesn't belong, and check if things
19656        // have changed since we did our last restorecon
19657        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19658            if (StorageManager.isFileEncryptedNativeOrEmulated()
19659                    && !StorageManager.isUserKeyUnlocked(userId)) {
19660                throw new RuntimeException(
19661                        "Yikes, someone asked us to reconcile CE storage while " + userId
19662                                + " was still locked; this would have caused massive data loss!");
19663            }
19664
19665            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19666
19667            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19668            for (File file : files) {
19669                final String packageName = file.getName();
19670                try {
19671                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19672                } catch (PackageManagerException e) {
19673                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19674                    try {
19675                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19676                                StorageManager.FLAG_STORAGE_CE, 0);
19677                    } catch (InstallerException e2) {
19678                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19679                    }
19680                }
19681            }
19682        }
19683        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19684            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19685
19686            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19687            for (File file : files) {
19688                final String packageName = file.getName();
19689                try {
19690                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19691                } catch (PackageManagerException e) {
19692                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19693                    try {
19694                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19695                                StorageManager.FLAG_STORAGE_DE, 0);
19696                    } catch (InstallerException e2) {
19697                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19698                    }
19699                }
19700            }
19701        }
19702
19703        // Ensure that data directories are ready to roll for all packages
19704        // installed for this volume and user
19705        final List<PackageSetting> packages;
19706        synchronized (mPackages) {
19707            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19708        }
19709        int preparedCount = 0;
19710        for (PackageSetting ps : packages) {
19711            final String packageName = ps.name;
19712            if (ps.pkg == null) {
19713                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19714                // TODO: might be due to legacy ASEC apps; we should circle back
19715                // and reconcile again once they're scanned
19716                continue;
19717            }
19718
19719            if (ps.getInstalled(userId)) {
19720                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19721
19722                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19723                    // We may have just shuffled around app data directories, so
19724                    // prepare them one more time
19725                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19726                }
19727
19728                preparedCount++;
19729            }
19730        }
19731
19732        if (restoreconNeeded) {
19733            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19734                SELinuxMMAC.setRestoreconDone(ceDir);
19735            }
19736            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19737                SELinuxMMAC.setRestoreconDone(deDir);
19738            }
19739        }
19740
19741        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19742                + " packages; restoreconNeeded was " + restoreconNeeded);
19743    }
19744
19745    /**
19746     * Prepare app data for the given app just after it was installed or
19747     * upgraded. This method carefully only touches users that it's installed
19748     * for, and it forces a restorecon to handle any seinfo changes.
19749     * <p>
19750     * Verifies that directories exist and that ownership and labeling is
19751     * correct for all installed apps. If there is an ownership mismatch, it
19752     * will try recovering system apps by wiping data; third-party app data is
19753     * left intact.
19754     * <p>
19755     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19756     */
19757    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19758        final PackageSetting ps;
19759        synchronized (mPackages) {
19760            ps = mSettings.mPackages.get(pkg.packageName);
19761            mSettings.writeKernelMappingLPr(ps);
19762        }
19763
19764        final UserManager um = mContext.getSystemService(UserManager.class);
19765        UserManagerInternal umInternal = getUserManagerInternal();
19766        for (UserInfo user : um.getUsers()) {
19767            final int flags;
19768            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19769                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19770            } else if (umInternal.isUserRunning(user.id)) {
19771                flags = StorageManager.FLAG_STORAGE_DE;
19772            } else {
19773                continue;
19774            }
19775
19776            if (ps.getInstalled(user.id)) {
19777                // Whenever an app changes, force a restorecon of its data
19778                // TODO: when user data is locked, mark that we're still dirty
19779                prepareAppDataLIF(pkg, user.id, flags, true);
19780            }
19781        }
19782    }
19783
19784    /**
19785     * Prepare app data for the given app.
19786     * <p>
19787     * Verifies that directories exist and that ownership and labeling is
19788     * correct for all installed apps. If there is an ownership mismatch, this
19789     * will try recovering system apps by wiping data; third-party app data is
19790     * left intact.
19791     */
19792    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19793            boolean restoreconNeeded) {
19794        if (pkg == null) {
19795            Slog.wtf(TAG, "Package was null!", new Throwable());
19796            return;
19797        }
19798        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19799        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19800        for (int i = 0; i < childCount; i++) {
19801            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19802        }
19803    }
19804
19805    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19806            boolean restoreconNeeded) {
19807        if (DEBUG_APP_DATA) {
19808            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19809                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19810        }
19811
19812        final String volumeUuid = pkg.volumeUuid;
19813        final String packageName = pkg.packageName;
19814        final ApplicationInfo app = pkg.applicationInfo;
19815        final int appId = UserHandle.getAppId(app.uid);
19816
19817        Preconditions.checkNotNull(app.seinfo);
19818
19819        try {
19820            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19821                    appId, app.seinfo, app.targetSdkVersion);
19822        } catch (InstallerException e) {
19823            if (app.isSystemApp()) {
19824                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19825                        + ", but trying to recover: " + e);
19826                destroyAppDataLeafLIF(pkg, userId, flags);
19827                try {
19828                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19829                            appId, app.seinfo, app.targetSdkVersion);
19830                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19831                } catch (InstallerException e2) {
19832                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19833                }
19834            } else {
19835                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19836            }
19837        }
19838
19839        if (restoreconNeeded) {
19840            try {
19841                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19842                        app.seinfo);
19843            } catch (InstallerException e) {
19844                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19845            }
19846        }
19847
19848        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19849            try {
19850                // CE storage is unlocked right now, so read out the inode and
19851                // remember for use later when it's locked
19852                // TODO: mark this structure as dirty so we persist it!
19853                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19854                        StorageManager.FLAG_STORAGE_CE);
19855                synchronized (mPackages) {
19856                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19857                    if (ps != null) {
19858                        ps.setCeDataInode(ceDataInode, userId);
19859                    }
19860                }
19861            } catch (InstallerException e) {
19862                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19863            }
19864        }
19865
19866        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19867    }
19868
19869    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19870        if (pkg == null) {
19871            Slog.wtf(TAG, "Package was null!", new Throwable());
19872            return;
19873        }
19874        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19875        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19876        for (int i = 0; i < childCount; i++) {
19877            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19878        }
19879    }
19880
19881    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19882        final String volumeUuid = pkg.volumeUuid;
19883        final String packageName = pkg.packageName;
19884        final ApplicationInfo app = pkg.applicationInfo;
19885
19886        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19887            // Create a native library symlink only if we have native libraries
19888            // and if the native libraries are 32 bit libraries. We do not provide
19889            // this symlink for 64 bit libraries.
19890            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19891                final String nativeLibPath = app.nativeLibraryDir;
19892                try {
19893                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19894                            nativeLibPath, userId);
19895                } catch (InstallerException e) {
19896                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19897                }
19898            }
19899        }
19900    }
19901
19902    /**
19903     * For system apps on non-FBE devices, this method migrates any existing
19904     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19905     * requested by the app.
19906     */
19907    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19908        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19909                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19910            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19911                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19912            try {
19913                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19914                        storageTarget);
19915            } catch (InstallerException e) {
19916                logCriticalInfo(Log.WARN,
19917                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19918            }
19919            return true;
19920        } else {
19921            return false;
19922        }
19923    }
19924
19925    public PackageFreezer freezePackage(String packageName, String killReason) {
19926        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
19927    }
19928
19929    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
19930        return new PackageFreezer(packageName, userId, killReason);
19931    }
19932
19933    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19934            String killReason) {
19935        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
19936    }
19937
19938    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
19939            String killReason) {
19940        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19941            return new PackageFreezer();
19942        } else {
19943            return freezePackage(packageName, userId, killReason);
19944        }
19945    }
19946
19947    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19948            String killReason) {
19949        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
19950    }
19951
19952    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
19953            String killReason) {
19954        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19955            return new PackageFreezer();
19956        } else {
19957            return freezePackage(packageName, userId, killReason);
19958        }
19959    }
19960
19961    /**
19962     * Class that freezes and kills the given package upon creation, and
19963     * unfreezes it upon closing. This is typically used when doing surgery on
19964     * app code/data to prevent the app from running while you're working.
19965     */
19966    private class PackageFreezer implements AutoCloseable {
19967        private final String mPackageName;
19968        private final PackageFreezer[] mChildren;
19969
19970        private final boolean mWeFroze;
19971
19972        private final AtomicBoolean mClosed = new AtomicBoolean();
19973        private final CloseGuard mCloseGuard = CloseGuard.get();
19974
19975        /**
19976         * Create and return a stub freezer that doesn't actually do anything,
19977         * typically used when someone requested
19978         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19979         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19980         */
19981        public PackageFreezer() {
19982            mPackageName = null;
19983            mChildren = null;
19984            mWeFroze = false;
19985            mCloseGuard.open("close");
19986        }
19987
19988        public PackageFreezer(String packageName, int userId, String killReason) {
19989            synchronized (mPackages) {
19990                mPackageName = packageName;
19991                mWeFroze = mFrozenPackages.add(mPackageName);
19992
19993                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19994                if (ps != null) {
19995                    killApplication(ps.name, ps.appId, userId, killReason);
19996                }
19997
19998                final PackageParser.Package p = mPackages.get(packageName);
19999                if (p != null && p.childPackages != null) {
20000                    final int N = p.childPackages.size();
20001                    mChildren = new PackageFreezer[N];
20002                    for (int i = 0; i < N; i++) {
20003                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20004                                userId, killReason);
20005                    }
20006                } else {
20007                    mChildren = null;
20008                }
20009            }
20010            mCloseGuard.open("close");
20011        }
20012
20013        @Override
20014        protected void finalize() throws Throwable {
20015            try {
20016                mCloseGuard.warnIfOpen();
20017                close();
20018            } finally {
20019                super.finalize();
20020            }
20021        }
20022
20023        @Override
20024        public void close() {
20025            mCloseGuard.close();
20026            if (mClosed.compareAndSet(false, true)) {
20027                synchronized (mPackages) {
20028                    if (mWeFroze) {
20029                        mFrozenPackages.remove(mPackageName);
20030                    }
20031
20032                    if (mChildren != null) {
20033                        for (PackageFreezer freezer : mChildren) {
20034                            freezer.close();
20035                        }
20036                    }
20037                }
20038            }
20039        }
20040    }
20041
20042    /**
20043     * Verify that given package is currently frozen.
20044     */
20045    private void checkPackageFrozen(String packageName) {
20046        synchronized (mPackages) {
20047            if (!mFrozenPackages.contains(packageName)) {
20048                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20049            }
20050        }
20051    }
20052
20053    @Override
20054    public int movePackage(final String packageName, final String volumeUuid) {
20055        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20056
20057        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20058        final int moveId = mNextMoveId.getAndIncrement();
20059        mHandler.post(new Runnable() {
20060            @Override
20061            public void run() {
20062                try {
20063                    movePackageInternal(packageName, volumeUuid, moveId, user);
20064                } catch (PackageManagerException e) {
20065                    Slog.w(TAG, "Failed to move " + packageName, e);
20066                    mMoveCallbacks.notifyStatusChanged(moveId,
20067                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20068                }
20069            }
20070        });
20071        return moveId;
20072    }
20073
20074    private void movePackageInternal(final String packageName, final String volumeUuid,
20075            final int moveId, UserHandle user) throws PackageManagerException {
20076        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20077        final PackageManager pm = mContext.getPackageManager();
20078
20079        final boolean currentAsec;
20080        final String currentVolumeUuid;
20081        final File codeFile;
20082        final String installerPackageName;
20083        final String packageAbiOverride;
20084        final int appId;
20085        final String seinfo;
20086        final String label;
20087        final int targetSdkVersion;
20088        final PackageFreezer freezer;
20089        final int[] installedUserIds;
20090
20091        // reader
20092        synchronized (mPackages) {
20093            final PackageParser.Package pkg = mPackages.get(packageName);
20094            final PackageSetting ps = mSettings.mPackages.get(packageName);
20095            if (pkg == null || ps == null) {
20096                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20097            }
20098
20099            if (pkg.applicationInfo.isSystemApp()) {
20100                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20101                        "Cannot move system application");
20102            }
20103
20104            if (pkg.applicationInfo.isExternalAsec()) {
20105                currentAsec = true;
20106                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20107            } else if (pkg.applicationInfo.isForwardLocked()) {
20108                currentAsec = true;
20109                currentVolumeUuid = "forward_locked";
20110            } else {
20111                currentAsec = false;
20112                currentVolumeUuid = ps.volumeUuid;
20113
20114                final File probe = new File(pkg.codePath);
20115                final File probeOat = new File(probe, "oat");
20116                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20117                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20118                            "Move only supported for modern cluster style installs");
20119                }
20120            }
20121
20122            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20123                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20124                        "Package already moved to " + volumeUuid);
20125            }
20126            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20127                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20128                        "Device admin cannot be moved");
20129            }
20130
20131            if (mFrozenPackages.contains(packageName)) {
20132                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20133                        "Failed to move already frozen package");
20134            }
20135
20136            codeFile = new File(pkg.codePath);
20137            installerPackageName = ps.installerPackageName;
20138            packageAbiOverride = ps.cpuAbiOverrideString;
20139            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20140            seinfo = pkg.applicationInfo.seinfo;
20141            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20142            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20143            freezer = freezePackage(packageName, "movePackageInternal");
20144            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20145        }
20146
20147        final Bundle extras = new Bundle();
20148        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20149        extras.putString(Intent.EXTRA_TITLE, label);
20150        mMoveCallbacks.notifyCreated(moveId, extras);
20151
20152        int installFlags;
20153        final boolean moveCompleteApp;
20154        final File measurePath;
20155
20156        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20157            installFlags = INSTALL_INTERNAL;
20158            moveCompleteApp = !currentAsec;
20159            measurePath = Environment.getDataAppDirectory(volumeUuid);
20160        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20161            installFlags = INSTALL_EXTERNAL;
20162            moveCompleteApp = false;
20163            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20164        } else {
20165            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20166            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20167                    || !volume.isMountedWritable()) {
20168                freezer.close();
20169                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20170                        "Move location not mounted private volume");
20171            }
20172
20173            Preconditions.checkState(!currentAsec);
20174
20175            installFlags = INSTALL_INTERNAL;
20176            moveCompleteApp = true;
20177            measurePath = Environment.getDataAppDirectory(volumeUuid);
20178        }
20179
20180        final PackageStats stats = new PackageStats(null, -1);
20181        synchronized (mInstaller) {
20182            for (int userId : installedUserIds) {
20183                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20184                    freezer.close();
20185                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20186                            "Failed to measure package size");
20187                }
20188            }
20189        }
20190
20191        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20192                + stats.dataSize);
20193
20194        final long startFreeBytes = measurePath.getFreeSpace();
20195        final long sizeBytes;
20196        if (moveCompleteApp) {
20197            sizeBytes = stats.codeSize + stats.dataSize;
20198        } else {
20199            sizeBytes = stats.codeSize;
20200        }
20201
20202        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20203            freezer.close();
20204            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20205                    "Not enough free space to move");
20206        }
20207
20208        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20209
20210        final CountDownLatch installedLatch = new CountDownLatch(1);
20211        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20212            @Override
20213            public void onUserActionRequired(Intent intent) throws RemoteException {
20214                throw new IllegalStateException();
20215            }
20216
20217            @Override
20218            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20219                    Bundle extras) throws RemoteException {
20220                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20221                        + PackageManager.installStatusToString(returnCode, msg));
20222
20223                installedLatch.countDown();
20224                freezer.close();
20225
20226                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20227                switch (status) {
20228                    case PackageInstaller.STATUS_SUCCESS:
20229                        mMoveCallbacks.notifyStatusChanged(moveId,
20230                                PackageManager.MOVE_SUCCEEDED);
20231                        break;
20232                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20233                        mMoveCallbacks.notifyStatusChanged(moveId,
20234                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20235                        break;
20236                    default:
20237                        mMoveCallbacks.notifyStatusChanged(moveId,
20238                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20239                        break;
20240                }
20241            }
20242        };
20243
20244        final MoveInfo move;
20245        if (moveCompleteApp) {
20246            // Kick off a thread to report progress estimates
20247            new Thread() {
20248                @Override
20249                public void run() {
20250                    while (true) {
20251                        try {
20252                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20253                                break;
20254                            }
20255                        } catch (InterruptedException ignored) {
20256                        }
20257
20258                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20259                        final int progress = 10 + (int) MathUtils.constrain(
20260                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20261                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20262                    }
20263                }
20264            }.start();
20265
20266            final String dataAppName = codeFile.getName();
20267            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20268                    dataAppName, appId, seinfo, targetSdkVersion);
20269        } else {
20270            move = null;
20271        }
20272
20273        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20274
20275        final Message msg = mHandler.obtainMessage(INIT_COPY);
20276        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20277        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20278                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20279                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20280        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20281        msg.obj = params;
20282
20283        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20284                System.identityHashCode(msg.obj));
20285        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20286                System.identityHashCode(msg.obj));
20287
20288        mHandler.sendMessage(msg);
20289    }
20290
20291    @Override
20292    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20293        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20294
20295        final int realMoveId = mNextMoveId.getAndIncrement();
20296        final Bundle extras = new Bundle();
20297        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20298        mMoveCallbacks.notifyCreated(realMoveId, extras);
20299
20300        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20301            @Override
20302            public void onCreated(int moveId, Bundle extras) {
20303                // Ignored
20304            }
20305
20306            @Override
20307            public void onStatusChanged(int moveId, int status, long estMillis) {
20308                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20309            }
20310        };
20311
20312        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20313        storage.setPrimaryStorageUuid(volumeUuid, callback);
20314        return realMoveId;
20315    }
20316
20317    @Override
20318    public int getMoveStatus(int moveId) {
20319        mContext.enforceCallingOrSelfPermission(
20320                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20321        return mMoveCallbacks.mLastStatus.get(moveId);
20322    }
20323
20324    @Override
20325    public void registerMoveCallback(IPackageMoveObserver callback) {
20326        mContext.enforceCallingOrSelfPermission(
20327                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20328        mMoveCallbacks.register(callback);
20329    }
20330
20331    @Override
20332    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20333        mContext.enforceCallingOrSelfPermission(
20334                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20335        mMoveCallbacks.unregister(callback);
20336    }
20337
20338    @Override
20339    public boolean setInstallLocation(int loc) {
20340        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20341                null);
20342        if (getInstallLocation() == loc) {
20343            return true;
20344        }
20345        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20346                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20347            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20348                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20349            return true;
20350        }
20351        return false;
20352   }
20353
20354    @Override
20355    public int getInstallLocation() {
20356        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20357                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20358                PackageHelper.APP_INSTALL_AUTO);
20359    }
20360
20361    /** Called by UserManagerService */
20362    void cleanUpUser(UserManagerService userManager, int userHandle) {
20363        synchronized (mPackages) {
20364            mDirtyUsers.remove(userHandle);
20365            mUserNeedsBadging.delete(userHandle);
20366            mSettings.removeUserLPw(userHandle);
20367            mPendingBroadcasts.remove(userHandle);
20368            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20369            removeUnusedPackagesLPw(userManager, userHandle);
20370        }
20371    }
20372
20373    /**
20374     * We're removing userHandle and would like to remove any downloaded packages
20375     * that are no longer in use by any other user.
20376     * @param userHandle the user being removed
20377     */
20378    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20379        final boolean DEBUG_CLEAN_APKS = false;
20380        int [] users = userManager.getUserIds();
20381        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20382        while (psit.hasNext()) {
20383            PackageSetting ps = psit.next();
20384            if (ps.pkg == null) {
20385                continue;
20386            }
20387            final String packageName = ps.pkg.packageName;
20388            // Skip over if system app
20389            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20390                continue;
20391            }
20392            if (DEBUG_CLEAN_APKS) {
20393                Slog.i(TAG, "Checking package " + packageName);
20394            }
20395            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20396            if (keep) {
20397                if (DEBUG_CLEAN_APKS) {
20398                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20399                }
20400            } else {
20401                for (int i = 0; i < users.length; i++) {
20402                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20403                        keep = true;
20404                        if (DEBUG_CLEAN_APKS) {
20405                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20406                                    + users[i]);
20407                        }
20408                        break;
20409                    }
20410                }
20411            }
20412            if (!keep) {
20413                if (DEBUG_CLEAN_APKS) {
20414                    Slog.i(TAG, "  Removing package " + packageName);
20415                }
20416                mHandler.post(new Runnable() {
20417                    public void run() {
20418                        deletePackageX(packageName, userHandle, 0);
20419                    } //end run
20420                });
20421            }
20422        }
20423    }
20424
20425    /** Called by UserManagerService */
20426    void createNewUser(int userId) {
20427        synchronized (mInstallLock) {
20428            mSettings.createNewUserLI(this, mInstaller, userId);
20429        }
20430        synchronized (mPackages) {
20431            scheduleWritePackageRestrictionsLocked(userId);
20432            scheduleWritePackageListLocked(userId);
20433            applyFactoryDefaultBrowserLPw(userId);
20434            primeDomainVerificationsLPw(userId);
20435        }
20436    }
20437
20438    void onBeforeUserStartUninitialized(final int userId) {
20439        synchronized (mPackages) {
20440            if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20441                return;
20442            }
20443        }
20444        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20445        // If permission review for legacy apps is required, we represent
20446        // dagerous permissions for such apps as always granted runtime
20447        // permissions to keep per user flag state whether review is needed.
20448        // Hence, if a new user is added we have to propagate dangerous
20449        // permission grants for these legacy apps.
20450        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20451            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20452                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20453        }
20454    }
20455
20456    @Override
20457    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20458        mContext.enforceCallingOrSelfPermission(
20459                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20460                "Only package verification agents can read the verifier device identity");
20461
20462        synchronized (mPackages) {
20463            return mSettings.getVerifierDeviceIdentityLPw();
20464        }
20465    }
20466
20467    @Override
20468    public void setPermissionEnforced(String permission, boolean enforced) {
20469        // TODO: Now that we no longer change GID for storage, this should to away.
20470        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20471                "setPermissionEnforced");
20472        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20473            synchronized (mPackages) {
20474                if (mSettings.mReadExternalStorageEnforced == null
20475                        || mSettings.mReadExternalStorageEnforced != enforced) {
20476                    mSettings.mReadExternalStorageEnforced = enforced;
20477                    mSettings.writeLPr();
20478                }
20479            }
20480            // kill any non-foreground processes so we restart them and
20481            // grant/revoke the GID.
20482            final IActivityManager am = ActivityManagerNative.getDefault();
20483            if (am != null) {
20484                final long token = Binder.clearCallingIdentity();
20485                try {
20486                    am.killProcessesBelowForeground("setPermissionEnforcement");
20487                } catch (RemoteException e) {
20488                } finally {
20489                    Binder.restoreCallingIdentity(token);
20490                }
20491            }
20492        } else {
20493            throw new IllegalArgumentException("No selective enforcement for " + permission);
20494        }
20495    }
20496
20497    @Override
20498    @Deprecated
20499    public boolean isPermissionEnforced(String permission) {
20500        return true;
20501    }
20502
20503    @Override
20504    public boolean isStorageLow() {
20505        final long token = Binder.clearCallingIdentity();
20506        try {
20507            final DeviceStorageMonitorInternal
20508                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20509            if (dsm != null) {
20510                return dsm.isMemoryLow();
20511            } else {
20512                return false;
20513            }
20514        } finally {
20515            Binder.restoreCallingIdentity(token);
20516        }
20517    }
20518
20519    @Override
20520    public IPackageInstaller getPackageInstaller() {
20521        return mInstallerService;
20522    }
20523
20524    private boolean userNeedsBadging(int userId) {
20525        int index = mUserNeedsBadging.indexOfKey(userId);
20526        if (index < 0) {
20527            final UserInfo userInfo;
20528            final long token = Binder.clearCallingIdentity();
20529            try {
20530                userInfo = sUserManager.getUserInfo(userId);
20531            } finally {
20532                Binder.restoreCallingIdentity(token);
20533            }
20534            final boolean b;
20535            if (userInfo != null && userInfo.isManagedProfile()) {
20536                b = true;
20537            } else {
20538                b = false;
20539            }
20540            mUserNeedsBadging.put(userId, b);
20541            return b;
20542        }
20543        return mUserNeedsBadging.valueAt(index);
20544    }
20545
20546    @Override
20547    public KeySet getKeySetByAlias(String packageName, String alias) {
20548        if (packageName == null || alias == null) {
20549            return null;
20550        }
20551        synchronized(mPackages) {
20552            final PackageParser.Package pkg = mPackages.get(packageName);
20553            if (pkg == null) {
20554                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20555                throw new IllegalArgumentException("Unknown package: " + packageName);
20556            }
20557            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20558            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20559        }
20560    }
20561
20562    @Override
20563    public KeySet getSigningKeySet(String packageName) {
20564        if (packageName == null) {
20565            return null;
20566        }
20567        synchronized(mPackages) {
20568            final PackageParser.Package pkg = mPackages.get(packageName);
20569            if (pkg == null) {
20570                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20571                throw new IllegalArgumentException("Unknown package: " + packageName);
20572            }
20573            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20574                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20575                throw new SecurityException("May not access signing KeySet of other apps.");
20576            }
20577            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20578            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20579        }
20580    }
20581
20582    @Override
20583    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20584        if (packageName == null || ks == null) {
20585            return false;
20586        }
20587        synchronized(mPackages) {
20588            final PackageParser.Package pkg = mPackages.get(packageName);
20589            if (pkg == null) {
20590                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20591                throw new IllegalArgumentException("Unknown package: " + packageName);
20592            }
20593            IBinder ksh = ks.getToken();
20594            if (ksh instanceof KeySetHandle) {
20595                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20596                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20597            }
20598            return false;
20599        }
20600    }
20601
20602    @Override
20603    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20604        if (packageName == null || ks == null) {
20605            return false;
20606        }
20607        synchronized(mPackages) {
20608            final PackageParser.Package pkg = mPackages.get(packageName);
20609            if (pkg == null) {
20610                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20611                throw new IllegalArgumentException("Unknown package: " + packageName);
20612            }
20613            IBinder ksh = ks.getToken();
20614            if (ksh instanceof KeySetHandle) {
20615                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20616                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20617            }
20618            return false;
20619        }
20620    }
20621
20622    private void deletePackageIfUnusedLPr(final String packageName) {
20623        PackageSetting ps = mSettings.mPackages.get(packageName);
20624        if (ps == null) {
20625            return;
20626        }
20627        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20628            // TODO Implement atomic delete if package is unused
20629            // It is currently possible that the package will be deleted even if it is installed
20630            // after this method returns.
20631            mHandler.post(new Runnable() {
20632                public void run() {
20633                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20634                }
20635            });
20636        }
20637    }
20638
20639    /**
20640     * Check and throw if the given before/after packages would be considered a
20641     * downgrade.
20642     */
20643    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20644            throws PackageManagerException {
20645        if (after.versionCode < before.mVersionCode) {
20646            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20647                    "Update version code " + after.versionCode + " is older than current "
20648                    + before.mVersionCode);
20649        } else if (after.versionCode == before.mVersionCode) {
20650            if (after.baseRevisionCode < before.baseRevisionCode) {
20651                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20652                        "Update base revision code " + after.baseRevisionCode
20653                        + " is older than current " + before.baseRevisionCode);
20654            }
20655
20656            if (!ArrayUtils.isEmpty(after.splitNames)) {
20657                for (int i = 0; i < after.splitNames.length; i++) {
20658                    final String splitName = after.splitNames[i];
20659                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20660                    if (j != -1) {
20661                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20662                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20663                                    "Update split " + splitName + " revision code "
20664                                    + after.splitRevisionCodes[i] + " is older than current "
20665                                    + before.splitRevisionCodes[j]);
20666                        }
20667                    }
20668                }
20669            }
20670        }
20671    }
20672
20673    private static class MoveCallbacks extends Handler {
20674        private static final int MSG_CREATED = 1;
20675        private static final int MSG_STATUS_CHANGED = 2;
20676
20677        private final RemoteCallbackList<IPackageMoveObserver>
20678                mCallbacks = new RemoteCallbackList<>();
20679
20680        private final SparseIntArray mLastStatus = new SparseIntArray();
20681
20682        public MoveCallbacks(Looper looper) {
20683            super(looper);
20684        }
20685
20686        public void register(IPackageMoveObserver callback) {
20687            mCallbacks.register(callback);
20688        }
20689
20690        public void unregister(IPackageMoveObserver callback) {
20691            mCallbacks.unregister(callback);
20692        }
20693
20694        @Override
20695        public void handleMessage(Message msg) {
20696            final SomeArgs args = (SomeArgs) msg.obj;
20697            final int n = mCallbacks.beginBroadcast();
20698            for (int i = 0; i < n; i++) {
20699                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20700                try {
20701                    invokeCallback(callback, msg.what, args);
20702                } catch (RemoteException ignored) {
20703                }
20704            }
20705            mCallbacks.finishBroadcast();
20706            args.recycle();
20707        }
20708
20709        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20710                throws RemoteException {
20711            switch (what) {
20712                case MSG_CREATED: {
20713                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20714                    break;
20715                }
20716                case MSG_STATUS_CHANGED: {
20717                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20718                    break;
20719                }
20720            }
20721        }
20722
20723        private void notifyCreated(int moveId, Bundle extras) {
20724            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20725
20726            final SomeArgs args = SomeArgs.obtain();
20727            args.argi1 = moveId;
20728            args.arg2 = extras;
20729            obtainMessage(MSG_CREATED, args).sendToTarget();
20730        }
20731
20732        private void notifyStatusChanged(int moveId, int status) {
20733            notifyStatusChanged(moveId, status, -1);
20734        }
20735
20736        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20737            Slog.v(TAG, "Move " + moveId + " status " + status);
20738
20739            final SomeArgs args = SomeArgs.obtain();
20740            args.argi1 = moveId;
20741            args.argi2 = status;
20742            args.arg3 = estMillis;
20743            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20744
20745            synchronized (mLastStatus) {
20746                mLastStatus.put(moveId, status);
20747            }
20748        }
20749    }
20750
20751    private final static class OnPermissionChangeListeners extends Handler {
20752        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20753
20754        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20755                new RemoteCallbackList<>();
20756
20757        public OnPermissionChangeListeners(Looper looper) {
20758            super(looper);
20759        }
20760
20761        @Override
20762        public void handleMessage(Message msg) {
20763            switch (msg.what) {
20764                case MSG_ON_PERMISSIONS_CHANGED: {
20765                    final int uid = msg.arg1;
20766                    handleOnPermissionsChanged(uid);
20767                } break;
20768            }
20769        }
20770
20771        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20772            mPermissionListeners.register(listener);
20773
20774        }
20775
20776        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20777            mPermissionListeners.unregister(listener);
20778        }
20779
20780        public void onPermissionsChanged(int uid) {
20781            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20782                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20783            }
20784        }
20785
20786        private void handleOnPermissionsChanged(int uid) {
20787            final int count = mPermissionListeners.beginBroadcast();
20788            try {
20789                for (int i = 0; i < count; i++) {
20790                    IOnPermissionsChangeListener callback = mPermissionListeners
20791                            .getBroadcastItem(i);
20792                    try {
20793                        callback.onPermissionsChanged(uid);
20794                    } catch (RemoteException e) {
20795                        Log.e(TAG, "Permission listener is dead", e);
20796                    }
20797                }
20798            } finally {
20799                mPermissionListeners.finishBroadcast();
20800            }
20801        }
20802    }
20803
20804    private class PackageManagerInternalImpl extends PackageManagerInternal {
20805        @Override
20806        public void setLocationPackagesProvider(PackagesProvider provider) {
20807            synchronized (mPackages) {
20808                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20809            }
20810        }
20811
20812        @Override
20813        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20814            synchronized (mPackages) {
20815                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20816            }
20817        }
20818
20819        @Override
20820        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20821            synchronized (mPackages) {
20822                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20823            }
20824        }
20825
20826        @Override
20827        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20828            synchronized (mPackages) {
20829                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20830            }
20831        }
20832
20833        @Override
20834        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20835            synchronized (mPackages) {
20836                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20837            }
20838        }
20839
20840        @Override
20841        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20842            synchronized (mPackages) {
20843                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20844            }
20845        }
20846
20847        @Override
20848        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20849            synchronized (mPackages) {
20850                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20851                        packageName, userId);
20852            }
20853        }
20854
20855        @Override
20856        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20857            synchronized (mPackages) {
20858                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20859                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20860                        packageName, userId);
20861            }
20862        }
20863
20864        @Override
20865        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20866            synchronized (mPackages) {
20867                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20868                        packageName, userId);
20869            }
20870        }
20871
20872        @Override
20873        public void setKeepUninstalledPackages(final List<String> packageList) {
20874            Preconditions.checkNotNull(packageList);
20875            List<String> removedFromList = null;
20876            synchronized (mPackages) {
20877                if (mKeepUninstalledPackages != null) {
20878                    final int packagesCount = mKeepUninstalledPackages.size();
20879                    for (int i = 0; i < packagesCount; i++) {
20880                        String oldPackage = mKeepUninstalledPackages.get(i);
20881                        if (packageList != null && packageList.contains(oldPackage)) {
20882                            continue;
20883                        }
20884                        if (removedFromList == null) {
20885                            removedFromList = new ArrayList<>();
20886                        }
20887                        removedFromList.add(oldPackage);
20888                    }
20889                }
20890                mKeepUninstalledPackages = new ArrayList<>(packageList);
20891                if (removedFromList != null) {
20892                    final int removedCount = removedFromList.size();
20893                    for (int i = 0; i < removedCount; i++) {
20894                        deletePackageIfUnusedLPr(removedFromList.get(i));
20895                    }
20896                }
20897            }
20898        }
20899
20900        @Override
20901        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20902            synchronized (mPackages) {
20903                // If we do not support permission review, done.
20904                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20905                    return false;
20906                }
20907
20908                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20909                if (packageSetting == null) {
20910                    return false;
20911                }
20912
20913                // Permission review applies only to apps not supporting the new permission model.
20914                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20915                    return false;
20916                }
20917
20918                // Legacy apps have the permission and get user consent on launch.
20919                PermissionsState permissionsState = packageSetting.getPermissionsState();
20920                return permissionsState.isPermissionReviewRequired(userId);
20921            }
20922        }
20923
20924        @Override
20925        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20926            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20927        }
20928
20929        @Override
20930        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20931                int userId) {
20932            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20933        }
20934
20935        @Override
20936        public void setDeviceAndProfileOwnerPackages(
20937                int deviceOwnerUserId, String deviceOwnerPackage,
20938                SparseArray<String> profileOwnerPackages) {
20939            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20940                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20941        }
20942
20943        @Override
20944        public boolean isPackageDataProtected(int userId, String packageName) {
20945            return mProtectedPackages.isPackageDataProtected(userId, packageName);
20946        }
20947    }
20948
20949    @Override
20950    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20951        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20952        synchronized (mPackages) {
20953            final long identity = Binder.clearCallingIdentity();
20954            try {
20955                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20956                        packageNames, userId);
20957            } finally {
20958                Binder.restoreCallingIdentity(identity);
20959            }
20960        }
20961    }
20962
20963    private static void enforceSystemOrPhoneCaller(String tag) {
20964        int callingUid = Binder.getCallingUid();
20965        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20966            throw new SecurityException(
20967                    "Cannot call " + tag + " from UID " + callingUid);
20968        }
20969    }
20970
20971    boolean isHistoricalPackageUsageAvailable() {
20972        return mPackageUsage.isHistoricalPackageUsageAvailable();
20973    }
20974
20975    /**
20976     * Return a <b>copy</b> of the collection of packages known to the package manager.
20977     * @return A copy of the values of mPackages.
20978     */
20979    Collection<PackageParser.Package> getPackages() {
20980        synchronized (mPackages) {
20981            return new ArrayList<>(mPackages.values());
20982        }
20983    }
20984
20985    /**
20986     * Logs process start information (including base APK hash) to the security log.
20987     * @hide
20988     */
20989    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20990            String apkFile, int pid) {
20991        if (!SecurityLog.isLoggingEnabled()) {
20992            return;
20993        }
20994        Bundle data = new Bundle();
20995        data.putLong("startTimestamp", System.currentTimeMillis());
20996        data.putString("processName", processName);
20997        data.putInt("uid", uid);
20998        data.putString("seinfo", seinfo);
20999        data.putString("apkFile", apkFile);
21000        data.putInt("pid", pid);
21001        Message msg = mProcessLoggingHandler.obtainMessage(
21002                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21003        msg.setData(data);
21004        mProcessLoggingHandler.sendMessage(msg);
21005    }
21006}
21007