PackageManagerService.java revision 26af56d28ea50f71d59c87e366d708966cc0d1de
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_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
63import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
65import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
66import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
74import static android.content.pm.PackageManager.PERMISSION_DENIED;
75import static android.content.pm.PackageManager.PERMISSION_GRANTED;
76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
77import static android.content.pm.PackageParser.isApkFile;
78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
79import static android.system.OsConstants.O_CREAT;
80import static android.system.OsConstants.O_RDWR;
81
82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
86import static com.android.internal.util.ArrayUtils.appendInt;
87import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
93import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
99
100import android.Manifest;
101import android.annotation.NonNull;
102import android.annotation.Nullable;
103import android.app.ActivityManager;
104import android.app.ActivityManagerNative;
105import android.app.IActivityManager;
106import android.app.ResourcesManager;
107import android.app.admin.IDevicePolicyManager;
108import android.app.admin.SecurityLog;
109import android.app.backup.IBackupManager;
110import android.content.BroadcastReceiver;
111import android.content.ComponentName;
112import android.content.Context;
113import android.content.IIntentReceiver;
114import android.content.Intent;
115import android.content.IntentFilter;
116import android.content.IntentSender;
117import android.content.IntentSender.SendIntentException;
118import android.content.ServiceConnection;
119import android.content.pm.ActivityInfo;
120import android.content.pm.ApplicationInfo;
121import android.content.pm.AppsQueryHelper;
122import android.content.pm.ComponentInfo;
123import android.content.pm.EphemeralApplicationInfo;
124import android.content.pm.EphemeralResolveInfo;
125import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
126import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
127import android.content.pm.FeatureInfo;
128import android.content.pm.IOnPermissionsChangeListener;
129import android.content.pm.IPackageDataObserver;
130import android.content.pm.IPackageDeleteObserver;
131import android.content.pm.IPackageDeleteObserver2;
132import android.content.pm.IPackageInstallObserver2;
133import android.content.pm.IPackageInstaller;
134import android.content.pm.IPackageManager;
135import android.content.pm.IPackageMoveObserver;
136import android.content.pm.IPackageStatsObserver;
137import android.content.pm.InstrumentationInfo;
138import android.content.pm.IntentFilterVerificationInfo;
139import android.content.pm.KeySet;
140import android.content.pm.PackageCleanItem;
141import android.content.pm.PackageInfo;
142import android.content.pm.PackageInfoLite;
143import android.content.pm.PackageInstaller;
144import android.content.pm.PackageManager;
145import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
146import android.content.pm.PackageManagerInternal;
147import android.content.pm.PackageParser;
148import android.content.pm.PackageParser.ActivityIntentInfo;
149import android.content.pm.PackageParser.PackageLite;
150import android.content.pm.PackageParser.PackageParserException;
151import android.content.pm.PackageStats;
152import android.content.pm.PackageUserState;
153import android.content.pm.ParceledListSlice;
154import android.content.pm.PermissionGroupInfo;
155import android.content.pm.PermissionInfo;
156import android.content.pm.ProviderInfo;
157import android.content.pm.ResolveInfo;
158import android.content.pm.ServiceInfo;
159import android.content.pm.Signature;
160import android.content.pm.UserInfo;
161import android.content.pm.VerifierDeviceIdentity;
162import android.content.pm.VerifierInfo;
163import android.content.res.Resources;
164import android.graphics.Bitmap;
165import android.hardware.display.DisplayManager;
166import android.net.Uri;
167import android.os.Binder;
168import android.os.Build;
169import android.os.Bundle;
170import android.os.Debug;
171import android.os.Environment;
172import android.os.Environment.UserEnvironment;
173import android.os.FileUtils;
174import android.os.Handler;
175import android.os.IBinder;
176import android.os.Looper;
177import android.os.Message;
178import android.os.Parcel;
179import android.os.ParcelFileDescriptor;
180import android.os.PatternMatcher;
181import android.os.Process;
182import android.os.RemoteCallbackList;
183import android.os.RemoteException;
184import android.os.ResultReceiver;
185import android.os.SELinux;
186import android.os.ServiceManager;
187import android.os.SystemClock;
188import android.os.SystemProperties;
189import android.os.Trace;
190import android.os.UserHandle;
191import android.os.UserManager;
192import android.os.UserManagerInternal;
193import android.os.storage.IMountService;
194import android.os.storage.MountServiceInternal;
195import android.os.storage.StorageEventListener;
196import android.os.storage.StorageManager;
197import android.os.storage.VolumeInfo;
198import android.os.storage.VolumeRecord;
199import android.provider.Settings.Global;
200import android.provider.Settings.Secure;
201import android.security.KeyStore;
202import android.security.SystemKeyStore;
203import android.system.ErrnoException;
204import android.system.Os;
205import android.text.TextUtils;
206import android.text.format.DateUtils;
207import android.util.ArrayMap;
208import android.util.ArraySet;
209import android.util.DisplayMetrics;
210import android.util.EventLog;
211import android.util.ExceptionUtils;
212import android.util.Log;
213import android.util.LogPrinter;
214import android.util.MathUtils;
215import android.util.PrintStreamPrinter;
216import android.util.Slog;
217import android.util.SparseArray;
218import android.util.SparseBooleanArray;
219import android.util.SparseIntArray;
220import android.util.Xml;
221import android.util.jar.StrictJarFile;
222import android.view.Display;
223
224import com.android.internal.R;
225import com.android.internal.annotations.GuardedBy;
226import com.android.internal.app.IMediaContainerService;
227import com.android.internal.app.ResolverActivity;
228import com.android.internal.content.NativeLibraryHelper;
229import com.android.internal.content.PackageHelper;
230import com.android.internal.logging.MetricsLogger;
231import com.android.internal.os.IParcelFileDescriptorFactory;
232import com.android.internal.os.InstallerConnection.InstallerException;
233import com.android.internal.os.SomeArgs;
234import com.android.internal.os.Zygote;
235import com.android.internal.telephony.CarrierAppUtils;
236import com.android.internal.util.ArrayUtils;
237import com.android.internal.util.FastPrintWriter;
238import com.android.internal.util.FastXmlSerializer;
239import com.android.internal.util.IndentingPrintWriter;
240import com.android.internal.util.Preconditions;
241import com.android.internal.util.XmlUtils;
242import com.android.server.AttributeCache;
243import com.android.server.EventLogTags;
244import com.android.server.FgThread;
245import com.android.server.IntentResolver;
246import com.android.server.LocalServices;
247import com.android.server.ServiceThread;
248import com.android.server.SystemConfig;
249import com.android.server.Watchdog;
250import com.android.server.net.NetworkPolicyManagerInternal;
251import com.android.server.pm.PermissionsState.PermissionState;
252import com.android.server.pm.Settings.DatabaseVersion;
253import com.android.server.pm.Settings.VersionInfo;
254import com.android.server.storage.DeviceStorageMonitorInternal;
255
256import dalvik.system.CloseGuard;
257import dalvik.system.DexFile;
258import dalvik.system.VMRuntime;
259
260import libcore.io.IoUtils;
261import libcore.util.EmptyArray;
262
263import org.xmlpull.v1.XmlPullParser;
264import org.xmlpull.v1.XmlPullParserException;
265import org.xmlpull.v1.XmlSerializer;
266
267import java.io.BufferedOutputStream;
268import java.io.BufferedReader;
269import java.io.ByteArrayInputStream;
270import java.io.ByteArrayOutputStream;
271import java.io.File;
272import java.io.FileDescriptor;
273import java.io.FileInputStream;
274import java.io.FileNotFoundException;
275import java.io.FileOutputStream;
276import java.io.FileReader;
277import java.io.FilenameFilter;
278import java.io.IOException;
279import java.io.PrintWriter;
280import java.nio.charset.StandardCharsets;
281import java.security.DigestInputStream;
282import java.security.MessageDigest;
283import java.security.NoSuchAlgorithmException;
284import java.security.PublicKey;
285import java.security.cert.Certificate;
286import java.security.cert.CertificateEncodingException;
287import java.security.cert.CertificateException;
288import java.text.SimpleDateFormat;
289import java.util.ArrayList;
290import java.util.Arrays;
291import java.util.Collection;
292import java.util.Collections;
293import java.util.Comparator;
294import java.util.Date;
295import java.util.HashSet;
296import java.util.Iterator;
297import java.util.List;
298import java.util.Map;
299import java.util.Objects;
300import java.util.Set;
301import java.util.concurrent.CountDownLatch;
302import java.util.concurrent.TimeUnit;
303import java.util.concurrent.atomic.AtomicBoolean;
304import java.util.concurrent.atomic.AtomicInteger;
305
306/**
307 * Keep track of all those APKs everywhere.
308 * <p>
309 * Internally there are two important locks:
310 * <ul>
311 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
312 * and other related state. It is a fine-grained lock that should only be held
313 * momentarily, as it's one of the most contended locks in the system.
314 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
315 * operations typically involve heavy lifting of application data on disk. Since
316 * {@code installd} is single-threaded, and it's operations can often be slow,
317 * this lock should never be acquired while already holding {@link #mPackages}.
318 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
319 * holding {@link #mInstallLock}.
320 * </ul>
321 * Many internal methods rely on the caller to hold the appropriate locks, and
322 * this contract is expressed through method name suffixes:
323 * <ul>
324 * <li>fooLI(): the caller must hold {@link #mInstallLock}
325 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
326 * being modified must be frozen
327 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
328 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
329 * </ul>
330 * <p>
331 * Because this class is very central to the platform's security; please run all
332 * CTS and unit tests whenever making modifications:
333 *
334 * <pre>
335 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
336 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
337 * </pre>
338 */
339public class PackageManagerService extends IPackageManager.Stub {
340    static final String TAG = "PackageManager";
341    static final boolean DEBUG_SETTINGS = false;
342    static final boolean DEBUG_PREFERRED = false;
343    static final boolean DEBUG_UPGRADE = false;
344    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
345    private static final boolean DEBUG_BACKUP = false;
346    private static final boolean DEBUG_INSTALL = false;
347    private static final boolean DEBUG_REMOVE = false;
348    private static final boolean DEBUG_BROADCASTS = false;
349    private static final boolean DEBUG_SHOW_INFO = false;
350    private static final boolean DEBUG_PACKAGE_INFO = false;
351    private static final boolean DEBUG_INTENT_MATCHING = false;
352    private static final boolean DEBUG_PACKAGE_SCANNING = false;
353    private static final boolean DEBUG_VERIFY = false;
354    private static final boolean DEBUG_FILTERS = false;
355
356    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
357    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
358    // user, but by default initialize to this.
359    static final boolean DEBUG_DEXOPT = false;
360
361    private static final boolean DEBUG_ABI_SELECTION = false;
362    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
363    private static final boolean DEBUG_TRIAGED_MISSING = false;
364    private static final boolean DEBUG_APP_DATA = false;
365
366    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
367
368    // STOPSHIP; b/30256615
369    private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE;
370
371    private static final int RADIO_UID = Process.PHONE_UID;
372    private static final int LOG_UID = Process.LOG_UID;
373    private static final int NFC_UID = Process.NFC_UID;
374    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
375    private static final int SHELL_UID = Process.SHELL_UID;
376
377    // Cap the size of permission trees that 3rd party apps can define
378    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
379
380    // Suffix used during package installation when copying/moving
381    // package apks to install directory.
382    private static final String INSTALL_PACKAGE_SUFFIX = "-";
383
384    static final int SCAN_NO_DEX = 1<<1;
385    static final int SCAN_FORCE_DEX = 1<<2;
386    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
387    static final int SCAN_NEW_INSTALL = 1<<4;
388    static final int SCAN_NO_PATHS = 1<<5;
389    static final int SCAN_UPDATE_TIME = 1<<6;
390    static final int SCAN_DEFER_DEX = 1<<7;
391    static final int SCAN_BOOTING = 1<<8;
392    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
393    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
394    static final int SCAN_REPLACING = 1<<11;
395    static final int SCAN_REQUIRE_KNOWN = 1<<12;
396    static final int SCAN_MOVE = 1<<13;
397    static final int SCAN_INITIAL = 1<<14;
398    static final int SCAN_CHECK_ONLY = 1<<15;
399    static final int SCAN_DONT_KILL_APP = 1<<17;
400    static final int SCAN_IGNORE_FROZEN = 1<<18;
401
402    static final int REMOVE_CHATTY = 1<<16;
403
404    private static final int[] EMPTY_INT_ARRAY = new int[0];
405
406    /**
407     * Timeout (in milliseconds) after which the watchdog should declare that
408     * our handler thread is wedged.  The usual default for such things is one
409     * minute but we sometimes do very lengthy I/O operations on this thread,
410     * such as installing multi-gigabyte applications, so ours needs to be longer.
411     */
412    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
413
414    /**
415     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
416     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
417     * settings entry if available, otherwise we use the hardcoded default.  If it's been
418     * more than this long since the last fstrim, we force one during the boot sequence.
419     *
420     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
421     * one gets run at the next available charging+idle time.  This final mandatory
422     * no-fstrim check kicks in only of the other scheduling criteria is never met.
423     */
424    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
425
426    /**
427     * Whether verification is enabled by default.
428     */
429    private static final boolean DEFAULT_VERIFY_ENABLE = true;
430
431    /**
432     * The default maximum time to wait for the verification agent to return in
433     * milliseconds.
434     */
435    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
436
437    /**
438     * The default response for package verification timeout.
439     *
440     * This can be either PackageManager.VERIFICATION_ALLOW or
441     * PackageManager.VERIFICATION_REJECT.
442     */
443    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
444
445    static final String PLATFORM_PACKAGE_NAME = "android";
446
447    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
448
449    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
450            DEFAULT_CONTAINER_PACKAGE,
451            "com.android.defcontainer.DefaultContainerService");
452
453    private static final String KILL_APP_REASON_GIDS_CHANGED =
454            "permission grant or revoke changed gids";
455
456    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
457            "permissions revoked";
458
459    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
460
461    private static final String PACKAGE_SCHEME = "package";
462
463    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
464
465    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
466    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
467
468    /** Permission grant: not grant the permission. */
469    private static final int GRANT_DENIED = 1;
470
471    /** Permission grant: grant the permission as an install permission. */
472    private static final int GRANT_INSTALL = 2;
473
474    /** Permission grant: grant the permission as a runtime one. */
475    private static final int GRANT_RUNTIME = 3;
476
477    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
478    private static final int GRANT_UPGRADE = 4;
479
480    /** Canonical intent used to identify what counts as a "web browser" app */
481    private static final Intent sBrowserIntent;
482    static {
483        sBrowserIntent = new Intent();
484        sBrowserIntent.setAction(Intent.ACTION_VIEW);
485        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
486        sBrowserIntent.setData(Uri.parse("http:"));
487    }
488
489    /**
490     * The set of all protected actions [i.e. those actions for which a high priority
491     * intent filter is disallowed].
492     */
493    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
494    static {
495        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
496        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
497        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
498        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
499    }
500
501    // Compilation reasons.
502    public static final int REASON_FIRST_BOOT = 0;
503    public static final int REASON_BOOT = 1;
504    public static final int REASON_INSTALL = 2;
505    public static final int REASON_BACKGROUND_DEXOPT = 3;
506    public static final int REASON_AB_OTA = 4;
507    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
508    public static final int REASON_SHARED_APK = 6;
509    public static final int REASON_FORCED_DEXOPT = 7;
510    public static final int REASON_CORE_APP = 8;
511
512    public static final int REASON_LAST = REASON_CORE_APP;
513
514    /** Special library name that skips shared libraries check during compilation. */
515    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
516
517    final ServiceThread mHandlerThread;
518
519    final PackageHandler mHandler;
520
521    private final ProcessLoggingHandler mProcessLoggingHandler;
522
523    /**
524     * Messages for {@link #mHandler} that need to wait for system ready before
525     * being dispatched.
526     */
527    private ArrayList<Message> mPostSystemReadyMessages;
528
529    final int mSdkVersion = Build.VERSION.SDK_INT;
530
531    final Context mContext;
532    final boolean mFactoryTest;
533    final boolean mOnlyCore;
534    final DisplayMetrics mMetrics;
535    final int mDefParseFlags;
536    final String[] mSeparateProcesses;
537    final boolean mIsUpgrade;
538    final boolean mIsPreNUpgrade;
539    final boolean mIsPreNMR1Upgrade;
540
541    @GuardedBy("mPackages")
542    private boolean mDexOptDialogShown;
543
544    /** The location for ASEC container files on internal storage. */
545    final String mAsecInternalPath;
546
547    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
548    // LOCK HELD.  Can be called with mInstallLock held.
549    @GuardedBy("mInstallLock")
550    final Installer mInstaller;
551
552    /** Directory where installed third-party apps stored */
553    final File mAppInstallDir;
554    final File mEphemeralInstallDir;
555
556    /**
557     * Directory to which applications installed internally have their
558     * 32 bit native libraries copied.
559     */
560    private File mAppLib32InstallDir;
561
562    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
563    // apps.
564    final File mDrmAppPrivateInstallDir;
565
566    // ----------------------------------------------------------------
567
568    // Lock for state used when installing and doing other long running
569    // operations.  Methods that must be called with this lock held have
570    // the suffix "LI".
571    final Object mInstallLock = new Object();
572
573    // ----------------------------------------------------------------
574
575    // Keys are String (package name), values are Package.  This also serves
576    // as the lock for the global state.  Methods that must be called with
577    // this lock held have the prefix "LP".
578    @GuardedBy("mPackages")
579    final ArrayMap<String, PackageParser.Package> mPackages =
580            new ArrayMap<String, PackageParser.Package>();
581
582    final ArrayMap<String, Set<String>> mKnownCodebase =
583            new ArrayMap<String, Set<String>>();
584
585    // Tracks available target package names -> overlay package paths.
586    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
587        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
588
589    /**
590     * Tracks new system packages [received in an OTA] that we expect to
591     * find updated user-installed versions. Keys are package name, values
592     * are package location.
593     */
594    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
595    /**
596     * Tracks high priority intent filters for protected actions. During boot, certain
597     * filter actions are protected and should never be allowed to have a high priority
598     * intent filter for them. However, there is one, and only one exception -- the
599     * setup wizard. It must be able to define a high priority intent filter for these
600     * actions to ensure there are no escapes from the wizard. We need to delay processing
601     * of these during boot as we need to look at all of the system packages in order
602     * to know which component is the setup wizard.
603     */
604    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
605    /**
606     * Whether or not processing protected filters should be deferred.
607     */
608    private boolean mDeferProtectedFilters = true;
609
610    /**
611     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
612     */
613    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
614    /**
615     * Whether or not system app permissions should be promoted from install to runtime.
616     */
617    boolean mPromoteSystemApps;
618
619    @GuardedBy("mPackages")
620    final Settings mSettings;
621
622    /**
623     * Set of package names that are currently "frozen", which means active
624     * surgery is being done on the code/data for that package. The platform
625     * will refuse to launch frozen packages to avoid race conditions.
626     *
627     * @see PackageFreezer
628     */
629    @GuardedBy("mPackages")
630    final ArraySet<String> mFrozenPackages = new ArraySet<>();
631
632    final ProtectedPackages mProtectedPackages;
633
634    boolean mFirstBoot;
635
636    // System configuration read by SystemConfig.
637    final int[] mGlobalGids;
638    final SparseArray<ArraySet<String>> mSystemPermissions;
639    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
640
641    // If mac_permissions.xml was found for seinfo labeling.
642    boolean mFoundPolicyFile;
643
644    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
645
646    public static final class SharedLibraryEntry {
647        public final String path;
648        public final String apk;
649
650        SharedLibraryEntry(String _path, String _apk) {
651            path = _path;
652            apk = _apk;
653        }
654    }
655
656    // Currently known shared libraries.
657    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
658            new ArrayMap<String, SharedLibraryEntry>();
659
660    // All available activities, for your resolving pleasure.
661    final ActivityIntentResolver mActivities =
662            new ActivityIntentResolver();
663
664    // All available receivers, for your resolving pleasure.
665    final ActivityIntentResolver mReceivers =
666            new ActivityIntentResolver();
667
668    // All available services, for your resolving pleasure.
669    final ServiceIntentResolver mServices = new ServiceIntentResolver();
670
671    // All available providers, for your resolving pleasure.
672    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
673
674    // Mapping from provider base names (first directory in content URI codePath)
675    // to the provider information.
676    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
677            new ArrayMap<String, PackageParser.Provider>();
678
679    // Mapping from instrumentation class names to info about them.
680    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
681            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
682
683    // Mapping from permission names to info about them.
684    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
685            new ArrayMap<String, PackageParser.PermissionGroup>();
686
687    // Packages whose data we have transfered into another package, thus
688    // should no longer exist.
689    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
690
691    // Broadcast actions that are only available to the system.
692    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
693
694    /** List of packages waiting for verification. */
695    final SparseArray<PackageVerificationState> mPendingVerification
696            = new SparseArray<PackageVerificationState>();
697
698    /** Set of packages associated with each app op permission. */
699    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
700
701    final PackageInstallerService mInstallerService;
702
703    private final PackageDexOptimizer mPackageDexOptimizer;
704
705    private AtomicInteger mNextMoveId = new AtomicInteger();
706    private final MoveCallbacks mMoveCallbacks;
707
708    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
709
710    // Cache of users who need badging.
711    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
712
713    /** Token for keys in mPendingVerification. */
714    private int mPendingVerificationToken = 0;
715
716    volatile boolean mSystemReady;
717    volatile boolean mSafeMode;
718    volatile boolean mHasSystemUidErrors;
719
720    ApplicationInfo mAndroidApplication;
721    final ActivityInfo mResolveActivity = new ActivityInfo();
722    final ResolveInfo mResolveInfo = new ResolveInfo();
723    ComponentName mResolveComponentName;
724    PackageParser.Package mPlatformPackage;
725    ComponentName mCustomResolverComponentName;
726
727    boolean mResolverReplaced = false;
728
729    private final @Nullable ComponentName mIntentFilterVerifierComponent;
730    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
731
732    private int mIntentFilterVerificationToken = 0;
733
734    /** Component that knows whether or not an ephemeral application exists */
735    final ComponentName mEphemeralResolverComponent;
736    /** The service connection to the ephemeral resolver */
737    final EphemeralResolverConnection mEphemeralResolverConnection;
738
739    /** Component used to install ephemeral applications */
740    final ComponentName mEphemeralInstallerComponent;
741    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
742    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
743
744    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
745            = new SparseArray<IntentFilterVerificationState>();
746
747    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
748
749    // List of packages names to keep cached, even if they are uninstalled for all users
750    private List<String> mKeepUninstalledPackages;
751
752    private UserManagerInternal mUserManagerInternal;
753
754    private static class IFVerificationParams {
755        PackageParser.Package pkg;
756        boolean replacing;
757        int userId;
758        int verifierUid;
759
760        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
761                int _userId, int _verifierUid) {
762            pkg = _pkg;
763            replacing = _replacing;
764            userId = _userId;
765            replacing = _replacing;
766            verifierUid = _verifierUid;
767        }
768    }
769
770    private interface IntentFilterVerifier<T extends IntentFilter> {
771        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
772                                               T filter, String packageName);
773        void startVerifications(int userId);
774        void receiveVerificationResponse(int verificationId);
775    }
776
777    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
778        private Context mContext;
779        private ComponentName mIntentFilterVerifierComponent;
780        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
781
782        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
783            mContext = context;
784            mIntentFilterVerifierComponent = verifierComponent;
785        }
786
787        private String getDefaultScheme() {
788            return IntentFilter.SCHEME_HTTPS;
789        }
790
791        @Override
792        public void startVerifications(int userId) {
793            // Launch verifications requests
794            int count = mCurrentIntentFilterVerifications.size();
795            for (int n=0; n<count; n++) {
796                int verificationId = mCurrentIntentFilterVerifications.get(n);
797                final IntentFilterVerificationState ivs =
798                        mIntentFilterVerificationStates.get(verificationId);
799
800                String packageName = ivs.getPackageName();
801
802                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
803                final int filterCount = filters.size();
804                ArraySet<String> domainsSet = new ArraySet<>();
805                for (int m=0; m<filterCount; m++) {
806                    PackageParser.ActivityIntentInfo filter = filters.get(m);
807                    domainsSet.addAll(filter.getHostsList());
808                }
809                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
810                synchronized (mPackages) {
811                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
812                            packageName, domainsList) != null) {
813                        scheduleWriteSettingsLocked();
814                    }
815                }
816                sendVerificationRequest(userId, verificationId, ivs);
817            }
818            mCurrentIntentFilterVerifications.clear();
819        }
820
821        private void sendVerificationRequest(int userId, int verificationId,
822                IntentFilterVerificationState ivs) {
823
824            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
825            verificationIntent.putExtra(
826                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
827                    verificationId);
828            verificationIntent.putExtra(
829                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
830                    getDefaultScheme());
831            verificationIntent.putExtra(
832                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
833                    ivs.getHostsString());
834            verificationIntent.putExtra(
835                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
836                    ivs.getPackageName());
837            verificationIntent.setComponent(mIntentFilterVerifierComponent);
838            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
839
840            UserHandle user = new UserHandle(userId);
841            mContext.sendBroadcastAsUser(verificationIntent, user);
842            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
843                    "Sending IntentFilter verification broadcast");
844        }
845
846        public void receiveVerificationResponse(int verificationId) {
847            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
848
849            final boolean verified = ivs.isVerified();
850
851            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
852            final int count = filters.size();
853            if (DEBUG_DOMAIN_VERIFICATION) {
854                Slog.i(TAG, "Received verification response " + verificationId
855                        + " for " + count + " filters, verified=" + verified);
856            }
857            for (int n=0; n<count; n++) {
858                PackageParser.ActivityIntentInfo filter = filters.get(n);
859                filter.setVerified(verified);
860
861                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
862                        + " verified with result:" + verified + " and hosts:"
863                        + ivs.getHostsString());
864            }
865
866            mIntentFilterVerificationStates.remove(verificationId);
867
868            final String packageName = ivs.getPackageName();
869            IntentFilterVerificationInfo ivi = null;
870
871            synchronized (mPackages) {
872                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
873            }
874            if (ivi == null) {
875                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
876                        + verificationId + " packageName:" + packageName);
877                return;
878            }
879            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
880                    "Updating IntentFilterVerificationInfo for package " + packageName
881                            +" verificationId:" + verificationId);
882
883            synchronized (mPackages) {
884                if (verified) {
885                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
886                } else {
887                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
888                }
889                scheduleWriteSettingsLocked();
890
891                final int userId = ivs.getUserId();
892                if (userId != UserHandle.USER_ALL) {
893                    final int userStatus =
894                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
895
896                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
897                    boolean needUpdate = false;
898
899                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
900                    // already been set by the User thru the Disambiguation dialog
901                    switch (userStatus) {
902                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
903                            if (verified) {
904                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
905                            } else {
906                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
907                            }
908                            needUpdate = true;
909                            break;
910
911                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
912                            if (verified) {
913                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
914                                needUpdate = true;
915                            }
916                            break;
917
918                        default:
919                            // Nothing to do
920                    }
921
922                    if (needUpdate) {
923                        mSettings.updateIntentFilterVerificationStatusLPw(
924                                packageName, updatedStatus, userId);
925                        scheduleWritePackageRestrictionsLocked(userId);
926                    }
927                }
928            }
929        }
930
931        @Override
932        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
933                    ActivityIntentInfo filter, String packageName) {
934            if (!hasValidDomains(filter)) {
935                return false;
936            }
937            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
938            if (ivs == null) {
939                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
940                        packageName);
941            }
942            if (DEBUG_DOMAIN_VERIFICATION) {
943                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
944            }
945            ivs.addFilter(filter);
946            return true;
947        }
948
949        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
950                int userId, int verificationId, String packageName) {
951            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
952                    verifierUid, userId, packageName);
953            ivs.setPendingState();
954            synchronized (mPackages) {
955                mIntentFilterVerificationStates.append(verificationId, ivs);
956                mCurrentIntentFilterVerifications.add(verificationId);
957            }
958            return ivs;
959        }
960    }
961
962    private static boolean hasValidDomains(ActivityIntentInfo filter) {
963        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
964                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
965                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
966    }
967
968    // Set of pending broadcasts for aggregating enable/disable of components.
969    static class PendingPackageBroadcasts {
970        // for each user id, a map of <package name -> components within that package>
971        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
972
973        public PendingPackageBroadcasts() {
974            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
975        }
976
977        public ArrayList<String> get(int userId, String packageName) {
978            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
979            return packages.get(packageName);
980        }
981
982        public void put(int userId, String packageName, ArrayList<String> components) {
983            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
984            packages.put(packageName, components);
985        }
986
987        public void remove(int userId, String packageName) {
988            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
989            if (packages != null) {
990                packages.remove(packageName);
991            }
992        }
993
994        public void remove(int userId) {
995            mUidMap.remove(userId);
996        }
997
998        public int userIdCount() {
999            return mUidMap.size();
1000        }
1001
1002        public int userIdAt(int n) {
1003            return mUidMap.keyAt(n);
1004        }
1005
1006        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1007            return mUidMap.get(userId);
1008        }
1009
1010        public int size() {
1011            // total number of pending broadcast entries across all userIds
1012            int num = 0;
1013            for (int i = 0; i< mUidMap.size(); i++) {
1014                num += mUidMap.valueAt(i).size();
1015            }
1016            return num;
1017        }
1018
1019        public void clear() {
1020            mUidMap.clear();
1021        }
1022
1023        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1024            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1025            if (map == null) {
1026                map = new ArrayMap<String, ArrayList<String>>();
1027                mUidMap.put(userId, map);
1028            }
1029            return map;
1030        }
1031    }
1032    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1033
1034    // Service Connection to remote media container service to copy
1035    // package uri's from external media onto secure containers
1036    // or internal storage.
1037    private IMediaContainerService mContainerService = null;
1038
1039    static final int SEND_PENDING_BROADCAST = 1;
1040    static final int MCS_BOUND = 3;
1041    static final int END_COPY = 4;
1042    static final int INIT_COPY = 5;
1043    static final int MCS_UNBIND = 6;
1044    static final int START_CLEANING_PACKAGE = 7;
1045    static final int FIND_INSTALL_LOC = 8;
1046    static final int POST_INSTALL = 9;
1047    static final int MCS_RECONNECT = 10;
1048    static final int MCS_GIVE_UP = 11;
1049    static final int UPDATED_MEDIA_STATUS = 12;
1050    static final int WRITE_SETTINGS = 13;
1051    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1052    static final int PACKAGE_VERIFIED = 15;
1053    static final int CHECK_PENDING_VERIFICATION = 16;
1054    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1055    static final int INTENT_FILTER_VERIFIED = 18;
1056    static final int WRITE_PACKAGE_LIST = 19;
1057
1058    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1059
1060    // Delay time in millisecs
1061    static final int BROADCAST_DELAY = 10 * 1000;
1062
1063    static UserManagerService sUserManager;
1064
1065    // Stores a list of users whose package restrictions file needs to be updated
1066    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1067
1068    final private DefaultContainerConnection mDefContainerConn =
1069            new DefaultContainerConnection();
1070    class DefaultContainerConnection implements ServiceConnection {
1071        public void onServiceConnected(ComponentName name, IBinder service) {
1072            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1073            IMediaContainerService imcs =
1074                IMediaContainerService.Stub.asInterface(service);
1075            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1076        }
1077
1078        public void onServiceDisconnected(ComponentName name) {
1079            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1080        }
1081    }
1082
1083    // Recordkeeping of restore-after-install operations that are currently in flight
1084    // between the Package Manager and the Backup Manager
1085    static class PostInstallData {
1086        public InstallArgs args;
1087        public PackageInstalledInfo res;
1088
1089        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1090            args = _a;
1091            res = _r;
1092        }
1093    }
1094
1095    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1096    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1097
1098    // XML tags for backup/restore of various bits of state
1099    private static final String TAG_PREFERRED_BACKUP = "pa";
1100    private static final String TAG_DEFAULT_APPS = "da";
1101    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1102
1103    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1104    private static final String TAG_ALL_GRANTS = "rt-grants";
1105    private static final String TAG_GRANT = "grant";
1106    private static final String ATTR_PACKAGE_NAME = "pkg";
1107
1108    private static final String TAG_PERMISSION = "perm";
1109    private static final String ATTR_PERMISSION_NAME = "name";
1110    private static final String ATTR_IS_GRANTED = "g";
1111    private static final String ATTR_USER_SET = "set";
1112    private static final String ATTR_USER_FIXED = "fixed";
1113    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1114
1115    // System/policy permission grants are not backed up
1116    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1117            FLAG_PERMISSION_POLICY_FIXED
1118            | FLAG_PERMISSION_SYSTEM_FIXED
1119            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1120
1121    // And we back up these user-adjusted states
1122    private static final int USER_RUNTIME_GRANT_MASK =
1123            FLAG_PERMISSION_USER_SET
1124            | FLAG_PERMISSION_USER_FIXED
1125            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1126
1127    final @Nullable String mRequiredVerifierPackage;
1128    final @NonNull String mRequiredInstallerPackage;
1129    final @NonNull String mRequiredUninstallerPackage;
1130    final @Nullable String mSetupWizardPackage;
1131    final @Nullable String mStorageManagerPackage;
1132    final @NonNull String mServicesSystemSharedLibraryPackageName;
1133    final @NonNull String mSharedSystemSharedLibraryPackageName;
1134
1135    private final PackageUsage mPackageUsage = new PackageUsage();
1136    private final CompilerStats mCompilerStats = new CompilerStats();
1137
1138    class PackageHandler extends Handler {
1139        private boolean mBound = false;
1140        final ArrayList<HandlerParams> mPendingInstalls =
1141            new ArrayList<HandlerParams>();
1142
1143        private boolean connectToService() {
1144            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1145                    " DefaultContainerService");
1146            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1147            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1148            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1149                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1150                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1151                mBound = true;
1152                return true;
1153            }
1154            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1155            return false;
1156        }
1157
1158        private void disconnectService() {
1159            mContainerService = null;
1160            mBound = false;
1161            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1162            mContext.unbindService(mDefContainerConn);
1163            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1164        }
1165
1166        PackageHandler(Looper looper) {
1167            super(looper);
1168        }
1169
1170        public void handleMessage(Message msg) {
1171            try {
1172                doHandleMessage(msg);
1173            } finally {
1174                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1175            }
1176        }
1177
1178        void doHandleMessage(Message msg) {
1179            switch (msg.what) {
1180                case INIT_COPY: {
1181                    HandlerParams params = (HandlerParams) msg.obj;
1182                    int idx = mPendingInstalls.size();
1183                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1184                    // If a bind was already initiated we dont really
1185                    // need to do anything. The pending install
1186                    // will be processed later on.
1187                    if (!mBound) {
1188                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1189                                System.identityHashCode(mHandler));
1190                        // If this is the only one pending we might
1191                        // have to bind to the service again.
1192                        if (!connectToService()) {
1193                            Slog.e(TAG, "Failed to bind to media container service");
1194                            params.serviceError();
1195                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1196                                    System.identityHashCode(mHandler));
1197                            if (params.traceMethod != null) {
1198                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1199                                        params.traceCookie);
1200                            }
1201                            return;
1202                        } else {
1203                            // Once we bind to the service, the first
1204                            // pending request will be processed.
1205                            mPendingInstalls.add(idx, params);
1206                        }
1207                    } else {
1208                        mPendingInstalls.add(idx, params);
1209                        // Already bound to the service. Just make
1210                        // sure we trigger off processing the first request.
1211                        if (idx == 0) {
1212                            mHandler.sendEmptyMessage(MCS_BOUND);
1213                        }
1214                    }
1215                    break;
1216                }
1217                case MCS_BOUND: {
1218                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1219                    if (msg.obj != null) {
1220                        mContainerService = (IMediaContainerService) msg.obj;
1221                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1222                                System.identityHashCode(mHandler));
1223                    }
1224                    if (mContainerService == null) {
1225                        if (!mBound) {
1226                            // Something seriously wrong since we are not bound and we are not
1227                            // waiting for connection. Bail out.
1228                            Slog.e(TAG, "Cannot bind to media container service");
1229                            for (HandlerParams params : mPendingInstalls) {
1230                                // Indicate service bind error
1231                                params.serviceError();
1232                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1233                                        System.identityHashCode(params));
1234                                if (params.traceMethod != null) {
1235                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1236                                            params.traceMethod, params.traceCookie);
1237                                }
1238                                return;
1239                            }
1240                            mPendingInstalls.clear();
1241                        } else {
1242                            Slog.w(TAG, "Waiting to connect to media container service");
1243                        }
1244                    } else if (mPendingInstalls.size() > 0) {
1245                        HandlerParams params = mPendingInstalls.get(0);
1246                        if (params != null) {
1247                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1248                                    System.identityHashCode(params));
1249                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1250                            if (params.startCopy()) {
1251                                // We are done...  look for more work or to
1252                                // go idle.
1253                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1254                                        "Checking for more work or unbind...");
1255                                // Delete pending install
1256                                if (mPendingInstalls.size() > 0) {
1257                                    mPendingInstalls.remove(0);
1258                                }
1259                                if (mPendingInstalls.size() == 0) {
1260                                    if (mBound) {
1261                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1262                                                "Posting delayed MCS_UNBIND");
1263                                        removeMessages(MCS_UNBIND);
1264                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1265                                        // Unbind after a little delay, to avoid
1266                                        // continual thrashing.
1267                                        sendMessageDelayed(ubmsg, 10000);
1268                                    }
1269                                } else {
1270                                    // There are more pending requests in queue.
1271                                    // Just post MCS_BOUND message to trigger processing
1272                                    // of next pending install.
1273                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1274                                            "Posting MCS_BOUND for next work");
1275                                    mHandler.sendEmptyMessage(MCS_BOUND);
1276                                }
1277                            }
1278                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1279                        }
1280                    } else {
1281                        // Should never happen ideally.
1282                        Slog.w(TAG, "Empty queue");
1283                    }
1284                    break;
1285                }
1286                case MCS_RECONNECT: {
1287                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1288                    if (mPendingInstalls.size() > 0) {
1289                        if (mBound) {
1290                            disconnectService();
1291                        }
1292                        if (!connectToService()) {
1293                            Slog.e(TAG, "Failed to bind to media container service");
1294                            for (HandlerParams params : mPendingInstalls) {
1295                                // Indicate service bind error
1296                                params.serviceError();
1297                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1298                                        System.identityHashCode(params));
1299                            }
1300                            mPendingInstalls.clear();
1301                        }
1302                    }
1303                    break;
1304                }
1305                case MCS_UNBIND: {
1306                    // If there is no actual work left, then time to unbind.
1307                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1308
1309                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1310                        if (mBound) {
1311                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1312
1313                            disconnectService();
1314                        }
1315                    } else if (mPendingInstalls.size() > 0) {
1316                        // There are more pending requests in queue.
1317                        // Just post MCS_BOUND message to trigger processing
1318                        // of next pending install.
1319                        mHandler.sendEmptyMessage(MCS_BOUND);
1320                    }
1321
1322                    break;
1323                }
1324                case MCS_GIVE_UP: {
1325                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1326                    HandlerParams params = mPendingInstalls.remove(0);
1327                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1328                            System.identityHashCode(params));
1329                    break;
1330                }
1331                case SEND_PENDING_BROADCAST: {
1332                    String packages[];
1333                    ArrayList<String> components[];
1334                    int size = 0;
1335                    int uids[];
1336                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1337                    synchronized (mPackages) {
1338                        if (mPendingBroadcasts == null) {
1339                            return;
1340                        }
1341                        size = mPendingBroadcasts.size();
1342                        if (size <= 0) {
1343                            // Nothing to be done. Just return
1344                            return;
1345                        }
1346                        packages = new String[size];
1347                        components = new ArrayList[size];
1348                        uids = new int[size];
1349                        int i = 0;  // filling out the above arrays
1350
1351                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1352                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1353                            Iterator<Map.Entry<String, ArrayList<String>>> it
1354                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1355                                            .entrySet().iterator();
1356                            while (it.hasNext() && i < size) {
1357                                Map.Entry<String, ArrayList<String>> ent = it.next();
1358                                packages[i] = ent.getKey();
1359                                components[i] = ent.getValue();
1360                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1361                                uids[i] = (ps != null)
1362                                        ? UserHandle.getUid(packageUserId, ps.appId)
1363                                        : -1;
1364                                i++;
1365                            }
1366                        }
1367                        size = i;
1368                        mPendingBroadcasts.clear();
1369                    }
1370                    // Send broadcasts
1371                    for (int i = 0; i < size; i++) {
1372                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1373                    }
1374                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1375                    break;
1376                }
1377                case START_CLEANING_PACKAGE: {
1378                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1379                    final String packageName = (String)msg.obj;
1380                    final int userId = msg.arg1;
1381                    final boolean andCode = msg.arg2 != 0;
1382                    synchronized (mPackages) {
1383                        if (userId == UserHandle.USER_ALL) {
1384                            int[] users = sUserManager.getUserIds();
1385                            for (int user : users) {
1386                                mSettings.addPackageToCleanLPw(
1387                                        new PackageCleanItem(user, packageName, andCode));
1388                            }
1389                        } else {
1390                            mSettings.addPackageToCleanLPw(
1391                                    new PackageCleanItem(userId, packageName, andCode));
1392                        }
1393                    }
1394                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1395                    startCleaningPackages();
1396                } break;
1397                case POST_INSTALL: {
1398                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1399
1400                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1401                    final boolean didRestore = (msg.arg2 != 0);
1402                    mRunningInstalls.delete(msg.arg1);
1403
1404                    if (data != null) {
1405                        InstallArgs args = data.args;
1406                        PackageInstalledInfo parentRes = data.res;
1407
1408                        final boolean grantPermissions = (args.installFlags
1409                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1410                        final boolean killApp = (args.installFlags
1411                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1412                        final String[] grantedPermissions = args.installGrantPermissions;
1413
1414                        // Handle the parent package
1415                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1416                                grantedPermissions, didRestore, args.installerPackageName,
1417                                args.observer);
1418
1419                        // Handle the child packages
1420                        final int childCount = (parentRes.addedChildPackages != null)
1421                                ? parentRes.addedChildPackages.size() : 0;
1422                        for (int i = 0; i < childCount; i++) {
1423                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1424                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1425                                    grantedPermissions, false, args.installerPackageName,
1426                                    args.observer);
1427                        }
1428
1429                        // Log tracing if needed
1430                        if (args.traceMethod != null) {
1431                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1432                                    args.traceCookie);
1433                        }
1434                    } else {
1435                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1436                    }
1437
1438                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1439                } break;
1440                case UPDATED_MEDIA_STATUS: {
1441                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1442                    boolean reportStatus = msg.arg1 == 1;
1443                    boolean doGc = msg.arg2 == 1;
1444                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1445                    if (doGc) {
1446                        // Force a gc to clear up stale containers.
1447                        Runtime.getRuntime().gc();
1448                    }
1449                    if (msg.obj != null) {
1450                        @SuppressWarnings("unchecked")
1451                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1452                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1453                        // Unload containers
1454                        unloadAllContainers(args);
1455                    }
1456                    if (reportStatus) {
1457                        try {
1458                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1459                            PackageHelper.getMountService().finishMediaUpdate();
1460                        } catch (RemoteException e) {
1461                            Log.e(TAG, "MountService not running?");
1462                        }
1463                    }
1464                } break;
1465                case WRITE_SETTINGS: {
1466                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1467                    synchronized (mPackages) {
1468                        removeMessages(WRITE_SETTINGS);
1469                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1470                        mSettings.writeLPr();
1471                        mDirtyUsers.clear();
1472                    }
1473                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1474                } break;
1475                case WRITE_PACKAGE_RESTRICTIONS: {
1476                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1477                    synchronized (mPackages) {
1478                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1479                        for (int userId : mDirtyUsers) {
1480                            mSettings.writePackageRestrictionsLPr(userId);
1481                        }
1482                        mDirtyUsers.clear();
1483                    }
1484                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1485                } break;
1486                case WRITE_PACKAGE_LIST: {
1487                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1488                    synchronized (mPackages) {
1489                        removeMessages(WRITE_PACKAGE_LIST);
1490                        mSettings.writePackageListLPr(msg.arg1);
1491                    }
1492                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1493                } break;
1494                case CHECK_PENDING_VERIFICATION: {
1495                    final int verificationId = msg.arg1;
1496                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1497
1498                    if ((state != null) && !state.timeoutExtended()) {
1499                        final InstallArgs args = state.getInstallArgs();
1500                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1501
1502                        Slog.i(TAG, "Verification timed out for " + originUri);
1503                        mPendingVerification.remove(verificationId);
1504
1505                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1506
1507                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1508                            Slog.i(TAG, "Continuing with installation of " + originUri);
1509                            state.setVerifierResponse(Binder.getCallingUid(),
1510                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1511                            broadcastPackageVerified(verificationId, originUri,
1512                                    PackageManager.VERIFICATION_ALLOW,
1513                                    state.getInstallArgs().getUser());
1514                            try {
1515                                ret = args.copyApk(mContainerService, true);
1516                            } catch (RemoteException e) {
1517                                Slog.e(TAG, "Could not contact the ContainerService");
1518                            }
1519                        } else {
1520                            broadcastPackageVerified(verificationId, originUri,
1521                                    PackageManager.VERIFICATION_REJECT,
1522                                    state.getInstallArgs().getUser());
1523                        }
1524
1525                        Trace.asyncTraceEnd(
1526                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1527
1528                        processPendingInstall(args, ret);
1529                        mHandler.sendEmptyMessage(MCS_UNBIND);
1530                    }
1531                    break;
1532                }
1533                case PACKAGE_VERIFIED: {
1534                    final int verificationId = msg.arg1;
1535
1536                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1537                    if (state == null) {
1538                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1539                        break;
1540                    }
1541
1542                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1543
1544                    state.setVerifierResponse(response.callerUid, response.code);
1545
1546                    if (state.isVerificationComplete()) {
1547                        mPendingVerification.remove(verificationId);
1548
1549                        final InstallArgs args = state.getInstallArgs();
1550                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1551
1552                        int ret;
1553                        if (state.isInstallAllowed()) {
1554                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1555                            broadcastPackageVerified(verificationId, originUri,
1556                                    response.code, state.getInstallArgs().getUser());
1557                            try {
1558                                ret = args.copyApk(mContainerService, true);
1559                            } catch (RemoteException e) {
1560                                Slog.e(TAG, "Could not contact the ContainerService");
1561                            }
1562                        } else {
1563                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1564                        }
1565
1566                        Trace.asyncTraceEnd(
1567                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1568
1569                        processPendingInstall(args, ret);
1570                        mHandler.sendEmptyMessage(MCS_UNBIND);
1571                    }
1572
1573                    break;
1574                }
1575                case START_INTENT_FILTER_VERIFICATIONS: {
1576                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1577                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1578                            params.replacing, params.pkg);
1579                    break;
1580                }
1581                case INTENT_FILTER_VERIFIED: {
1582                    final int verificationId = msg.arg1;
1583
1584                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1585                            verificationId);
1586                    if (state == null) {
1587                        Slog.w(TAG, "Invalid IntentFilter verification token "
1588                                + verificationId + " received");
1589                        break;
1590                    }
1591
1592                    final int userId = state.getUserId();
1593
1594                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1595                            "Processing IntentFilter verification with token:"
1596                            + verificationId + " and userId:" + userId);
1597
1598                    final IntentFilterVerificationResponse response =
1599                            (IntentFilterVerificationResponse) msg.obj;
1600
1601                    state.setVerifierResponse(response.callerUid, response.code);
1602
1603                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1604                            "IntentFilter verification with token:" + verificationId
1605                            + " and userId:" + userId
1606                            + " is settings verifier response with response code:"
1607                            + response.code);
1608
1609                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1610                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1611                                + response.getFailedDomainsString());
1612                    }
1613
1614                    if (state.isVerificationComplete()) {
1615                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1616                    } else {
1617                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1618                                "IntentFilter verification with token:" + verificationId
1619                                + " was not said to be complete");
1620                    }
1621
1622                    break;
1623                }
1624            }
1625        }
1626    }
1627
1628    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1629            boolean killApp, String[] grantedPermissions,
1630            boolean launchedForRestore, String installerPackage,
1631            IPackageInstallObserver2 installObserver) {
1632        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1633            // Send the removed broadcasts
1634            if (res.removedInfo != null) {
1635                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1636            }
1637
1638            // Now that we successfully installed the package, grant runtime
1639            // permissions if requested before broadcasting the install.
1640            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1641                    >= Build.VERSION_CODES.M) {
1642                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1643            }
1644
1645            final boolean update = res.removedInfo != null
1646                    && res.removedInfo.removedPackage != null;
1647
1648            // If this is the first time we have child packages for a disabled privileged
1649            // app that had no children, we grant requested runtime permissions to the new
1650            // children if the parent on the system image had them already granted.
1651            if (res.pkg.parentPackage != null) {
1652                synchronized (mPackages) {
1653                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1654                }
1655            }
1656
1657            synchronized (mPackages) {
1658                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1659            }
1660
1661            final String packageName = res.pkg.applicationInfo.packageName;
1662            Bundle extras = new Bundle(1);
1663            extras.putInt(Intent.EXTRA_UID, res.uid);
1664
1665            // Determine the set of users who are adding this package for
1666            // the first time vs. those who are seeing an update.
1667            int[] firstUsers = EMPTY_INT_ARRAY;
1668            int[] updateUsers = EMPTY_INT_ARRAY;
1669            if (res.origUsers == null || res.origUsers.length == 0) {
1670                firstUsers = res.newUsers;
1671            } else {
1672                for (int newUser : res.newUsers) {
1673                    boolean isNew = true;
1674                    for (int origUser : res.origUsers) {
1675                        if (origUser == newUser) {
1676                            isNew = false;
1677                            break;
1678                        }
1679                    }
1680                    if (isNew) {
1681                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1682                    } else {
1683                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1684                    }
1685                }
1686            }
1687
1688            // Send installed broadcasts if the install/update is not ephemeral
1689            if (!isEphemeral(res.pkg)) {
1690                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1691
1692                // Send added for users that see the package for the first time
1693                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1694                        extras, 0 /*flags*/, null /*targetPackage*/,
1695                        null /*finishedReceiver*/, firstUsers);
1696
1697                // Send added for users that don't see the package for the first time
1698                if (update) {
1699                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1700                }
1701                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1702                        extras, 0 /*flags*/, null /*targetPackage*/,
1703                        null /*finishedReceiver*/, updateUsers);
1704
1705                // Send replaced for users that don't see the package for the first time
1706                if (update) {
1707                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1708                            packageName, extras, 0 /*flags*/,
1709                            null /*targetPackage*/, null /*finishedReceiver*/,
1710                            updateUsers);
1711                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1712                            null /*package*/, null /*extras*/, 0 /*flags*/,
1713                            packageName /*targetPackage*/,
1714                            null /*finishedReceiver*/, updateUsers);
1715                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1716                    // First-install and we did a restore, so we're responsible for the
1717                    // first-launch broadcast.
1718                    if (DEBUG_BACKUP) {
1719                        Slog.i(TAG, "Post-restore of " + packageName
1720                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1721                    }
1722                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1723                }
1724
1725                // Send broadcast package appeared if forward locked/external for all users
1726                // treat asec-hosted packages like removable media on upgrade
1727                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1728                    if (DEBUG_INSTALL) {
1729                        Slog.i(TAG, "upgrading pkg " + res.pkg
1730                                + " is ASEC-hosted -> AVAILABLE");
1731                    }
1732                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1733                    ArrayList<String> pkgList = new ArrayList<>(1);
1734                    pkgList.add(packageName);
1735                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1736                }
1737            }
1738
1739            // Work that needs to happen on first install within each user
1740            if (firstUsers != null && firstUsers.length > 0) {
1741                synchronized (mPackages) {
1742                    for (int userId : firstUsers) {
1743                        // If this app is a browser and it's newly-installed for some
1744                        // users, clear any default-browser state in those users. The
1745                        // app's nature doesn't depend on the user, so we can just check
1746                        // its browser nature in any user and generalize.
1747                        if (packageIsBrowser(packageName, userId)) {
1748                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1749                        }
1750
1751                        // We may also need to apply pending (restored) runtime
1752                        // permission grants within these users.
1753                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1754                    }
1755                }
1756            }
1757
1758            // Log current value of "unknown sources" setting
1759            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1760                    getUnknownSourcesSettings());
1761
1762            // Force a gc to clear up things
1763            Runtime.getRuntime().gc();
1764
1765            // Remove the replaced package's older resources safely now
1766            // We delete after a gc for applications  on sdcard.
1767            if (res.removedInfo != null && res.removedInfo.args != null) {
1768                synchronized (mInstallLock) {
1769                    res.removedInfo.args.doPostDeleteLI(true);
1770                }
1771            }
1772        }
1773
1774        // If someone is watching installs - notify them
1775        if (installObserver != null) {
1776            try {
1777                Bundle extras = extrasForInstallResult(res);
1778                installObserver.onPackageInstalled(res.name, res.returnCode,
1779                        res.returnMsg, extras);
1780            } catch (RemoteException e) {
1781                Slog.i(TAG, "Observer no longer exists.");
1782            }
1783        }
1784    }
1785
1786    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1787            PackageParser.Package pkg) {
1788        if (pkg.parentPackage == null) {
1789            return;
1790        }
1791        if (pkg.requestedPermissions == null) {
1792            return;
1793        }
1794        final PackageSetting disabledSysParentPs = mSettings
1795                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1796        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1797                || !disabledSysParentPs.isPrivileged()
1798                || (disabledSysParentPs.childPackageNames != null
1799                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1800            return;
1801        }
1802        final int[] allUserIds = sUserManager.getUserIds();
1803        final int permCount = pkg.requestedPermissions.size();
1804        for (int i = 0; i < permCount; i++) {
1805            String permission = pkg.requestedPermissions.get(i);
1806            BasePermission bp = mSettings.mPermissions.get(permission);
1807            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1808                continue;
1809            }
1810            for (int userId : allUserIds) {
1811                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1812                        permission, userId)) {
1813                    grantRuntimePermission(pkg.packageName, permission, userId);
1814                }
1815            }
1816        }
1817    }
1818
1819    private StorageEventListener mStorageListener = new StorageEventListener() {
1820        @Override
1821        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1822            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1823                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1824                    final String volumeUuid = vol.getFsUuid();
1825
1826                    // Clean up any users or apps that were removed or recreated
1827                    // while this volume was missing
1828                    reconcileUsers(volumeUuid);
1829                    reconcileApps(volumeUuid);
1830
1831                    // Clean up any install sessions that expired or were
1832                    // cancelled while this volume was missing
1833                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1834
1835                    loadPrivatePackages(vol);
1836
1837                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1838                    unloadPrivatePackages(vol);
1839                }
1840            }
1841
1842            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1843                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1844                    updateExternalMediaStatus(true, false);
1845                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1846                    updateExternalMediaStatus(false, false);
1847                }
1848            }
1849        }
1850
1851        @Override
1852        public void onVolumeForgotten(String fsUuid) {
1853            if (TextUtils.isEmpty(fsUuid)) {
1854                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1855                return;
1856            }
1857
1858            // Remove any apps installed on the forgotten volume
1859            synchronized (mPackages) {
1860                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1861                for (PackageSetting ps : packages) {
1862                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1863                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1864                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1865                }
1866
1867                mSettings.onVolumeForgotten(fsUuid);
1868                mSettings.writeLPr();
1869            }
1870        }
1871    };
1872
1873    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1874            String[] grantedPermissions) {
1875        for (int userId : userIds) {
1876            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1877        }
1878
1879        // We could have touched GID membership, so flush out packages.list
1880        synchronized (mPackages) {
1881            mSettings.writePackageListLPr();
1882        }
1883    }
1884
1885    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1886            String[] grantedPermissions) {
1887        SettingBase sb = (SettingBase) pkg.mExtras;
1888        if (sb == null) {
1889            return;
1890        }
1891
1892        PermissionsState permissionsState = sb.getPermissionsState();
1893
1894        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1895                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1896
1897        for (String permission : pkg.requestedPermissions) {
1898            final BasePermission bp;
1899            synchronized (mPackages) {
1900                bp = mSettings.mPermissions.get(permission);
1901            }
1902            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1903                    && (grantedPermissions == null
1904                           || ArrayUtils.contains(grantedPermissions, permission))) {
1905                final int flags = permissionsState.getPermissionFlags(permission, userId);
1906                // Installer cannot change immutable permissions.
1907                if ((flags & immutableFlags) == 0) {
1908                    grantRuntimePermission(pkg.packageName, permission, userId);
1909                }
1910            }
1911        }
1912    }
1913
1914    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1915        Bundle extras = null;
1916        switch (res.returnCode) {
1917            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1918                extras = new Bundle();
1919                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1920                        res.origPermission);
1921                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1922                        res.origPackage);
1923                break;
1924            }
1925            case PackageManager.INSTALL_SUCCEEDED: {
1926                extras = new Bundle();
1927                extras.putBoolean(Intent.EXTRA_REPLACING,
1928                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1929                break;
1930            }
1931        }
1932        return extras;
1933    }
1934
1935    void scheduleWriteSettingsLocked() {
1936        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1937            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1938        }
1939    }
1940
1941    void scheduleWritePackageListLocked(int userId) {
1942        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1943            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1944            msg.arg1 = userId;
1945            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1946        }
1947    }
1948
1949    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1950        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1951        scheduleWritePackageRestrictionsLocked(userId);
1952    }
1953
1954    void scheduleWritePackageRestrictionsLocked(int userId) {
1955        final int[] userIds = (userId == UserHandle.USER_ALL)
1956                ? sUserManager.getUserIds() : new int[]{userId};
1957        for (int nextUserId : userIds) {
1958            if (!sUserManager.exists(nextUserId)) return;
1959            mDirtyUsers.add(nextUserId);
1960            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1961                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1962            }
1963        }
1964    }
1965
1966    public static PackageManagerService main(Context context, Installer installer,
1967            boolean factoryTest, boolean onlyCore) {
1968        // Self-check for initial settings.
1969        PackageManagerServiceCompilerMapping.checkProperties();
1970
1971        PackageManagerService m = new PackageManagerService(context, installer,
1972                factoryTest, onlyCore);
1973        m.enableSystemUserPackages();
1974        ServiceManager.addService("package", m);
1975        return m;
1976    }
1977
1978    private void enableSystemUserPackages() {
1979        if (!UserManager.isSplitSystemUser()) {
1980            return;
1981        }
1982        // For system user, enable apps based on the following conditions:
1983        // - app is whitelisted or belong to one of these groups:
1984        //   -- system app which has no launcher icons
1985        //   -- system app which has INTERACT_ACROSS_USERS permission
1986        //   -- system IME app
1987        // - app is not in the blacklist
1988        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1989        Set<String> enableApps = new ArraySet<>();
1990        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1991                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1992                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1993        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1994        enableApps.addAll(wlApps);
1995        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1996                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1997        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1998        enableApps.removeAll(blApps);
1999        Log.i(TAG, "Applications installed for system user: " + enableApps);
2000        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2001                UserHandle.SYSTEM);
2002        final int allAppsSize = allAps.size();
2003        synchronized (mPackages) {
2004            for (int i = 0; i < allAppsSize; i++) {
2005                String pName = allAps.get(i);
2006                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2007                // Should not happen, but we shouldn't be failing if it does
2008                if (pkgSetting == null) {
2009                    continue;
2010                }
2011                boolean install = enableApps.contains(pName);
2012                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2013                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2014                            + " for system user");
2015                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2016                }
2017            }
2018        }
2019    }
2020
2021    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2022        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2023                Context.DISPLAY_SERVICE);
2024        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2025    }
2026
2027    /**
2028     * Requests that files preopted on a secondary system partition be copied to the data partition
2029     * if possible.  Note that the actual copying of the files is accomplished by init for security
2030     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2031     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2032     */
2033    private static void requestCopyPreoptedFiles() {
2034        final int WAIT_TIME_MS = 100;
2035        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2036        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2037            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2038            // We will wait for up to 100 seconds.
2039            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2040            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2041                try {
2042                    Thread.sleep(WAIT_TIME_MS);
2043                } catch (InterruptedException e) {
2044                    // Do nothing
2045                }
2046                if (SystemClock.uptimeMillis() > timeEnd) {
2047                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2048                    Slog.wtf(TAG, "cppreopt did not finish!");
2049                    break;
2050                }
2051            }
2052        }
2053    }
2054
2055    public PackageManagerService(Context context, Installer installer,
2056            boolean factoryTest, boolean onlyCore) {
2057        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2058                SystemClock.uptimeMillis());
2059
2060        if (mSdkVersion <= 0) {
2061            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2062        }
2063
2064        mContext = context;
2065        mFactoryTest = factoryTest;
2066        mOnlyCore = onlyCore;
2067        mMetrics = new DisplayMetrics();
2068        mSettings = new Settings(mPackages);
2069        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2070                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2071        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2072                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2073        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2074                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2075        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2076                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2077        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2078                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2079        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2080                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2081
2082        String separateProcesses = SystemProperties.get("debug.separate_processes");
2083        if (separateProcesses != null && separateProcesses.length() > 0) {
2084            if ("*".equals(separateProcesses)) {
2085                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2086                mSeparateProcesses = null;
2087                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2088            } else {
2089                mDefParseFlags = 0;
2090                mSeparateProcesses = separateProcesses.split(",");
2091                Slog.w(TAG, "Running with debug.separate_processes: "
2092                        + separateProcesses);
2093            }
2094        } else {
2095            mDefParseFlags = 0;
2096            mSeparateProcesses = null;
2097        }
2098
2099        mInstaller = installer;
2100        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2101                "*dexopt*");
2102        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2103
2104        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2105                FgThread.get().getLooper());
2106
2107        getDefaultDisplayMetrics(context, mMetrics);
2108
2109        SystemConfig systemConfig = SystemConfig.getInstance();
2110        mGlobalGids = systemConfig.getGlobalGids();
2111        mSystemPermissions = systemConfig.getSystemPermissions();
2112        mAvailableFeatures = systemConfig.getAvailableFeatures();
2113
2114        mProtectedPackages = new ProtectedPackages(mContext);
2115
2116        synchronized (mInstallLock) {
2117        // writer
2118        synchronized (mPackages) {
2119            mHandlerThread = new ServiceThread(TAG,
2120                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2121            mHandlerThread.start();
2122            mHandler = new PackageHandler(mHandlerThread.getLooper());
2123            mProcessLoggingHandler = new ProcessLoggingHandler();
2124            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2125
2126            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2127
2128            File dataDir = Environment.getDataDirectory();
2129            mAppInstallDir = new File(dataDir, "app");
2130            mAppLib32InstallDir = new File(dataDir, "app-lib");
2131            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2132            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2133            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2134
2135            sUserManager = new UserManagerService(context, this, mPackages);
2136
2137            // Propagate permission configuration in to package manager.
2138            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2139                    = systemConfig.getPermissions();
2140            for (int i=0; i<permConfig.size(); i++) {
2141                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2142                BasePermission bp = mSettings.mPermissions.get(perm.name);
2143                if (bp == null) {
2144                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2145                    mSettings.mPermissions.put(perm.name, bp);
2146                }
2147                if (perm.gids != null) {
2148                    bp.setGids(perm.gids, perm.perUser);
2149                }
2150            }
2151
2152            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2153            for (int i=0; i<libConfig.size(); i++) {
2154                mSharedLibraries.put(libConfig.keyAt(i),
2155                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2156            }
2157
2158            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2159
2160            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2161
2162            if (mFirstBoot) {
2163                requestCopyPreoptedFiles();
2164            }
2165
2166            String customResolverActivity = Resources.getSystem().getString(
2167                    R.string.config_customResolverActivity);
2168            if (TextUtils.isEmpty(customResolverActivity)) {
2169                customResolverActivity = null;
2170            } else {
2171                mCustomResolverComponentName = ComponentName.unflattenFromString(
2172                        customResolverActivity);
2173            }
2174
2175            long startTime = SystemClock.uptimeMillis();
2176
2177            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2178                    startTime);
2179
2180            // Set flag to monitor and not change apk file paths when
2181            // scanning install directories.
2182            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2183
2184            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2185            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2186
2187            if (bootClassPath == null) {
2188                Slog.w(TAG, "No BOOTCLASSPATH found!");
2189            }
2190
2191            if (systemServerClassPath == null) {
2192                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2193            }
2194
2195            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2196            final String[] dexCodeInstructionSets =
2197                    getDexCodeInstructionSets(
2198                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2199
2200            /**
2201             * Ensure all external libraries have had dexopt run on them.
2202             */
2203            if (mSharedLibraries.size() > 0) {
2204                // NOTE: For now, we're compiling these system "shared libraries"
2205                // (and framework jars) into all available architectures. It's possible
2206                // to compile them only when we come across an app that uses them (there's
2207                // already logic for that in scanPackageLI) but that adds some complexity.
2208                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2209                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2210                        final String lib = libEntry.path;
2211                        if (lib == null) {
2212                            continue;
2213                        }
2214
2215                        try {
2216                            // Shared libraries do not have profiles so we perform a full
2217                            // AOT compilation (if needed).
2218                            int dexoptNeeded = DexFile.getDexOptNeeded(
2219                                    lib, dexCodeInstructionSet,
2220                                    getCompilerFilterForReason(REASON_SHARED_APK),
2221                                    false /* newProfile */);
2222                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2223                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2224                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2225                                        getCompilerFilterForReason(REASON_SHARED_APK),
2226                                        StorageManager.UUID_PRIVATE_INTERNAL,
2227                                        SKIP_SHARED_LIBRARY_CHECK);
2228                            }
2229                        } catch (FileNotFoundException e) {
2230                            Slog.w(TAG, "Library not found: " + lib);
2231                        } catch (IOException | InstallerException e) {
2232                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2233                                    + e.getMessage());
2234                        }
2235                    }
2236                }
2237            }
2238
2239            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2240
2241            final VersionInfo ver = mSettings.getInternalVersion();
2242            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2243
2244            // when upgrading from pre-M, promote system app permissions from install to runtime
2245            mPromoteSystemApps =
2246                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2247
2248            // When upgrading from pre-N, we need to handle package extraction like first boot,
2249            // as there is no profiling data available.
2250            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2251
2252            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2253
2254            // save off the names of pre-existing system packages prior to scanning; we don't
2255            // want to automatically grant runtime permissions for new system apps
2256            if (mPromoteSystemApps) {
2257                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2258                while (pkgSettingIter.hasNext()) {
2259                    PackageSetting ps = pkgSettingIter.next();
2260                    if (isSystemApp(ps)) {
2261                        mExistingSystemPackages.add(ps.name);
2262                    }
2263                }
2264            }
2265
2266            // Collect vendor overlay packages.
2267            // (Do this before scanning any apps.)
2268            // For security and version matching reason, only consider
2269            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2270            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2271            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2272                    | PackageParser.PARSE_IS_SYSTEM
2273                    | PackageParser.PARSE_IS_SYSTEM_DIR
2274                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2275
2276            // Find base frameworks (resource packages without code).
2277            scanDirTracedLI(frameworkDir, mDefParseFlags
2278                    | PackageParser.PARSE_IS_SYSTEM
2279                    | PackageParser.PARSE_IS_SYSTEM_DIR
2280                    | PackageParser.PARSE_IS_PRIVILEGED,
2281                    scanFlags | SCAN_NO_DEX, 0);
2282
2283            // Collected privileged system packages.
2284            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2285            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2286                    | PackageParser.PARSE_IS_SYSTEM
2287                    | PackageParser.PARSE_IS_SYSTEM_DIR
2288                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2289
2290            // Collect ordinary system packages.
2291            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2292            scanDirTracedLI(systemAppDir, mDefParseFlags
2293                    | PackageParser.PARSE_IS_SYSTEM
2294                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2295
2296            // Collect all vendor packages.
2297            File vendorAppDir = new File("/vendor/app");
2298            try {
2299                vendorAppDir = vendorAppDir.getCanonicalFile();
2300            } catch (IOException e) {
2301                // failed to look up canonical path, continue with original one
2302            }
2303            scanDirTracedLI(vendorAppDir, mDefParseFlags
2304                    | PackageParser.PARSE_IS_SYSTEM
2305                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2306
2307            // Collect all OEM packages.
2308            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2309            scanDirTracedLI(oemAppDir, mDefParseFlags
2310                    | PackageParser.PARSE_IS_SYSTEM
2311                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2312
2313            // Prune any system packages that no longer exist.
2314            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2315            if (!mOnlyCore) {
2316                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2317                while (psit.hasNext()) {
2318                    PackageSetting ps = psit.next();
2319
2320                    /*
2321                     * If this is not a system app, it can't be a
2322                     * disable system app.
2323                     */
2324                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2325                        continue;
2326                    }
2327
2328                    /*
2329                     * If the package is scanned, it's not erased.
2330                     */
2331                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2332                    if (scannedPkg != null) {
2333                        /*
2334                         * If the system app is both scanned and in the
2335                         * disabled packages list, then it must have been
2336                         * added via OTA. Remove it from the currently
2337                         * scanned package so the previously user-installed
2338                         * application can be scanned.
2339                         */
2340                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2341                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2342                                    + ps.name + "; removing system app.  Last known codePath="
2343                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2344                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2345                                    + scannedPkg.mVersionCode);
2346                            removePackageLI(scannedPkg, true);
2347                            mExpectingBetter.put(ps.name, ps.codePath);
2348                        }
2349
2350                        continue;
2351                    }
2352
2353                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2354                        psit.remove();
2355                        logCriticalInfo(Log.WARN, "System package " + ps.name
2356                                + " no longer exists; it's data will be wiped");
2357                        // Actual deletion of code and data will be handled by later
2358                        // reconciliation step
2359                    } else {
2360                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2361                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2362                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2363                        }
2364                    }
2365                }
2366            }
2367
2368            //look for any incomplete package installations
2369            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2370            for (int i = 0; i < deletePkgsList.size(); i++) {
2371                // Actual deletion of code and data will be handled by later
2372                // reconciliation step
2373                final String packageName = deletePkgsList.get(i).name;
2374                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2375                synchronized (mPackages) {
2376                    mSettings.removePackageLPw(packageName);
2377                }
2378            }
2379
2380            //delete tmp files
2381            deleteTempPackageFiles();
2382
2383            // Remove any shared userIDs that have no associated packages
2384            mSettings.pruneSharedUsersLPw();
2385
2386            if (!mOnlyCore) {
2387                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2388                        SystemClock.uptimeMillis());
2389                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2390
2391                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2392                        | PackageParser.PARSE_FORWARD_LOCK,
2393                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2394
2395                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2396                        | PackageParser.PARSE_IS_EPHEMERAL,
2397                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2398
2399                /**
2400                 * Remove disable package settings for any updated system
2401                 * apps that were removed via an OTA. If they're not a
2402                 * previously-updated app, remove them completely.
2403                 * Otherwise, just revoke their system-level permissions.
2404                 */
2405                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2406                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2407                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2408
2409                    String msg;
2410                    if (deletedPkg == null) {
2411                        msg = "Updated system package " + deletedAppName
2412                                + " no longer exists; it's data will be wiped";
2413                        // Actual deletion of code and data will be handled by later
2414                        // reconciliation step
2415                    } else {
2416                        msg = "Updated system app + " + deletedAppName
2417                                + " no longer present; removing system privileges for "
2418                                + deletedAppName;
2419
2420                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2421
2422                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2423                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2424                    }
2425                    logCriticalInfo(Log.WARN, msg);
2426                }
2427
2428                /**
2429                 * Make sure all system apps that we expected to appear on
2430                 * the userdata partition actually showed up. If they never
2431                 * appeared, crawl back and revive the system version.
2432                 */
2433                for (int i = 0; i < mExpectingBetter.size(); i++) {
2434                    final String packageName = mExpectingBetter.keyAt(i);
2435                    if (!mPackages.containsKey(packageName)) {
2436                        final File scanFile = mExpectingBetter.valueAt(i);
2437
2438                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2439                                + " but never showed up; reverting to system");
2440
2441                        int reparseFlags = mDefParseFlags;
2442                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2443                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2444                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2445                                    | PackageParser.PARSE_IS_PRIVILEGED;
2446                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2447                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2448                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2449                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2450                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2451                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2452                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2453                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2454                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2455                        } else {
2456                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2457                            continue;
2458                        }
2459
2460                        mSettings.enableSystemPackageLPw(packageName);
2461
2462                        try {
2463                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2464                        } catch (PackageManagerException e) {
2465                            Slog.e(TAG, "Failed to parse original system package: "
2466                                    + e.getMessage());
2467                        }
2468                    }
2469                }
2470            }
2471            mExpectingBetter.clear();
2472
2473            // Resolve the storage manager.
2474            mStorageManagerPackage = getStorageManagerPackageName();
2475
2476            // Resolve protected action filters. Only the setup wizard is allowed to
2477            // have a high priority filter for these actions.
2478            mSetupWizardPackage = getSetupWizardPackageName();
2479            if (mProtectedFilters.size() > 0) {
2480                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2481                    Slog.i(TAG, "No setup wizard;"
2482                        + " All protected intents capped to priority 0");
2483                }
2484                for (ActivityIntentInfo filter : mProtectedFilters) {
2485                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2486                        if (DEBUG_FILTERS) {
2487                            Slog.i(TAG, "Found setup wizard;"
2488                                + " allow priority " + filter.getPriority() + ";"
2489                                + " package: " + filter.activity.info.packageName
2490                                + " activity: " + filter.activity.className
2491                                + " priority: " + filter.getPriority());
2492                        }
2493                        // skip setup wizard; allow it to keep the high priority filter
2494                        continue;
2495                    }
2496                    Slog.w(TAG, "Protected action; cap priority to 0;"
2497                            + " package: " + filter.activity.info.packageName
2498                            + " activity: " + filter.activity.className
2499                            + " origPrio: " + filter.getPriority());
2500                    filter.setPriority(0);
2501                }
2502            }
2503            mDeferProtectedFilters = false;
2504            mProtectedFilters.clear();
2505
2506            // Now that we know all of the shared libraries, update all clients to have
2507            // the correct library paths.
2508            updateAllSharedLibrariesLPw();
2509
2510            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2511                // NOTE: We ignore potential failures here during a system scan (like
2512                // the rest of the commands above) because there's precious little we
2513                // can do about it. A settings error is reported, though.
2514                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2515                        false /* boot complete */);
2516            }
2517
2518            // Now that we know all the packages we are keeping,
2519            // read and update their last usage times.
2520            mPackageUsage.read(mPackages);
2521            mCompilerStats.read();
2522
2523            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2524                    SystemClock.uptimeMillis());
2525            Slog.i(TAG, "Time to scan packages: "
2526                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2527                    + " seconds");
2528
2529            // If the platform SDK has changed since the last time we booted,
2530            // we need to re-grant app permission to catch any new ones that
2531            // appear.  This is really a hack, and means that apps can in some
2532            // cases get permissions that the user didn't initially explicitly
2533            // allow...  it would be nice to have some better way to handle
2534            // this situation.
2535            int updateFlags = UPDATE_PERMISSIONS_ALL;
2536            if (ver.sdkVersion != mSdkVersion) {
2537                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2538                        + mSdkVersion + "; regranting permissions for internal storage");
2539                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2540            }
2541            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2542            ver.sdkVersion = mSdkVersion;
2543
2544            // If this is the first boot or an update from pre-M, and it is a normal
2545            // boot, then we need to initialize the default preferred apps across
2546            // all defined users.
2547            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2548                for (UserInfo user : sUserManager.getUsers(true)) {
2549                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2550                    applyFactoryDefaultBrowserLPw(user.id);
2551                    primeDomainVerificationsLPw(user.id);
2552                }
2553            }
2554
2555            // Prepare storage for system user really early during boot,
2556            // since core system apps like SettingsProvider and SystemUI
2557            // can't wait for user to start
2558            final int storageFlags;
2559            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2560                storageFlags = StorageManager.FLAG_STORAGE_DE;
2561            } else {
2562                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2563            }
2564            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2565                    storageFlags);
2566
2567            // If this is first boot after an OTA, and a normal boot, then
2568            // we need to clear code cache directories.
2569            // Note that we do *not* clear the application profiles. These remain valid
2570            // across OTAs and are used to drive profile verification (post OTA) and
2571            // profile compilation (without waiting to collect a fresh set of profiles).
2572            if (mIsUpgrade && !onlyCore) {
2573                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2574                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2575                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2576                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2577                        // No apps are running this early, so no need to freeze
2578                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2579                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2580                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2581                    }
2582                }
2583                ver.fingerprint = Build.FINGERPRINT;
2584            }
2585
2586            checkDefaultBrowser();
2587
2588            // clear only after permissions and other defaults have been updated
2589            mExistingSystemPackages.clear();
2590            mPromoteSystemApps = false;
2591
2592            // All the changes are done during package scanning.
2593            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2594
2595            // can downgrade to reader
2596            mSettings.writeLPr();
2597
2598            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2599            // early on (before the package manager declares itself as early) because other
2600            // components in the system server might ask for package contexts for these apps.
2601            //
2602            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2603            // (i.e, that the data partition is unavailable).
2604            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2605                long start = System.nanoTime();
2606                List<PackageParser.Package> coreApps = new ArrayList<>();
2607                for (PackageParser.Package pkg : mPackages.values()) {
2608                    if (pkg.coreApp) {
2609                        coreApps.add(pkg);
2610                    }
2611                }
2612
2613                int[] stats = performDexOptUpgrade(coreApps, false,
2614                        getCompilerFilterForReason(REASON_CORE_APP));
2615
2616                final int elapsedTimeSeconds =
2617                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2618                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2619
2620                if (DEBUG_DEXOPT) {
2621                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2622                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2623                }
2624
2625
2626                // TODO: Should we log these stats to tron too ?
2627                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2628                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2629                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2630                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2631            }
2632
2633            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2634                    SystemClock.uptimeMillis());
2635
2636            if (!mOnlyCore) {
2637                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2638                mRequiredInstallerPackage = getRequiredInstallerLPr();
2639                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2640                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2641                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2642                        mIntentFilterVerifierComponent);
2643                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2644                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2645                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2646                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2647            } else {
2648                mRequiredVerifierPackage = null;
2649                mRequiredInstallerPackage = null;
2650                mRequiredUninstallerPackage = null;
2651                mIntentFilterVerifierComponent = null;
2652                mIntentFilterVerifier = null;
2653                mServicesSystemSharedLibraryPackageName = null;
2654                mSharedSystemSharedLibraryPackageName = null;
2655            }
2656
2657            mInstallerService = new PackageInstallerService(context, this);
2658
2659            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2660            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2661            // both the installer and resolver must be present to enable ephemeral
2662            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2663                if (DEBUG_EPHEMERAL) {
2664                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2665                            + " installer:" + ephemeralInstallerComponent);
2666                }
2667                mEphemeralResolverComponent = ephemeralResolverComponent;
2668                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2669                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2670                mEphemeralResolverConnection =
2671                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2672            } else {
2673                if (DEBUG_EPHEMERAL) {
2674                    final String missingComponent =
2675                            (ephemeralResolverComponent == null)
2676                            ? (ephemeralInstallerComponent == null)
2677                                    ? "resolver and installer"
2678                                    : "resolver"
2679                            : "installer";
2680                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2681                }
2682                mEphemeralResolverComponent = null;
2683                mEphemeralInstallerComponent = null;
2684                mEphemeralResolverConnection = null;
2685            }
2686
2687            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2688        } // synchronized (mPackages)
2689        } // synchronized (mInstallLock)
2690
2691        // Now after opening every single application zip, make sure they
2692        // are all flushed.  Not really needed, but keeps things nice and
2693        // tidy.
2694        Runtime.getRuntime().gc();
2695
2696        // The initial scanning above does many calls into installd while
2697        // holding the mPackages lock, but we're mostly interested in yelling
2698        // once we have a booted system.
2699        mInstaller.setWarnIfHeld(mPackages);
2700
2701        // Expose private service for system components to use.
2702        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2703    }
2704
2705    @Override
2706    public boolean isFirstBoot() {
2707        return mFirstBoot;
2708    }
2709
2710    @Override
2711    public boolean isOnlyCoreApps() {
2712        return mOnlyCore;
2713    }
2714
2715    @Override
2716    public boolean isUpgrade() {
2717        return mIsUpgrade;
2718    }
2719
2720    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2721        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2722
2723        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2724                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2725                UserHandle.USER_SYSTEM);
2726        if (matches.size() == 1) {
2727            return matches.get(0).getComponentInfo().packageName;
2728        } else if (matches.size() == 0) {
2729            Log.e(TAG, "There should probably be a verifier, but, none were found");
2730            return null;
2731        }
2732        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2733    }
2734
2735    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2736        synchronized (mPackages) {
2737            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2738            if (libraryEntry == null) {
2739                throw new IllegalStateException("Missing required shared library:" + libraryName);
2740            }
2741            return libraryEntry.apk;
2742        }
2743    }
2744
2745    private @NonNull String getRequiredInstallerLPr() {
2746        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2747        intent.addCategory(Intent.CATEGORY_DEFAULT);
2748        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2749
2750        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2751                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2752                UserHandle.USER_SYSTEM);
2753        if (matches.size() == 1) {
2754            ResolveInfo resolveInfo = matches.get(0);
2755            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2756                throw new RuntimeException("The installer must be a privileged app");
2757            }
2758            return matches.get(0).getComponentInfo().packageName;
2759        } else {
2760            throw new RuntimeException("There must be exactly one installer; found " + matches);
2761        }
2762    }
2763
2764    private @NonNull String getRequiredUninstallerLPr() {
2765        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2766        intent.addCategory(Intent.CATEGORY_DEFAULT);
2767        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2768
2769        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2770                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2771                UserHandle.USER_SYSTEM);
2772        if (resolveInfo == null ||
2773                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2774            throw new RuntimeException("There must be exactly one uninstaller; found "
2775                    + resolveInfo);
2776        }
2777        return resolveInfo.getComponentInfo().packageName;
2778    }
2779
2780    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2781        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2782
2783        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2784                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2785                UserHandle.USER_SYSTEM);
2786        ResolveInfo best = null;
2787        final int N = matches.size();
2788        for (int i = 0; i < N; i++) {
2789            final ResolveInfo cur = matches.get(i);
2790            final String packageName = cur.getComponentInfo().packageName;
2791            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2792                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2793                continue;
2794            }
2795
2796            if (best == null || cur.priority > best.priority) {
2797                best = cur;
2798            }
2799        }
2800
2801        if (best != null) {
2802            return best.getComponentInfo().getComponentName();
2803        } else {
2804            throw new RuntimeException("There must be at least one intent filter verifier");
2805        }
2806    }
2807
2808    private @Nullable ComponentName getEphemeralResolverLPr() {
2809        final String[] packageArray =
2810                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2811        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2812            if (DEBUG_EPHEMERAL) {
2813                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2814            }
2815            return null;
2816        }
2817
2818        final int resolveFlags =
2819                MATCH_DIRECT_BOOT_AWARE
2820                | MATCH_DIRECT_BOOT_UNAWARE
2821                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2822        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2823        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2824                resolveFlags, UserHandle.USER_SYSTEM);
2825
2826        final int N = resolvers.size();
2827        if (N == 0) {
2828            if (DEBUG_EPHEMERAL) {
2829                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2830            }
2831            return null;
2832        }
2833
2834        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2835        for (int i = 0; i < N; i++) {
2836            final ResolveInfo info = resolvers.get(i);
2837
2838            if (info.serviceInfo == null) {
2839                continue;
2840            }
2841
2842            final String packageName = info.serviceInfo.packageName;
2843            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2844                if (DEBUG_EPHEMERAL) {
2845                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2846                            + " pkg: " + packageName + ", info:" + info);
2847                }
2848                continue;
2849            }
2850
2851            if (DEBUG_EPHEMERAL) {
2852                Slog.v(TAG, "Ephemeral resolver found;"
2853                        + " pkg: " + packageName + ", info:" + info);
2854            }
2855            return new ComponentName(packageName, info.serviceInfo.name);
2856        }
2857        if (DEBUG_EPHEMERAL) {
2858            Slog.v(TAG, "Ephemeral resolver NOT found");
2859        }
2860        return null;
2861    }
2862
2863    private @Nullable ComponentName getEphemeralInstallerLPr() {
2864        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2865        intent.addCategory(Intent.CATEGORY_DEFAULT);
2866        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2867
2868        final int resolveFlags =
2869                MATCH_DIRECT_BOOT_AWARE
2870                | MATCH_DIRECT_BOOT_UNAWARE
2871                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2872        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2873                resolveFlags, UserHandle.USER_SYSTEM);
2874        if (matches.size() == 0) {
2875            return null;
2876        } else if (matches.size() == 1) {
2877            return matches.get(0).getComponentInfo().getComponentName();
2878        } else {
2879            throw new RuntimeException(
2880                    "There must be at most one ephemeral installer; found " + matches);
2881        }
2882    }
2883
2884    private void primeDomainVerificationsLPw(int userId) {
2885        if (DEBUG_DOMAIN_VERIFICATION) {
2886            Slog.d(TAG, "Priming domain verifications in user " + userId);
2887        }
2888
2889        SystemConfig systemConfig = SystemConfig.getInstance();
2890        ArraySet<String> packages = systemConfig.getLinkedApps();
2891        ArraySet<String> domains = new ArraySet<String>();
2892
2893        for (String packageName : packages) {
2894            PackageParser.Package pkg = mPackages.get(packageName);
2895            if (pkg != null) {
2896                if (!pkg.isSystemApp()) {
2897                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2898                    continue;
2899                }
2900
2901                domains.clear();
2902                for (PackageParser.Activity a : pkg.activities) {
2903                    for (ActivityIntentInfo filter : a.intents) {
2904                        if (hasValidDomains(filter)) {
2905                            domains.addAll(filter.getHostsList());
2906                        }
2907                    }
2908                }
2909
2910                if (domains.size() > 0) {
2911                    if (DEBUG_DOMAIN_VERIFICATION) {
2912                        Slog.v(TAG, "      + " + packageName);
2913                    }
2914                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2915                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2916                    // and then 'always' in the per-user state actually used for intent resolution.
2917                    final IntentFilterVerificationInfo ivi;
2918                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2919                            new ArrayList<String>(domains));
2920                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2921                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2922                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2923                } else {
2924                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2925                            + "' does not handle web links");
2926                }
2927            } else {
2928                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2929            }
2930        }
2931
2932        scheduleWritePackageRestrictionsLocked(userId);
2933        scheduleWriteSettingsLocked();
2934    }
2935
2936    private void applyFactoryDefaultBrowserLPw(int userId) {
2937        // The default browser app's package name is stored in a string resource,
2938        // with a product-specific overlay used for vendor customization.
2939        String browserPkg = mContext.getResources().getString(
2940                com.android.internal.R.string.default_browser);
2941        if (!TextUtils.isEmpty(browserPkg)) {
2942            // non-empty string => required to be a known package
2943            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2944            if (ps == null) {
2945                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2946                browserPkg = null;
2947            } else {
2948                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2949            }
2950        }
2951
2952        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2953        // default.  If there's more than one, just leave everything alone.
2954        if (browserPkg == null) {
2955            calculateDefaultBrowserLPw(userId);
2956        }
2957    }
2958
2959    private void calculateDefaultBrowserLPw(int userId) {
2960        List<String> allBrowsers = resolveAllBrowserApps(userId);
2961        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2962        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2963    }
2964
2965    private List<String> resolveAllBrowserApps(int userId) {
2966        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2967        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2968                PackageManager.MATCH_ALL, userId);
2969
2970        final int count = list.size();
2971        List<String> result = new ArrayList<String>(count);
2972        for (int i=0; i<count; i++) {
2973            ResolveInfo info = list.get(i);
2974            if (info.activityInfo == null
2975                    || !info.handleAllWebDataURI
2976                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2977                    || result.contains(info.activityInfo.packageName)) {
2978                continue;
2979            }
2980            result.add(info.activityInfo.packageName);
2981        }
2982
2983        return result;
2984    }
2985
2986    private boolean packageIsBrowser(String packageName, int userId) {
2987        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2988                PackageManager.MATCH_ALL, userId);
2989        final int N = list.size();
2990        for (int i = 0; i < N; i++) {
2991            ResolveInfo info = list.get(i);
2992            if (packageName.equals(info.activityInfo.packageName)) {
2993                return true;
2994            }
2995        }
2996        return false;
2997    }
2998
2999    private void checkDefaultBrowser() {
3000        final int myUserId = UserHandle.myUserId();
3001        final String packageName = getDefaultBrowserPackageName(myUserId);
3002        if (packageName != null) {
3003            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3004            if (info == null) {
3005                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3006                synchronized (mPackages) {
3007                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3008                }
3009            }
3010        }
3011    }
3012
3013    @Override
3014    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3015            throws RemoteException {
3016        try {
3017            return super.onTransact(code, data, reply, flags);
3018        } catch (RuntimeException e) {
3019            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3020                Slog.wtf(TAG, "Package Manager Crash", e);
3021            }
3022            throw e;
3023        }
3024    }
3025
3026    static int[] appendInts(int[] cur, int[] add) {
3027        if (add == null) return cur;
3028        if (cur == null) return add;
3029        final int N = add.length;
3030        for (int i=0; i<N; i++) {
3031            cur = appendInt(cur, add[i]);
3032        }
3033        return cur;
3034    }
3035
3036    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3037        if (!sUserManager.exists(userId)) return null;
3038        if (ps == null) {
3039            return null;
3040        }
3041        final PackageParser.Package p = ps.pkg;
3042        if (p == null) {
3043            return null;
3044        }
3045
3046        final PermissionsState permissionsState = ps.getPermissionsState();
3047
3048        // Compute GIDs only if requested
3049        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3050                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3051        // Compute granted permissions only if package has requested permissions
3052        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3053                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3054        final PackageUserState state = ps.readUserState(userId);
3055
3056        return PackageParser.generatePackageInfo(p, gids, flags,
3057                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3058    }
3059
3060    @Override
3061    public void checkPackageStartable(String packageName, int userId) {
3062        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3063
3064        synchronized (mPackages) {
3065            final PackageSetting ps = mSettings.mPackages.get(packageName);
3066            if (ps == null) {
3067                throw new SecurityException("Package " + packageName + " was not found!");
3068            }
3069
3070            if (!ps.getInstalled(userId)) {
3071                throw new SecurityException(
3072                        "Package " + packageName + " was not installed for user " + userId + "!");
3073            }
3074
3075            if (mSafeMode && !ps.isSystem()) {
3076                throw new SecurityException("Package " + packageName + " not a system app!");
3077            }
3078
3079            if (mFrozenPackages.contains(packageName)) {
3080                throw new SecurityException("Package " + packageName + " is currently frozen!");
3081            }
3082
3083            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3084                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3085                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3086            }
3087        }
3088    }
3089
3090    @Override
3091    public boolean isPackageAvailable(String packageName, int userId) {
3092        if (!sUserManager.exists(userId)) return false;
3093        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3094                false /* requireFullPermission */, false /* checkShell */, "is package available");
3095        synchronized (mPackages) {
3096            PackageParser.Package p = mPackages.get(packageName);
3097            if (p != null) {
3098                final PackageSetting ps = (PackageSetting) p.mExtras;
3099                if (ps != null) {
3100                    final PackageUserState state = ps.readUserState(userId);
3101                    if (state != null) {
3102                        return PackageParser.isAvailable(state);
3103                    }
3104                }
3105            }
3106        }
3107        return false;
3108    }
3109
3110    @Override
3111    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3112        if (!sUserManager.exists(userId)) return null;
3113        flags = updateFlagsForPackage(flags, userId, packageName);
3114        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3115                false /* requireFullPermission */, false /* checkShell */, "get package info");
3116        // reader
3117        synchronized (mPackages) {
3118            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3119            PackageParser.Package p = null;
3120            if (matchFactoryOnly) {
3121                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3122                if (ps != null) {
3123                    return generatePackageInfo(ps, flags, userId);
3124                }
3125            }
3126            if (p == null) {
3127                p = mPackages.get(packageName);
3128                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3129                    return null;
3130                }
3131            }
3132            if (DEBUG_PACKAGE_INFO)
3133                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3134            if (p != null) {
3135                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3136            }
3137            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3138                final PackageSetting ps = mSettings.mPackages.get(packageName);
3139                return generatePackageInfo(ps, flags, userId);
3140            }
3141        }
3142        return null;
3143    }
3144
3145    @Override
3146    public String[] currentToCanonicalPackageNames(String[] names) {
3147        String[] out = new String[names.length];
3148        // reader
3149        synchronized (mPackages) {
3150            for (int i=names.length-1; i>=0; i--) {
3151                PackageSetting ps = mSettings.mPackages.get(names[i]);
3152                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3153            }
3154        }
3155        return out;
3156    }
3157
3158    @Override
3159    public String[] canonicalToCurrentPackageNames(String[] names) {
3160        String[] out = new String[names.length];
3161        // reader
3162        synchronized (mPackages) {
3163            for (int i=names.length-1; i>=0; i--) {
3164                String cur = mSettings.mRenamedPackages.get(names[i]);
3165                out[i] = cur != null ? cur : names[i];
3166            }
3167        }
3168        return out;
3169    }
3170
3171    @Override
3172    public int getPackageUid(String packageName, int flags, int userId) {
3173        if (!sUserManager.exists(userId)) return -1;
3174        flags = updateFlagsForPackage(flags, userId, packageName);
3175        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3176                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3177
3178        // reader
3179        synchronized (mPackages) {
3180            final PackageParser.Package p = mPackages.get(packageName);
3181            if (p != null && p.isMatch(flags)) {
3182                return UserHandle.getUid(userId, p.applicationInfo.uid);
3183            }
3184            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3185                final PackageSetting ps = mSettings.mPackages.get(packageName);
3186                if (ps != null && ps.isMatch(flags)) {
3187                    return UserHandle.getUid(userId, ps.appId);
3188                }
3189            }
3190        }
3191
3192        return -1;
3193    }
3194
3195    @Override
3196    public int[] getPackageGids(String packageName, int flags, int userId) {
3197        if (!sUserManager.exists(userId)) return null;
3198        flags = updateFlagsForPackage(flags, userId, packageName);
3199        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3200                false /* requireFullPermission */, false /* checkShell */,
3201                "getPackageGids");
3202
3203        // reader
3204        synchronized (mPackages) {
3205            final PackageParser.Package p = mPackages.get(packageName);
3206            if (p != null && p.isMatch(flags)) {
3207                PackageSetting ps = (PackageSetting) p.mExtras;
3208                return ps.getPermissionsState().computeGids(userId);
3209            }
3210            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3211                final PackageSetting ps = mSettings.mPackages.get(packageName);
3212                if (ps != null && ps.isMatch(flags)) {
3213                    return ps.getPermissionsState().computeGids(userId);
3214                }
3215            }
3216        }
3217
3218        return null;
3219    }
3220
3221    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3222        if (bp.perm != null) {
3223            return PackageParser.generatePermissionInfo(bp.perm, flags);
3224        }
3225        PermissionInfo pi = new PermissionInfo();
3226        pi.name = bp.name;
3227        pi.packageName = bp.sourcePackage;
3228        pi.nonLocalizedLabel = bp.name;
3229        pi.protectionLevel = bp.protectionLevel;
3230        return pi;
3231    }
3232
3233    @Override
3234    public PermissionInfo getPermissionInfo(String name, int flags) {
3235        // reader
3236        synchronized (mPackages) {
3237            final BasePermission p = mSettings.mPermissions.get(name);
3238            if (p != null) {
3239                return generatePermissionInfo(p, flags);
3240            }
3241            return null;
3242        }
3243    }
3244
3245    @Override
3246    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3247            int flags) {
3248        // reader
3249        synchronized (mPackages) {
3250            if (group != null && !mPermissionGroups.containsKey(group)) {
3251                // This is thrown as NameNotFoundException
3252                return null;
3253            }
3254
3255            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3256            for (BasePermission p : mSettings.mPermissions.values()) {
3257                if (group == null) {
3258                    if (p.perm == null || p.perm.info.group == null) {
3259                        out.add(generatePermissionInfo(p, flags));
3260                    }
3261                } else {
3262                    if (p.perm != null && group.equals(p.perm.info.group)) {
3263                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3264                    }
3265                }
3266            }
3267            return new ParceledListSlice<>(out);
3268        }
3269    }
3270
3271    @Override
3272    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3273        // reader
3274        synchronized (mPackages) {
3275            return PackageParser.generatePermissionGroupInfo(
3276                    mPermissionGroups.get(name), flags);
3277        }
3278    }
3279
3280    @Override
3281    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3282        // reader
3283        synchronized (mPackages) {
3284            final int N = mPermissionGroups.size();
3285            ArrayList<PermissionGroupInfo> out
3286                    = new ArrayList<PermissionGroupInfo>(N);
3287            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3288                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3289            }
3290            return new ParceledListSlice<>(out);
3291        }
3292    }
3293
3294    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3295            int userId) {
3296        if (!sUserManager.exists(userId)) return null;
3297        PackageSetting ps = mSettings.mPackages.get(packageName);
3298        if (ps != null) {
3299            if (ps.pkg == null) {
3300                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3301                if (pInfo != null) {
3302                    return pInfo.applicationInfo;
3303                }
3304                return null;
3305            }
3306            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3307                    ps.readUserState(userId), userId);
3308        }
3309        return null;
3310    }
3311
3312    @Override
3313    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3314        if (!sUserManager.exists(userId)) return null;
3315        flags = updateFlagsForApplication(flags, userId, packageName);
3316        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3317                false /* requireFullPermission */, false /* checkShell */, "get application info");
3318        // writer
3319        synchronized (mPackages) {
3320            PackageParser.Package p = mPackages.get(packageName);
3321            if (DEBUG_PACKAGE_INFO) Log.v(
3322                    TAG, "getApplicationInfo " + packageName
3323                    + ": " + p);
3324            if (p != null) {
3325                PackageSetting ps = mSettings.mPackages.get(packageName);
3326                if (ps == null) return null;
3327                // Note: isEnabledLP() does not apply here - always return info
3328                return PackageParser.generateApplicationInfo(
3329                        p, flags, ps.readUserState(userId), userId);
3330            }
3331            if ("android".equals(packageName)||"system".equals(packageName)) {
3332                return mAndroidApplication;
3333            }
3334            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3335                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3336            }
3337        }
3338        return null;
3339    }
3340
3341    @Override
3342    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3343            final IPackageDataObserver observer) {
3344        mContext.enforceCallingOrSelfPermission(
3345                android.Manifest.permission.CLEAR_APP_CACHE, null);
3346        // Queue up an async operation since clearing cache may take a little while.
3347        mHandler.post(new Runnable() {
3348            public void run() {
3349                mHandler.removeCallbacks(this);
3350                boolean success = true;
3351                synchronized (mInstallLock) {
3352                    try {
3353                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3354                    } catch (InstallerException e) {
3355                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3356                        success = false;
3357                    }
3358                }
3359                if (observer != null) {
3360                    try {
3361                        observer.onRemoveCompleted(null, success);
3362                    } catch (RemoteException e) {
3363                        Slog.w(TAG, "RemoveException when invoking call back");
3364                    }
3365                }
3366            }
3367        });
3368    }
3369
3370    @Override
3371    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3372            final IntentSender pi) {
3373        mContext.enforceCallingOrSelfPermission(
3374                android.Manifest.permission.CLEAR_APP_CACHE, null);
3375        // Queue up an async operation since clearing cache may take a little while.
3376        mHandler.post(new Runnable() {
3377            public void run() {
3378                mHandler.removeCallbacks(this);
3379                boolean success = true;
3380                synchronized (mInstallLock) {
3381                    try {
3382                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3383                    } catch (InstallerException e) {
3384                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3385                        success = false;
3386                    }
3387                }
3388                if(pi != null) {
3389                    try {
3390                        // Callback via pending intent
3391                        int code = success ? 1 : 0;
3392                        pi.sendIntent(null, code, null,
3393                                null, null);
3394                    } catch (SendIntentException e1) {
3395                        Slog.i(TAG, "Failed to send pending intent");
3396                    }
3397                }
3398            }
3399        });
3400    }
3401
3402    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3403        synchronized (mInstallLock) {
3404            try {
3405                mInstaller.freeCache(volumeUuid, freeStorageSize);
3406            } catch (InstallerException e) {
3407                throw new IOException("Failed to free enough space", e);
3408            }
3409        }
3410    }
3411
3412    /**
3413     * Update given flags based on encryption status of current user.
3414     */
3415    private int updateFlags(int flags, int userId) {
3416        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3417                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3418            // Caller expressed an explicit opinion about what encryption
3419            // aware/unaware components they want to see, so fall through and
3420            // give them what they want
3421        } else {
3422            // Caller expressed no opinion, so match based on user state
3423            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3424                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3425            } else {
3426                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3427            }
3428        }
3429        return flags;
3430    }
3431
3432    private UserManagerInternal getUserManagerInternal() {
3433        if (mUserManagerInternal == null) {
3434            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3435        }
3436        return mUserManagerInternal;
3437    }
3438
3439    /**
3440     * Update given flags when being used to request {@link PackageInfo}.
3441     */
3442    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3443        boolean triaged = true;
3444        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3445                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3446            // Caller is asking for component details, so they'd better be
3447            // asking for specific encryption matching behavior, or be triaged
3448            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3449                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3450                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3451                triaged = false;
3452            }
3453        }
3454        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3455                | PackageManager.MATCH_SYSTEM_ONLY
3456                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3457            triaged = false;
3458        }
3459        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3460            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3461                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3462        }
3463        return updateFlags(flags, userId);
3464    }
3465
3466    /**
3467     * Update given flags when being used to request {@link ApplicationInfo}.
3468     */
3469    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3470        return updateFlagsForPackage(flags, userId, cookie);
3471    }
3472
3473    /**
3474     * Update given flags when being used to request {@link ComponentInfo}.
3475     */
3476    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3477        if (cookie instanceof Intent) {
3478            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3479                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3480            }
3481        }
3482
3483        boolean triaged = true;
3484        // Caller is asking for component details, so they'd better be
3485        // asking for specific encryption matching behavior, or be triaged
3486        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3487                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3488                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3489            triaged = false;
3490        }
3491        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3492            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3493                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3494        }
3495
3496        return updateFlags(flags, userId);
3497    }
3498
3499    /**
3500     * Update given flags when being used to request {@link ResolveInfo}.
3501     */
3502    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3503        // Safe mode means we shouldn't match any third-party components
3504        if (mSafeMode) {
3505            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3506        }
3507
3508        return updateFlagsForComponent(flags, userId, cookie);
3509    }
3510
3511    @Override
3512    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3513        if (!sUserManager.exists(userId)) return null;
3514        flags = updateFlagsForComponent(flags, userId, component);
3515        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3516                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3517        synchronized (mPackages) {
3518            PackageParser.Activity a = mActivities.mActivities.get(component);
3519
3520            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3521            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3522                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3523                if (ps == null) return null;
3524                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3525                        userId);
3526            }
3527            if (mResolveComponentName.equals(component)) {
3528                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3529                        new PackageUserState(), userId);
3530            }
3531        }
3532        return null;
3533    }
3534
3535    @Override
3536    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3537            String resolvedType) {
3538        synchronized (mPackages) {
3539            if (component.equals(mResolveComponentName)) {
3540                // The resolver supports EVERYTHING!
3541                return true;
3542            }
3543            PackageParser.Activity a = mActivities.mActivities.get(component);
3544            if (a == null) {
3545                return false;
3546            }
3547            for (int i=0; i<a.intents.size(); i++) {
3548                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3549                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3550                    return true;
3551                }
3552            }
3553            return false;
3554        }
3555    }
3556
3557    @Override
3558    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3559        if (!sUserManager.exists(userId)) return null;
3560        flags = updateFlagsForComponent(flags, userId, component);
3561        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3562                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3563        synchronized (mPackages) {
3564            PackageParser.Activity a = mReceivers.mActivities.get(component);
3565            if (DEBUG_PACKAGE_INFO) Log.v(
3566                TAG, "getReceiverInfo " + component + ": " + a);
3567            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3568                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3569                if (ps == null) return null;
3570                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3571                        userId);
3572            }
3573        }
3574        return null;
3575    }
3576
3577    @Override
3578    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3579        if (!sUserManager.exists(userId)) return null;
3580        flags = updateFlagsForComponent(flags, userId, component);
3581        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3582                false /* requireFullPermission */, false /* checkShell */, "get service info");
3583        synchronized (mPackages) {
3584            PackageParser.Service s = mServices.mServices.get(component);
3585            if (DEBUG_PACKAGE_INFO) Log.v(
3586                TAG, "getServiceInfo " + component + ": " + s);
3587            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3588                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3589                if (ps == null) return null;
3590                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3591                        userId);
3592            }
3593        }
3594        return null;
3595    }
3596
3597    @Override
3598    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3599        if (!sUserManager.exists(userId)) return null;
3600        flags = updateFlagsForComponent(flags, userId, component);
3601        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3602                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3603        synchronized (mPackages) {
3604            PackageParser.Provider p = mProviders.mProviders.get(component);
3605            if (DEBUG_PACKAGE_INFO) Log.v(
3606                TAG, "getProviderInfo " + component + ": " + p);
3607            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3608                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3609                if (ps == null) return null;
3610                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3611                        userId);
3612            }
3613        }
3614        return null;
3615    }
3616
3617    @Override
3618    public String[] getSystemSharedLibraryNames() {
3619        Set<String> libSet;
3620        synchronized (mPackages) {
3621            libSet = mSharedLibraries.keySet();
3622            int size = libSet.size();
3623            if (size > 0) {
3624                String[] libs = new String[size];
3625                libSet.toArray(libs);
3626                return libs;
3627            }
3628        }
3629        return null;
3630    }
3631
3632    @Override
3633    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3634        synchronized (mPackages) {
3635            return mServicesSystemSharedLibraryPackageName;
3636        }
3637    }
3638
3639    @Override
3640    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3641        synchronized (mPackages) {
3642            return mSharedSystemSharedLibraryPackageName;
3643        }
3644    }
3645
3646    @Override
3647    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3648        synchronized (mPackages) {
3649            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3650
3651            final FeatureInfo fi = new FeatureInfo();
3652            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3653                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3654            res.add(fi);
3655
3656            return new ParceledListSlice<>(res);
3657        }
3658    }
3659
3660    @Override
3661    public boolean hasSystemFeature(String name, int version) {
3662        synchronized (mPackages) {
3663            final FeatureInfo feat = mAvailableFeatures.get(name);
3664            if (feat == null) {
3665                return false;
3666            } else {
3667                return feat.version >= version;
3668            }
3669        }
3670    }
3671
3672    @Override
3673    public int checkPermission(String permName, String pkgName, int userId) {
3674        if (!sUserManager.exists(userId)) {
3675            return PackageManager.PERMISSION_DENIED;
3676        }
3677
3678        synchronized (mPackages) {
3679            final PackageParser.Package p = mPackages.get(pkgName);
3680            if (p != null && p.mExtras != null) {
3681                final PackageSetting ps = (PackageSetting) p.mExtras;
3682                final PermissionsState permissionsState = ps.getPermissionsState();
3683                if (permissionsState.hasPermission(permName, userId)) {
3684                    return PackageManager.PERMISSION_GRANTED;
3685                }
3686                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3687                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3688                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3689                    return PackageManager.PERMISSION_GRANTED;
3690                }
3691            }
3692        }
3693
3694        return PackageManager.PERMISSION_DENIED;
3695    }
3696
3697    @Override
3698    public int checkUidPermission(String permName, int uid) {
3699        final int userId = UserHandle.getUserId(uid);
3700
3701        if (!sUserManager.exists(userId)) {
3702            return PackageManager.PERMISSION_DENIED;
3703        }
3704
3705        synchronized (mPackages) {
3706            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3707            if (obj != null) {
3708                final SettingBase ps = (SettingBase) obj;
3709                final PermissionsState permissionsState = ps.getPermissionsState();
3710                if (permissionsState.hasPermission(permName, userId)) {
3711                    return PackageManager.PERMISSION_GRANTED;
3712                }
3713                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3714                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3715                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3716                    return PackageManager.PERMISSION_GRANTED;
3717                }
3718            } else {
3719                ArraySet<String> perms = mSystemPermissions.get(uid);
3720                if (perms != null) {
3721                    if (perms.contains(permName)) {
3722                        return PackageManager.PERMISSION_GRANTED;
3723                    }
3724                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3725                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3726                        return PackageManager.PERMISSION_GRANTED;
3727                    }
3728                }
3729            }
3730        }
3731
3732        return PackageManager.PERMISSION_DENIED;
3733    }
3734
3735    @Override
3736    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3737        if (UserHandle.getCallingUserId() != userId) {
3738            mContext.enforceCallingPermission(
3739                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3740                    "isPermissionRevokedByPolicy for user " + userId);
3741        }
3742
3743        if (checkPermission(permission, packageName, userId)
3744                == PackageManager.PERMISSION_GRANTED) {
3745            return false;
3746        }
3747
3748        final long identity = Binder.clearCallingIdentity();
3749        try {
3750            final int flags = getPermissionFlags(permission, packageName, userId);
3751            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3752        } finally {
3753            Binder.restoreCallingIdentity(identity);
3754        }
3755    }
3756
3757    @Override
3758    public String getPermissionControllerPackageName() {
3759        synchronized (mPackages) {
3760            return mRequiredInstallerPackage;
3761        }
3762    }
3763
3764    /**
3765     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3766     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3767     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3768     * @param message the message to log on security exception
3769     */
3770    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3771            boolean checkShell, String message) {
3772        if (userId < 0) {
3773            throw new IllegalArgumentException("Invalid userId " + userId);
3774        }
3775        if (checkShell) {
3776            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3777        }
3778        if (userId == UserHandle.getUserId(callingUid)) return;
3779        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3780            if (requireFullPermission) {
3781                mContext.enforceCallingOrSelfPermission(
3782                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3783            } else {
3784                try {
3785                    mContext.enforceCallingOrSelfPermission(
3786                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3787                } catch (SecurityException se) {
3788                    mContext.enforceCallingOrSelfPermission(
3789                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3790                }
3791            }
3792        }
3793    }
3794
3795    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3796        if (callingUid == Process.SHELL_UID) {
3797            if (userHandle >= 0
3798                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3799                throw new SecurityException("Shell does not have permission to access user "
3800                        + userHandle);
3801            } else if (userHandle < 0) {
3802                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3803                        + Debug.getCallers(3));
3804            }
3805        }
3806    }
3807
3808    private BasePermission findPermissionTreeLP(String permName) {
3809        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3810            if (permName.startsWith(bp.name) &&
3811                    permName.length() > bp.name.length() &&
3812                    permName.charAt(bp.name.length()) == '.') {
3813                return bp;
3814            }
3815        }
3816        return null;
3817    }
3818
3819    private BasePermission checkPermissionTreeLP(String permName) {
3820        if (permName != null) {
3821            BasePermission bp = findPermissionTreeLP(permName);
3822            if (bp != null) {
3823                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3824                    return bp;
3825                }
3826                throw new SecurityException("Calling uid "
3827                        + Binder.getCallingUid()
3828                        + " is not allowed to add to permission tree "
3829                        + bp.name + " owned by uid " + bp.uid);
3830            }
3831        }
3832        throw new SecurityException("No permission tree found for " + permName);
3833    }
3834
3835    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3836        if (s1 == null) {
3837            return s2 == null;
3838        }
3839        if (s2 == null) {
3840            return false;
3841        }
3842        if (s1.getClass() != s2.getClass()) {
3843            return false;
3844        }
3845        return s1.equals(s2);
3846    }
3847
3848    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3849        if (pi1.icon != pi2.icon) return false;
3850        if (pi1.logo != pi2.logo) return false;
3851        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3852        if (!compareStrings(pi1.name, pi2.name)) return false;
3853        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3854        // We'll take care of setting this one.
3855        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3856        // These are not currently stored in settings.
3857        //if (!compareStrings(pi1.group, pi2.group)) return false;
3858        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3859        //if (pi1.labelRes != pi2.labelRes) return false;
3860        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3861        return true;
3862    }
3863
3864    int permissionInfoFootprint(PermissionInfo info) {
3865        int size = info.name.length();
3866        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3867        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3868        return size;
3869    }
3870
3871    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3872        int size = 0;
3873        for (BasePermission perm : mSettings.mPermissions.values()) {
3874            if (perm.uid == tree.uid) {
3875                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3876            }
3877        }
3878        return size;
3879    }
3880
3881    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3882        // We calculate the max size of permissions defined by this uid and throw
3883        // if that plus the size of 'info' would exceed our stated maximum.
3884        if (tree.uid != Process.SYSTEM_UID) {
3885            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3886            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3887                throw new SecurityException("Permission tree size cap exceeded");
3888            }
3889        }
3890    }
3891
3892    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3893        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3894            throw new SecurityException("Label must be specified in permission");
3895        }
3896        BasePermission tree = checkPermissionTreeLP(info.name);
3897        BasePermission bp = mSettings.mPermissions.get(info.name);
3898        boolean added = bp == null;
3899        boolean changed = true;
3900        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3901        if (added) {
3902            enforcePermissionCapLocked(info, tree);
3903            bp = new BasePermission(info.name, tree.sourcePackage,
3904                    BasePermission.TYPE_DYNAMIC);
3905        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3906            throw new SecurityException(
3907                    "Not allowed to modify non-dynamic permission "
3908                    + info.name);
3909        } else {
3910            if (bp.protectionLevel == fixedLevel
3911                    && bp.perm.owner.equals(tree.perm.owner)
3912                    && bp.uid == tree.uid
3913                    && comparePermissionInfos(bp.perm.info, info)) {
3914                changed = false;
3915            }
3916        }
3917        bp.protectionLevel = fixedLevel;
3918        info = new PermissionInfo(info);
3919        info.protectionLevel = fixedLevel;
3920        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3921        bp.perm.info.packageName = tree.perm.info.packageName;
3922        bp.uid = tree.uid;
3923        if (added) {
3924            mSettings.mPermissions.put(info.name, bp);
3925        }
3926        if (changed) {
3927            if (!async) {
3928                mSettings.writeLPr();
3929            } else {
3930                scheduleWriteSettingsLocked();
3931            }
3932        }
3933        return added;
3934    }
3935
3936    @Override
3937    public boolean addPermission(PermissionInfo info) {
3938        synchronized (mPackages) {
3939            return addPermissionLocked(info, false);
3940        }
3941    }
3942
3943    @Override
3944    public boolean addPermissionAsync(PermissionInfo info) {
3945        synchronized (mPackages) {
3946            return addPermissionLocked(info, true);
3947        }
3948    }
3949
3950    @Override
3951    public void removePermission(String name) {
3952        synchronized (mPackages) {
3953            checkPermissionTreeLP(name);
3954            BasePermission bp = mSettings.mPermissions.get(name);
3955            if (bp != null) {
3956                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3957                    throw new SecurityException(
3958                            "Not allowed to modify non-dynamic permission "
3959                            + name);
3960                }
3961                mSettings.mPermissions.remove(name);
3962                mSettings.writeLPr();
3963            }
3964        }
3965    }
3966
3967    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3968            BasePermission bp) {
3969        int index = pkg.requestedPermissions.indexOf(bp.name);
3970        if (index == -1) {
3971            throw new SecurityException("Package " + pkg.packageName
3972                    + " has not requested permission " + bp.name);
3973        }
3974        if (!bp.isRuntime() && !bp.isDevelopment()) {
3975            throw new SecurityException("Permission " + bp.name
3976                    + " is not a changeable permission type");
3977        }
3978    }
3979
3980    @Override
3981    public void grantRuntimePermission(String packageName, String name, final int userId) {
3982        if (!sUserManager.exists(userId)) {
3983            Log.e(TAG, "No such user:" + userId);
3984            return;
3985        }
3986
3987        mContext.enforceCallingOrSelfPermission(
3988                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3989                "grantRuntimePermission");
3990
3991        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3992                true /* requireFullPermission */, true /* checkShell */,
3993                "grantRuntimePermission");
3994
3995        final int uid;
3996        final SettingBase sb;
3997
3998        synchronized (mPackages) {
3999            final PackageParser.Package pkg = mPackages.get(packageName);
4000            if (pkg == null) {
4001                throw new IllegalArgumentException("Unknown package: " + packageName);
4002            }
4003
4004            final BasePermission bp = mSettings.mPermissions.get(name);
4005            if (bp == null) {
4006                throw new IllegalArgumentException("Unknown permission: " + name);
4007            }
4008
4009            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4010
4011            // If a permission review is required for legacy apps we represent
4012            // their permissions as always granted runtime ones since we need
4013            // to keep the review required permission flag per user while an
4014            // install permission's state is shared across all users.
4015            if (Build.PERMISSIONS_REVIEW_REQUIRED
4016                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4017                    && bp.isRuntime()) {
4018                return;
4019            }
4020
4021            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4022            sb = (SettingBase) pkg.mExtras;
4023            if (sb == null) {
4024                throw new IllegalArgumentException("Unknown package: " + packageName);
4025            }
4026
4027            final PermissionsState permissionsState = sb.getPermissionsState();
4028
4029            final int flags = permissionsState.getPermissionFlags(name, userId);
4030            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4031                throw new SecurityException("Cannot grant system fixed permission "
4032                        + name + " for package " + packageName);
4033            }
4034
4035            if (bp.isDevelopment()) {
4036                // Development permissions must be handled specially, since they are not
4037                // normal runtime permissions.  For now they apply to all users.
4038                if (permissionsState.grantInstallPermission(bp) !=
4039                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4040                    scheduleWriteSettingsLocked();
4041                }
4042                return;
4043            }
4044
4045            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4046                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4047                return;
4048            }
4049
4050            final int result = permissionsState.grantRuntimePermission(bp, userId);
4051            switch (result) {
4052                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4053                    return;
4054                }
4055
4056                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4057                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4058                    mHandler.post(new Runnable() {
4059                        @Override
4060                        public void run() {
4061                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4062                        }
4063                    });
4064                }
4065                break;
4066            }
4067
4068            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4069
4070            // Not critical if that is lost - app has to request again.
4071            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4072        }
4073
4074        // Only need to do this if user is initialized. Otherwise it's a new user
4075        // and there are no processes running as the user yet and there's no need
4076        // to make an expensive call to remount processes for the changed permissions.
4077        if (READ_EXTERNAL_STORAGE.equals(name)
4078                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4079            final long token = Binder.clearCallingIdentity();
4080            try {
4081                if (sUserManager.isInitialized(userId)) {
4082                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4083                            MountServiceInternal.class);
4084                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4085                }
4086            } finally {
4087                Binder.restoreCallingIdentity(token);
4088            }
4089        }
4090    }
4091
4092    @Override
4093    public void revokeRuntimePermission(String packageName, String name, int userId) {
4094        if (!sUserManager.exists(userId)) {
4095            Log.e(TAG, "No such user:" + userId);
4096            return;
4097        }
4098
4099        mContext.enforceCallingOrSelfPermission(
4100                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4101                "revokeRuntimePermission");
4102
4103        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4104                true /* requireFullPermission */, true /* checkShell */,
4105                "revokeRuntimePermission");
4106
4107        final int appId;
4108
4109        synchronized (mPackages) {
4110            final PackageParser.Package pkg = mPackages.get(packageName);
4111            if (pkg == null) {
4112                throw new IllegalArgumentException("Unknown package: " + packageName);
4113            }
4114
4115            final BasePermission bp = mSettings.mPermissions.get(name);
4116            if (bp == null) {
4117                throw new IllegalArgumentException("Unknown permission: " + name);
4118            }
4119
4120            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4121
4122            // If a permission review is required for legacy apps we represent
4123            // their permissions as always granted runtime ones since we need
4124            // to keep the review required permission flag per user while an
4125            // install permission's state is shared across all users.
4126            if (Build.PERMISSIONS_REVIEW_REQUIRED
4127                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4128                    && bp.isRuntime()) {
4129                return;
4130            }
4131
4132            SettingBase sb = (SettingBase) pkg.mExtras;
4133            if (sb == null) {
4134                throw new IllegalArgumentException("Unknown package: " + packageName);
4135            }
4136
4137            final PermissionsState permissionsState = sb.getPermissionsState();
4138
4139            final int flags = permissionsState.getPermissionFlags(name, userId);
4140            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4141                throw new SecurityException("Cannot revoke system fixed permission "
4142                        + name + " for package " + packageName);
4143            }
4144
4145            if (bp.isDevelopment()) {
4146                // Development permissions must be handled specially, since they are not
4147                // normal runtime permissions.  For now they apply to all users.
4148                if (permissionsState.revokeInstallPermission(bp) !=
4149                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4150                    scheduleWriteSettingsLocked();
4151                }
4152                return;
4153            }
4154
4155            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4156                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4157                return;
4158            }
4159
4160            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4161
4162            // Critical, after this call app should never have the permission.
4163            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4164
4165            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4166        }
4167
4168        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4169    }
4170
4171    @Override
4172    public void resetRuntimePermissions() {
4173        mContext.enforceCallingOrSelfPermission(
4174                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4175                "revokeRuntimePermission");
4176
4177        int callingUid = Binder.getCallingUid();
4178        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4179            mContext.enforceCallingOrSelfPermission(
4180                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4181                    "resetRuntimePermissions");
4182        }
4183
4184        synchronized (mPackages) {
4185            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4186            for (int userId : UserManagerService.getInstance().getUserIds()) {
4187                final int packageCount = mPackages.size();
4188                for (int i = 0; i < packageCount; i++) {
4189                    PackageParser.Package pkg = mPackages.valueAt(i);
4190                    if (!(pkg.mExtras instanceof PackageSetting)) {
4191                        continue;
4192                    }
4193                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4194                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4195                }
4196            }
4197        }
4198    }
4199
4200    @Override
4201    public int getPermissionFlags(String name, String packageName, int userId) {
4202        if (!sUserManager.exists(userId)) {
4203            return 0;
4204        }
4205
4206        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4207
4208        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4209                true /* requireFullPermission */, false /* checkShell */,
4210                "getPermissionFlags");
4211
4212        synchronized (mPackages) {
4213            final PackageParser.Package pkg = mPackages.get(packageName);
4214            if (pkg == null) {
4215                return 0;
4216            }
4217
4218            final BasePermission bp = mSettings.mPermissions.get(name);
4219            if (bp == null) {
4220                return 0;
4221            }
4222
4223            SettingBase sb = (SettingBase) pkg.mExtras;
4224            if (sb == null) {
4225                return 0;
4226            }
4227
4228            PermissionsState permissionsState = sb.getPermissionsState();
4229            return permissionsState.getPermissionFlags(name, userId);
4230        }
4231    }
4232
4233    @Override
4234    public void updatePermissionFlags(String name, String packageName, int flagMask,
4235            int flagValues, int userId) {
4236        if (!sUserManager.exists(userId)) {
4237            return;
4238        }
4239
4240        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4241
4242        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4243                true /* requireFullPermission */, true /* checkShell */,
4244                "updatePermissionFlags");
4245
4246        // Only the system can change these flags and nothing else.
4247        if (getCallingUid() != Process.SYSTEM_UID) {
4248            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4249            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4250            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4251            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4252            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4253        }
4254
4255        synchronized (mPackages) {
4256            final PackageParser.Package pkg = mPackages.get(packageName);
4257            if (pkg == null) {
4258                throw new IllegalArgumentException("Unknown package: " + packageName);
4259            }
4260
4261            final BasePermission bp = mSettings.mPermissions.get(name);
4262            if (bp == null) {
4263                throw new IllegalArgumentException("Unknown permission: " + name);
4264            }
4265
4266            SettingBase sb = (SettingBase) pkg.mExtras;
4267            if (sb == null) {
4268                throw new IllegalArgumentException("Unknown package: " + packageName);
4269            }
4270
4271            PermissionsState permissionsState = sb.getPermissionsState();
4272
4273            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4274
4275            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4276                // Install and runtime permissions are stored in different places,
4277                // so figure out what permission changed and persist the change.
4278                if (permissionsState.getInstallPermissionState(name) != null) {
4279                    scheduleWriteSettingsLocked();
4280                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4281                        || hadState) {
4282                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4283                }
4284            }
4285        }
4286    }
4287
4288    /**
4289     * Update the permission flags for all packages and runtime permissions of a user in order
4290     * to allow device or profile owner to remove POLICY_FIXED.
4291     */
4292    @Override
4293    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4294        if (!sUserManager.exists(userId)) {
4295            return;
4296        }
4297
4298        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4299
4300        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4301                true /* requireFullPermission */, true /* checkShell */,
4302                "updatePermissionFlagsForAllApps");
4303
4304        // Only the system can change system fixed flags.
4305        if (getCallingUid() != Process.SYSTEM_UID) {
4306            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4307            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4308        }
4309
4310        synchronized (mPackages) {
4311            boolean changed = false;
4312            final int packageCount = mPackages.size();
4313            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4314                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4315                SettingBase sb = (SettingBase) pkg.mExtras;
4316                if (sb == null) {
4317                    continue;
4318                }
4319                PermissionsState permissionsState = sb.getPermissionsState();
4320                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4321                        userId, flagMask, flagValues);
4322            }
4323            if (changed) {
4324                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4325            }
4326        }
4327    }
4328
4329    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4330        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4331                != PackageManager.PERMISSION_GRANTED
4332            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4333                != PackageManager.PERMISSION_GRANTED) {
4334            throw new SecurityException(message + " requires "
4335                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4336                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4337        }
4338    }
4339
4340    @Override
4341    public boolean shouldShowRequestPermissionRationale(String permissionName,
4342            String packageName, int userId) {
4343        if (UserHandle.getCallingUserId() != userId) {
4344            mContext.enforceCallingPermission(
4345                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4346                    "canShowRequestPermissionRationale for user " + userId);
4347        }
4348
4349        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4350        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4351            return false;
4352        }
4353
4354        if (checkPermission(permissionName, packageName, userId)
4355                == PackageManager.PERMISSION_GRANTED) {
4356            return false;
4357        }
4358
4359        final int flags;
4360
4361        final long identity = Binder.clearCallingIdentity();
4362        try {
4363            flags = getPermissionFlags(permissionName,
4364                    packageName, userId);
4365        } finally {
4366            Binder.restoreCallingIdentity(identity);
4367        }
4368
4369        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4370                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4371                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4372
4373        if ((flags & fixedFlags) != 0) {
4374            return false;
4375        }
4376
4377        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4378    }
4379
4380    @Override
4381    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4382        mContext.enforceCallingOrSelfPermission(
4383                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4384                "addOnPermissionsChangeListener");
4385
4386        synchronized (mPackages) {
4387            mOnPermissionChangeListeners.addListenerLocked(listener);
4388        }
4389    }
4390
4391    @Override
4392    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4393        synchronized (mPackages) {
4394            mOnPermissionChangeListeners.removeListenerLocked(listener);
4395        }
4396    }
4397
4398    @Override
4399    public boolean isProtectedBroadcast(String actionName) {
4400        synchronized (mPackages) {
4401            if (mProtectedBroadcasts.contains(actionName)) {
4402                return true;
4403            } else if (actionName != null) {
4404                // TODO: remove these terrible hacks
4405                if (actionName.startsWith("android.net.netmon.lingerExpired")
4406                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4407                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4408                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4409                    return true;
4410                }
4411            }
4412        }
4413        return false;
4414    }
4415
4416    @Override
4417    public int checkSignatures(String pkg1, String pkg2) {
4418        synchronized (mPackages) {
4419            final PackageParser.Package p1 = mPackages.get(pkg1);
4420            final PackageParser.Package p2 = mPackages.get(pkg2);
4421            if (p1 == null || p1.mExtras == null
4422                    || p2 == null || p2.mExtras == null) {
4423                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4424            }
4425            return compareSignatures(p1.mSignatures, p2.mSignatures);
4426        }
4427    }
4428
4429    @Override
4430    public int checkUidSignatures(int uid1, int uid2) {
4431        // Map to base uids.
4432        uid1 = UserHandle.getAppId(uid1);
4433        uid2 = UserHandle.getAppId(uid2);
4434        // reader
4435        synchronized (mPackages) {
4436            Signature[] s1;
4437            Signature[] s2;
4438            Object obj = mSettings.getUserIdLPr(uid1);
4439            if (obj != null) {
4440                if (obj instanceof SharedUserSetting) {
4441                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4442                } else if (obj instanceof PackageSetting) {
4443                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4444                } else {
4445                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4446                }
4447            } else {
4448                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4449            }
4450            obj = mSettings.getUserIdLPr(uid2);
4451            if (obj != null) {
4452                if (obj instanceof SharedUserSetting) {
4453                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4454                } else if (obj instanceof PackageSetting) {
4455                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4456                } else {
4457                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4458                }
4459            } else {
4460                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4461            }
4462            return compareSignatures(s1, s2);
4463        }
4464    }
4465
4466    /**
4467     * This method should typically only be used when granting or revoking
4468     * permissions, since the app may immediately restart after this call.
4469     * <p>
4470     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4471     * guard your work against the app being relaunched.
4472     */
4473    private void killUid(int appId, int userId, String reason) {
4474        final long identity = Binder.clearCallingIdentity();
4475        try {
4476            IActivityManager am = ActivityManagerNative.getDefault();
4477            if (am != null) {
4478                try {
4479                    am.killUid(appId, userId, reason);
4480                } catch (RemoteException e) {
4481                    /* ignore - same process */
4482                }
4483            }
4484        } finally {
4485            Binder.restoreCallingIdentity(identity);
4486        }
4487    }
4488
4489    /**
4490     * Compares two sets of signatures. Returns:
4491     * <br />
4492     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4493     * <br />
4494     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4495     * <br />
4496     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4497     * <br />
4498     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4499     * <br />
4500     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4501     */
4502    static int compareSignatures(Signature[] s1, Signature[] s2) {
4503        if (s1 == null) {
4504            return s2 == null
4505                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4506                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4507        }
4508
4509        if (s2 == null) {
4510            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4511        }
4512
4513        if (s1.length != s2.length) {
4514            return PackageManager.SIGNATURE_NO_MATCH;
4515        }
4516
4517        // Since both signature sets are of size 1, we can compare without HashSets.
4518        if (s1.length == 1) {
4519            return s1[0].equals(s2[0]) ?
4520                    PackageManager.SIGNATURE_MATCH :
4521                    PackageManager.SIGNATURE_NO_MATCH;
4522        }
4523
4524        ArraySet<Signature> set1 = new ArraySet<Signature>();
4525        for (Signature sig : s1) {
4526            set1.add(sig);
4527        }
4528        ArraySet<Signature> set2 = new ArraySet<Signature>();
4529        for (Signature sig : s2) {
4530            set2.add(sig);
4531        }
4532        // Make sure s2 contains all signatures in s1.
4533        if (set1.equals(set2)) {
4534            return PackageManager.SIGNATURE_MATCH;
4535        }
4536        return PackageManager.SIGNATURE_NO_MATCH;
4537    }
4538
4539    /**
4540     * If the database version for this type of package (internal storage or
4541     * external storage) is less than the version where package signatures
4542     * were updated, return true.
4543     */
4544    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4545        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4546        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4547    }
4548
4549    /**
4550     * Used for backward compatibility to make sure any packages with
4551     * certificate chains get upgraded to the new style. {@code existingSigs}
4552     * will be in the old format (since they were stored on disk from before the
4553     * system upgrade) and {@code scannedSigs} will be in the newer format.
4554     */
4555    private int compareSignaturesCompat(PackageSignatures existingSigs,
4556            PackageParser.Package scannedPkg) {
4557        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4558            return PackageManager.SIGNATURE_NO_MATCH;
4559        }
4560
4561        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4562        for (Signature sig : existingSigs.mSignatures) {
4563            existingSet.add(sig);
4564        }
4565        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4566        for (Signature sig : scannedPkg.mSignatures) {
4567            try {
4568                Signature[] chainSignatures = sig.getChainSignatures();
4569                for (Signature chainSig : chainSignatures) {
4570                    scannedCompatSet.add(chainSig);
4571                }
4572            } catch (CertificateEncodingException e) {
4573                scannedCompatSet.add(sig);
4574            }
4575        }
4576        /*
4577         * Make sure the expanded scanned set contains all signatures in the
4578         * existing one.
4579         */
4580        if (scannedCompatSet.equals(existingSet)) {
4581            // Migrate the old signatures to the new scheme.
4582            existingSigs.assignSignatures(scannedPkg.mSignatures);
4583            // The new KeySets will be re-added later in the scanning process.
4584            synchronized (mPackages) {
4585                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4586            }
4587            return PackageManager.SIGNATURE_MATCH;
4588        }
4589        return PackageManager.SIGNATURE_NO_MATCH;
4590    }
4591
4592    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4593        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4594        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4595    }
4596
4597    private int compareSignaturesRecover(PackageSignatures existingSigs,
4598            PackageParser.Package scannedPkg) {
4599        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4600            return PackageManager.SIGNATURE_NO_MATCH;
4601        }
4602
4603        String msg = null;
4604        try {
4605            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4606                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4607                        + scannedPkg.packageName);
4608                return PackageManager.SIGNATURE_MATCH;
4609            }
4610        } catch (CertificateException e) {
4611            msg = e.getMessage();
4612        }
4613
4614        logCriticalInfo(Log.INFO,
4615                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4616        return PackageManager.SIGNATURE_NO_MATCH;
4617    }
4618
4619    @Override
4620    public List<String> getAllPackages() {
4621        synchronized (mPackages) {
4622            return new ArrayList<String>(mPackages.keySet());
4623        }
4624    }
4625
4626    @Override
4627    public String[] getPackagesForUid(int uid) {
4628        uid = UserHandle.getAppId(uid);
4629        // reader
4630        synchronized (mPackages) {
4631            Object obj = mSettings.getUserIdLPr(uid);
4632            if (obj instanceof SharedUserSetting) {
4633                final SharedUserSetting sus = (SharedUserSetting) obj;
4634                final int N = sus.packages.size();
4635                final String[] res = new String[N];
4636                for (int i = 0; i < N; i++) {
4637                    res[i] = sus.packages.valueAt(i).name;
4638                }
4639                return res;
4640            } else if (obj instanceof PackageSetting) {
4641                final PackageSetting ps = (PackageSetting) obj;
4642                return new String[] { ps.name };
4643            }
4644        }
4645        return null;
4646    }
4647
4648    @Override
4649    public String getNameForUid(int uid) {
4650        // reader
4651        synchronized (mPackages) {
4652            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4653            if (obj instanceof SharedUserSetting) {
4654                final SharedUserSetting sus = (SharedUserSetting) obj;
4655                return sus.name + ":" + sus.userId;
4656            } else if (obj instanceof PackageSetting) {
4657                final PackageSetting ps = (PackageSetting) obj;
4658                return ps.name;
4659            }
4660        }
4661        return null;
4662    }
4663
4664    @Override
4665    public int getUidForSharedUser(String sharedUserName) {
4666        if(sharedUserName == null) {
4667            return -1;
4668        }
4669        // reader
4670        synchronized (mPackages) {
4671            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4672            if (suid == null) {
4673                return -1;
4674            }
4675            return suid.userId;
4676        }
4677    }
4678
4679    @Override
4680    public int getFlagsForUid(int uid) {
4681        synchronized (mPackages) {
4682            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4683            if (obj instanceof SharedUserSetting) {
4684                final SharedUserSetting sus = (SharedUserSetting) obj;
4685                return sus.pkgFlags;
4686            } else if (obj instanceof PackageSetting) {
4687                final PackageSetting ps = (PackageSetting) obj;
4688                return ps.pkgFlags;
4689            }
4690        }
4691        return 0;
4692    }
4693
4694    @Override
4695    public int getPrivateFlagsForUid(int uid) {
4696        synchronized (mPackages) {
4697            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4698            if (obj instanceof SharedUserSetting) {
4699                final SharedUserSetting sus = (SharedUserSetting) obj;
4700                return sus.pkgPrivateFlags;
4701            } else if (obj instanceof PackageSetting) {
4702                final PackageSetting ps = (PackageSetting) obj;
4703                return ps.pkgPrivateFlags;
4704            }
4705        }
4706        return 0;
4707    }
4708
4709    @Override
4710    public boolean isUidPrivileged(int uid) {
4711        uid = UserHandle.getAppId(uid);
4712        // reader
4713        synchronized (mPackages) {
4714            Object obj = mSettings.getUserIdLPr(uid);
4715            if (obj instanceof SharedUserSetting) {
4716                final SharedUserSetting sus = (SharedUserSetting) obj;
4717                final Iterator<PackageSetting> it = sus.packages.iterator();
4718                while (it.hasNext()) {
4719                    if (it.next().isPrivileged()) {
4720                        return true;
4721                    }
4722                }
4723            } else if (obj instanceof PackageSetting) {
4724                final PackageSetting ps = (PackageSetting) obj;
4725                return ps.isPrivileged();
4726            }
4727        }
4728        return false;
4729    }
4730
4731    @Override
4732    public String[] getAppOpPermissionPackages(String permissionName) {
4733        synchronized (mPackages) {
4734            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4735            if (pkgs == null) {
4736                return null;
4737            }
4738            return pkgs.toArray(new String[pkgs.size()]);
4739        }
4740    }
4741
4742    @Override
4743    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4744            int flags, int userId) {
4745        try {
4746            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4747
4748            if (!sUserManager.exists(userId)) return null;
4749            flags = updateFlagsForResolve(flags, userId, intent);
4750            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4751                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4752
4753            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4754            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4755                    flags, userId);
4756            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4757
4758            final ResolveInfo bestChoice =
4759                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4760            return bestChoice;
4761        } finally {
4762            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4763        }
4764    }
4765
4766    @Override
4767    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4768            IntentFilter filter, int match, ComponentName activity) {
4769        final int userId = UserHandle.getCallingUserId();
4770        if (DEBUG_PREFERRED) {
4771            Log.v(TAG, "setLastChosenActivity intent=" + intent
4772                + " resolvedType=" + resolvedType
4773                + " flags=" + flags
4774                + " filter=" + filter
4775                + " match=" + match
4776                + " activity=" + activity);
4777            filter.dump(new PrintStreamPrinter(System.out), "    ");
4778        }
4779        intent.setComponent(null);
4780        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4781                userId);
4782        // Find any earlier preferred or last chosen entries and nuke them
4783        findPreferredActivity(intent, resolvedType,
4784                flags, query, 0, false, true, false, userId);
4785        // Add the new activity as the last chosen for this filter
4786        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4787                "Setting last chosen");
4788    }
4789
4790    @Override
4791    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4792        final int userId = UserHandle.getCallingUserId();
4793        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4794        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4795                userId);
4796        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4797                false, false, false, userId);
4798    }
4799
4800    private boolean isEphemeralDisabled() {
4801        // ephemeral apps have been disabled across the board
4802        if (DISABLE_EPHEMERAL_APPS) {
4803            return true;
4804        }
4805        // system isn't up yet; can't read settings, so, assume no ephemeral apps
4806        if (!mSystemReady) {
4807            return true;
4808        }
4809        return Secure.getInt(mContext.getContentResolver(), Secure.WEB_ACTION_ENABLED, 1) == 0;
4810    }
4811
4812    private boolean isEphemeralAllowed(
4813            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4814            boolean skipPackageCheck) {
4815        // Short circuit and return early if possible.
4816        if (isEphemeralDisabled()) {
4817            return false;
4818        }
4819        final int callingUser = UserHandle.getCallingUserId();
4820        if (callingUser != UserHandle.USER_SYSTEM) {
4821            return false;
4822        }
4823        if (mEphemeralResolverConnection == null) {
4824            return false;
4825        }
4826        if (intent.getComponent() != null) {
4827            return false;
4828        }
4829        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4830            return false;
4831        }
4832        if (!skipPackageCheck && intent.getPackage() != null) {
4833            return false;
4834        }
4835        final boolean isWebUri = hasWebURI(intent);
4836        if (!isWebUri || intent.getData().getHost() == null) {
4837            return false;
4838        }
4839        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4840        synchronized (mPackages) {
4841            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4842            for (int n = 0; n < count; n++) {
4843                ResolveInfo info = resolvedActivities.get(n);
4844                String packageName = info.activityInfo.packageName;
4845                PackageSetting ps = mSettings.mPackages.get(packageName);
4846                if (ps != null) {
4847                    // Try to get the status from User settings first
4848                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4849                    int status = (int) (packedStatus >> 32);
4850                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4851                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4852                        if (DEBUG_EPHEMERAL) {
4853                            Slog.v(TAG, "DENY ephemeral apps;"
4854                                + " pkg: " + packageName + ", status: " + status);
4855                        }
4856                        return false;
4857                    }
4858                }
4859            }
4860        }
4861        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4862        return true;
4863    }
4864
4865    private static EphemeralResolveInfo getEphemeralResolveInfo(
4866            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4867            String resolvedType, int userId, String packageName) {
4868        final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4869                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4870        final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4871                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4872        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4873                ephemeralPrefixCount);
4874        final int[] shaPrefix = digest.getDigestPrefix();
4875        final byte[][] digestBytes = digest.getDigestBytes();
4876        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4877                resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4878        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4879            // No hash prefix match; there are no ephemeral apps for this domain.
4880            return null;
4881        }
4882
4883        // Go in reverse order so we match the narrowest scope first.
4884        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4885            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4886                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4887                    continue;
4888                }
4889                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4890                // No filters; this should never happen.
4891                if (filters.isEmpty()) {
4892                    continue;
4893                }
4894                if (packageName != null
4895                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4896                    continue;
4897                }
4898                // We have a domain match; resolve the filters to see if anything matches.
4899                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4900                for (int j = filters.size() - 1; j >= 0; --j) {
4901                    final EphemeralResolveIntentInfo intentInfo =
4902                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4903                    ephemeralResolver.addFilter(intentInfo);
4904                }
4905                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4906                        intent, resolvedType, false /*defaultOnly*/, userId);
4907                if (!matchedResolveInfoList.isEmpty()) {
4908                    return matchedResolveInfoList.get(0);
4909                }
4910            }
4911        }
4912        // Hash or filter mis-match; no ephemeral apps for this domain.
4913        return null;
4914    }
4915
4916    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4917            int flags, List<ResolveInfo> query, int userId) {
4918        if (query != null) {
4919            final int N = query.size();
4920            if (N == 1) {
4921                return query.get(0);
4922            } else if (N > 1) {
4923                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4924                // If there is more than one activity with the same priority,
4925                // then let the user decide between them.
4926                ResolveInfo r0 = query.get(0);
4927                ResolveInfo r1 = query.get(1);
4928                if (DEBUG_INTENT_MATCHING || debug) {
4929                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4930                            + r1.activityInfo.name + "=" + r1.priority);
4931                }
4932                // If the first activity has a higher priority, or a different
4933                // default, then it is always desirable to pick it.
4934                if (r0.priority != r1.priority
4935                        || r0.preferredOrder != r1.preferredOrder
4936                        || r0.isDefault != r1.isDefault) {
4937                    return query.get(0);
4938                }
4939                // If we have saved a preference for a preferred activity for
4940                // this Intent, use that.
4941                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4942                        flags, query, r0.priority, true, false, debug, userId);
4943                if (ri != null) {
4944                    return ri;
4945                }
4946                ri = new ResolveInfo(mResolveInfo);
4947                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4948                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4949                // If all of the options come from the same package, show the application's
4950                // label and icon instead of the generic resolver's.
4951                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
4952                // and then throw away the ResolveInfo itself, meaning that the caller loses
4953                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
4954                // a fallback for this case; we only set the target package's resources on
4955                // the ResolveInfo, not the ActivityInfo.
4956                final String intentPackage = intent.getPackage();
4957                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
4958                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
4959                    ri.resolvePackageName = intentPackage;
4960                    if (userNeedsBadging(userId)) {
4961                        ri.noResourceId = true;
4962                    } else {
4963                        ri.icon = appi.icon;
4964                    }
4965                    ri.iconResourceId = appi.icon;
4966                    ri.labelRes = appi.labelRes;
4967                }
4968                ri.activityInfo.applicationInfo = new ApplicationInfo(
4969                        ri.activityInfo.applicationInfo);
4970                if (userId != 0) {
4971                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4972                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4973                }
4974                // Make sure that the resolver is displayable in car mode
4975                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4976                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4977                return ri;
4978            }
4979        }
4980        return null;
4981    }
4982
4983    /**
4984     * Return true if the given list is not empty and all of its contents have
4985     * an activityInfo with the given package name.
4986     */
4987    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
4988        if (ArrayUtils.isEmpty(list)) {
4989            return false;
4990        }
4991        for (int i = 0, N = list.size(); i < N; i++) {
4992            final ResolveInfo ri = list.get(i);
4993            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
4994            if (ai == null || !packageName.equals(ai.packageName)) {
4995                return false;
4996            }
4997        }
4998        return true;
4999    }
5000
5001    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5002            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5003        final int N = query.size();
5004        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5005                .get(userId);
5006        // Get the list of persistent preferred activities that handle the intent
5007        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5008        List<PersistentPreferredActivity> pprefs = ppir != null
5009                ? ppir.queryIntent(intent, resolvedType,
5010                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5011                : null;
5012        if (pprefs != null && pprefs.size() > 0) {
5013            final int M = pprefs.size();
5014            for (int i=0; i<M; i++) {
5015                final PersistentPreferredActivity ppa = pprefs.get(i);
5016                if (DEBUG_PREFERRED || debug) {
5017                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5018                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5019                            + "\n  component=" + ppa.mComponent);
5020                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5021                }
5022                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5023                        flags | MATCH_DISABLED_COMPONENTS, userId);
5024                if (DEBUG_PREFERRED || debug) {
5025                    Slog.v(TAG, "Found persistent preferred activity:");
5026                    if (ai != null) {
5027                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5028                    } else {
5029                        Slog.v(TAG, "  null");
5030                    }
5031                }
5032                if (ai == null) {
5033                    // This previously registered persistent preferred activity
5034                    // component is no longer known. Ignore it and do NOT remove it.
5035                    continue;
5036                }
5037                for (int j=0; j<N; j++) {
5038                    final ResolveInfo ri = query.get(j);
5039                    if (!ri.activityInfo.applicationInfo.packageName
5040                            .equals(ai.applicationInfo.packageName)) {
5041                        continue;
5042                    }
5043                    if (!ri.activityInfo.name.equals(ai.name)) {
5044                        continue;
5045                    }
5046                    //  Found a persistent preference that can handle the intent.
5047                    if (DEBUG_PREFERRED || debug) {
5048                        Slog.v(TAG, "Returning persistent preferred activity: " +
5049                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5050                    }
5051                    return ri;
5052                }
5053            }
5054        }
5055        return null;
5056    }
5057
5058    // TODO: handle preferred activities missing while user has amnesia
5059    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5060            List<ResolveInfo> query, int priority, boolean always,
5061            boolean removeMatches, boolean debug, int userId) {
5062        if (!sUserManager.exists(userId)) return null;
5063        flags = updateFlagsForResolve(flags, userId, intent);
5064        // writer
5065        synchronized (mPackages) {
5066            if (intent.getSelector() != null) {
5067                intent = intent.getSelector();
5068            }
5069            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5070
5071            // Try to find a matching persistent preferred activity.
5072            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5073                    debug, userId);
5074
5075            // If a persistent preferred activity matched, use it.
5076            if (pri != null) {
5077                return pri;
5078            }
5079
5080            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5081            // Get the list of preferred activities that handle the intent
5082            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5083            List<PreferredActivity> prefs = pir != null
5084                    ? pir.queryIntent(intent, resolvedType,
5085                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5086                    : null;
5087            if (prefs != null && prefs.size() > 0) {
5088                boolean changed = false;
5089                try {
5090                    // First figure out how good the original match set is.
5091                    // We will only allow preferred activities that came
5092                    // from the same match quality.
5093                    int match = 0;
5094
5095                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5096
5097                    final int N = query.size();
5098                    for (int j=0; j<N; j++) {
5099                        final ResolveInfo ri = query.get(j);
5100                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5101                                + ": 0x" + Integer.toHexString(match));
5102                        if (ri.match > match) {
5103                            match = ri.match;
5104                        }
5105                    }
5106
5107                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5108                            + Integer.toHexString(match));
5109
5110                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5111                    final int M = prefs.size();
5112                    for (int i=0; i<M; i++) {
5113                        final PreferredActivity pa = prefs.get(i);
5114                        if (DEBUG_PREFERRED || debug) {
5115                            Slog.v(TAG, "Checking PreferredActivity ds="
5116                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5117                                    + "\n  component=" + pa.mPref.mComponent);
5118                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5119                        }
5120                        if (pa.mPref.mMatch != match) {
5121                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5122                                    + Integer.toHexString(pa.mPref.mMatch));
5123                            continue;
5124                        }
5125                        // If it's not an "always" type preferred activity and that's what we're
5126                        // looking for, skip it.
5127                        if (always && !pa.mPref.mAlways) {
5128                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5129                            continue;
5130                        }
5131                        final ActivityInfo ai = getActivityInfo(
5132                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5133                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5134                                userId);
5135                        if (DEBUG_PREFERRED || debug) {
5136                            Slog.v(TAG, "Found preferred activity:");
5137                            if (ai != null) {
5138                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5139                            } else {
5140                                Slog.v(TAG, "  null");
5141                            }
5142                        }
5143                        if (ai == null) {
5144                            // This previously registered preferred activity
5145                            // component is no longer known.  Most likely an update
5146                            // to the app was installed and in the new version this
5147                            // component no longer exists.  Clean it up by removing
5148                            // it from the preferred activities list, and skip it.
5149                            Slog.w(TAG, "Removing dangling preferred activity: "
5150                                    + pa.mPref.mComponent);
5151                            pir.removeFilter(pa);
5152                            changed = true;
5153                            continue;
5154                        }
5155                        for (int j=0; j<N; j++) {
5156                            final ResolveInfo ri = query.get(j);
5157                            if (!ri.activityInfo.applicationInfo.packageName
5158                                    .equals(ai.applicationInfo.packageName)) {
5159                                continue;
5160                            }
5161                            if (!ri.activityInfo.name.equals(ai.name)) {
5162                                continue;
5163                            }
5164
5165                            if (removeMatches) {
5166                                pir.removeFilter(pa);
5167                                changed = true;
5168                                if (DEBUG_PREFERRED) {
5169                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5170                                }
5171                                break;
5172                            }
5173
5174                            // Okay we found a previously set preferred or last chosen app.
5175                            // If the result set is different from when this
5176                            // was created, we need to clear it and re-ask the
5177                            // user their preference, if we're looking for an "always" type entry.
5178                            if (always && !pa.mPref.sameSet(query)) {
5179                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5180                                        + intent + " type " + resolvedType);
5181                                if (DEBUG_PREFERRED) {
5182                                    Slog.v(TAG, "Removing preferred activity since set changed "
5183                                            + pa.mPref.mComponent);
5184                                }
5185                                pir.removeFilter(pa);
5186                                // Re-add the filter as a "last chosen" entry (!always)
5187                                PreferredActivity lastChosen = new PreferredActivity(
5188                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5189                                pir.addFilter(lastChosen);
5190                                changed = true;
5191                                return null;
5192                            }
5193
5194                            // Yay! Either the set matched or we're looking for the last chosen
5195                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5196                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5197                            return ri;
5198                        }
5199                    }
5200                } finally {
5201                    if (changed) {
5202                        if (DEBUG_PREFERRED) {
5203                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5204                        }
5205                        scheduleWritePackageRestrictionsLocked(userId);
5206                    }
5207                }
5208            }
5209        }
5210        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5211        return null;
5212    }
5213
5214    /*
5215     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5216     */
5217    @Override
5218    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5219            int targetUserId) {
5220        mContext.enforceCallingOrSelfPermission(
5221                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5222        List<CrossProfileIntentFilter> matches =
5223                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5224        if (matches != null) {
5225            int size = matches.size();
5226            for (int i = 0; i < size; i++) {
5227                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5228            }
5229        }
5230        if (hasWebURI(intent)) {
5231            // cross-profile app linking works only towards the parent.
5232            final UserInfo parent = getProfileParent(sourceUserId);
5233            synchronized(mPackages) {
5234                int flags = updateFlagsForResolve(0, parent.id, intent);
5235                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5236                        intent, resolvedType, flags, sourceUserId, parent.id);
5237                return xpDomainInfo != null;
5238            }
5239        }
5240        return false;
5241    }
5242
5243    private UserInfo getProfileParent(int userId) {
5244        final long identity = Binder.clearCallingIdentity();
5245        try {
5246            return sUserManager.getProfileParent(userId);
5247        } finally {
5248            Binder.restoreCallingIdentity(identity);
5249        }
5250    }
5251
5252    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5253            String resolvedType, int userId) {
5254        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5255        if (resolver != null) {
5256            return resolver.queryIntent(intent, resolvedType, false, userId);
5257        }
5258        return null;
5259    }
5260
5261    @Override
5262    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5263            String resolvedType, int flags, int userId) {
5264        try {
5265            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5266
5267            return new ParceledListSlice<>(
5268                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5269        } finally {
5270            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5271        }
5272    }
5273
5274    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5275            String resolvedType, int flags, int userId) {
5276        if (!sUserManager.exists(userId)) return Collections.emptyList();
5277        flags = updateFlagsForResolve(flags, userId, intent);
5278        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5279                false /* requireFullPermission */, false /* checkShell */,
5280                "query intent activities");
5281        ComponentName comp = intent.getComponent();
5282        if (comp == null) {
5283            if (intent.getSelector() != null) {
5284                intent = intent.getSelector();
5285                comp = intent.getComponent();
5286            }
5287        }
5288
5289        if (comp != null) {
5290            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5291            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5292            if (ai != null) {
5293                final ResolveInfo ri = new ResolveInfo();
5294                ri.activityInfo = ai;
5295                list.add(ri);
5296            }
5297            return list;
5298        }
5299
5300        // reader
5301        boolean sortResult = false;
5302        boolean addEphemeral = false;
5303        boolean matchEphemeralPackage = false;
5304        List<ResolveInfo> result;
5305        final String pkgName = intent.getPackage();
5306        synchronized (mPackages) {
5307            if (pkgName == null) {
5308                List<CrossProfileIntentFilter> matchingFilters =
5309                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5310                // Check for results that need to skip the current profile.
5311                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5312                        resolvedType, flags, userId);
5313                if (xpResolveInfo != null) {
5314                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5315                    xpResult.add(xpResolveInfo);
5316                    return filterIfNotSystemUser(xpResult, userId);
5317                }
5318
5319                // Check for results in the current profile.
5320                result = filterIfNotSystemUser(mActivities.queryIntent(
5321                        intent, resolvedType, flags, userId), userId);
5322                addEphemeral =
5323                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5324
5325                // Check for cross profile results.
5326                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5327                xpResolveInfo = queryCrossProfileIntents(
5328                        matchingFilters, intent, resolvedType, flags, userId,
5329                        hasNonNegativePriorityResult);
5330                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5331                    boolean isVisibleToUser = filterIfNotSystemUser(
5332                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5333                    if (isVisibleToUser) {
5334                        result.add(xpResolveInfo);
5335                        sortResult = true;
5336                    }
5337                }
5338                if (hasWebURI(intent)) {
5339                    CrossProfileDomainInfo xpDomainInfo = null;
5340                    final UserInfo parent = getProfileParent(userId);
5341                    if (parent != null) {
5342                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5343                                flags, userId, parent.id);
5344                    }
5345                    if (xpDomainInfo != null) {
5346                        if (xpResolveInfo != null) {
5347                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5348                            // in the result.
5349                            result.remove(xpResolveInfo);
5350                        }
5351                        if (result.size() == 0 && !addEphemeral) {
5352                            result.add(xpDomainInfo.resolveInfo);
5353                            return result;
5354                        }
5355                    }
5356                    if (result.size() > 1 || addEphemeral) {
5357                        result = filterCandidatesWithDomainPreferredActivitiesLPr(
5358                                intent, flags, result, xpDomainInfo, userId);
5359                        sortResult = true;
5360                    }
5361                }
5362            } else {
5363                final PackageParser.Package pkg = mPackages.get(pkgName);
5364                if (pkg != null) {
5365                    result = filterIfNotSystemUser(
5366                            mActivities.queryIntentForPackage(
5367                                    intent, resolvedType, flags, pkg.activities, userId),
5368                            userId);
5369                } else {
5370                    // the caller wants to resolve for a particular package; however, there
5371                    // were no installed results, so, try to find an ephemeral result
5372                    addEphemeral = isEphemeralAllowed(
5373                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5374                    matchEphemeralPackage = true;
5375                    result = new ArrayList<ResolveInfo>();
5376                }
5377            }
5378        }
5379        if (addEphemeral) {
5380            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5381            final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5382                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5383                    matchEphemeralPackage ? pkgName : null);
5384            if (ai != null) {
5385                if (DEBUG_EPHEMERAL) {
5386                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5387                }
5388                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5389                ephemeralInstaller.ephemeralResolveInfo = ai;
5390                // make sure this resolver is the default
5391                ephemeralInstaller.isDefault = true;
5392                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5393                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5394                // add a non-generic filter
5395                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5396                ephemeralInstaller.filter.addDataPath(
5397                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5398                result.add(ephemeralInstaller);
5399            }
5400            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5401        }
5402        if (sortResult) {
5403            Collections.sort(result, mResolvePrioritySorter);
5404        }
5405        return result;
5406    }
5407
5408    private static class CrossProfileDomainInfo {
5409        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5410        ResolveInfo resolveInfo;
5411        /* Best domain verification status of the activities found in the other profile */
5412        int bestDomainVerificationStatus;
5413    }
5414
5415    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5416            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5417        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5418                sourceUserId)) {
5419            return null;
5420        }
5421        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5422                resolvedType, flags, parentUserId);
5423
5424        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5425            return null;
5426        }
5427        CrossProfileDomainInfo result = null;
5428        int size = resultTargetUser.size();
5429        for (int i = 0; i < size; i++) {
5430            ResolveInfo riTargetUser = resultTargetUser.get(i);
5431            // Intent filter verification is only for filters that specify a host. So don't return
5432            // those that handle all web uris.
5433            if (riTargetUser.handleAllWebDataURI) {
5434                continue;
5435            }
5436            String packageName = riTargetUser.activityInfo.packageName;
5437            PackageSetting ps = mSettings.mPackages.get(packageName);
5438            if (ps == null) {
5439                continue;
5440            }
5441            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5442            int status = (int)(verificationState >> 32);
5443            if (result == null) {
5444                result = new CrossProfileDomainInfo();
5445                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5446                        sourceUserId, parentUserId);
5447                result.bestDomainVerificationStatus = status;
5448            } else {
5449                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5450                        result.bestDomainVerificationStatus);
5451            }
5452        }
5453        // Don't consider matches with status NEVER across profiles.
5454        if (result != null && result.bestDomainVerificationStatus
5455                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5456            return null;
5457        }
5458        return result;
5459    }
5460
5461    /**
5462     * Verification statuses are ordered from the worse to the best, except for
5463     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5464     */
5465    private int bestDomainVerificationStatus(int status1, int status2) {
5466        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5467            return status2;
5468        }
5469        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5470            return status1;
5471        }
5472        return (int) MathUtils.max(status1, status2);
5473    }
5474
5475    private boolean isUserEnabled(int userId) {
5476        long callingId = Binder.clearCallingIdentity();
5477        try {
5478            UserInfo userInfo = sUserManager.getUserInfo(userId);
5479            return userInfo != null && userInfo.isEnabled();
5480        } finally {
5481            Binder.restoreCallingIdentity(callingId);
5482        }
5483    }
5484
5485    /**
5486     * Filter out activities with systemUserOnly flag set, when current user is not System.
5487     *
5488     * @return filtered list
5489     */
5490    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5491        if (userId == UserHandle.USER_SYSTEM) {
5492            return resolveInfos;
5493        }
5494        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5495            ResolveInfo info = resolveInfos.get(i);
5496            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5497                resolveInfos.remove(i);
5498            }
5499        }
5500        return resolveInfos;
5501    }
5502
5503    /**
5504     * @param resolveInfos list of resolve infos in descending priority order
5505     * @return if the list contains a resolve info with non-negative priority
5506     */
5507    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5508        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5509    }
5510
5511    private static boolean hasWebURI(Intent intent) {
5512        if (intent.getData() == null) {
5513            return false;
5514        }
5515        final String scheme = intent.getScheme();
5516        if (TextUtils.isEmpty(scheme)) {
5517            return false;
5518        }
5519        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5520    }
5521
5522    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5523            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5524            int userId) {
5525        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5526
5527        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5528            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5529                    candidates.size());
5530        }
5531
5532        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5533        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5534        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5535        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5536        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5537        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5538
5539        synchronized (mPackages) {
5540            final int count = candidates.size();
5541            // First, try to use linked apps. Partition the candidates into four lists:
5542            // one for the final results, one for the "do not use ever", one for "undefined status"
5543            // and finally one for "browser app type".
5544            for (int n=0; n<count; n++) {
5545                ResolveInfo info = candidates.get(n);
5546                String packageName = info.activityInfo.packageName;
5547                PackageSetting ps = mSettings.mPackages.get(packageName);
5548                if (ps != null) {
5549                    // Add to the special match all list (Browser use case)
5550                    if (info.handleAllWebDataURI) {
5551                        matchAllList.add(info);
5552                        continue;
5553                    }
5554                    // Try to get the status from User settings first
5555                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5556                    int status = (int)(packedStatus >> 32);
5557                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5558                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5559                        if (DEBUG_DOMAIN_VERIFICATION) {
5560                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5561                                    + " : linkgen=" + linkGeneration);
5562                        }
5563                        // Use link-enabled generation as preferredOrder, i.e.
5564                        // prefer newly-enabled over earlier-enabled.
5565                        info.preferredOrder = linkGeneration;
5566                        alwaysList.add(info);
5567                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5568                        if (DEBUG_DOMAIN_VERIFICATION) {
5569                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5570                        }
5571                        neverList.add(info);
5572                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5573                        if (DEBUG_DOMAIN_VERIFICATION) {
5574                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5575                        }
5576                        alwaysAskList.add(info);
5577                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5578                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5579                        if (DEBUG_DOMAIN_VERIFICATION) {
5580                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5581                        }
5582                        undefinedList.add(info);
5583                    }
5584                }
5585            }
5586
5587            // We'll want to include browser possibilities in a few cases
5588            boolean includeBrowser = false;
5589
5590            // First try to add the "always" resolution(s) for the current user, if any
5591            if (alwaysList.size() > 0) {
5592                result.addAll(alwaysList);
5593            } else {
5594                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5595                result.addAll(undefinedList);
5596                // Maybe add one for the other profile.
5597                if (xpDomainInfo != null && (
5598                        xpDomainInfo.bestDomainVerificationStatus
5599                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5600                    result.add(xpDomainInfo.resolveInfo);
5601                }
5602                includeBrowser = true;
5603            }
5604
5605            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5606            // If there were 'always' entries their preferred order has been set, so we also
5607            // back that off to make the alternatives equivalent
5608            if (alwaysAskList.size() > 0) {
5609                for (ResolveInfo i : result) {
5610                    i.preferredOrder = 0;
5611                }
5612                result.addAll(alwaysAskList);
5613                includeBrowser = true;
5614            }
5615
5616            if (includeBrowser) {
5617                // Also add browsers (all of them or only the default one)
5618                if (DEBUG_DOMAIN_VERIFICATION) {
5619                    Slog.v(TAG, "   ...including browsers in candidate set");
5620                }
5621                if ((matchFlags & MATCH_ALL) != 0) {
5622                    result.addAll(matchAllList);
5623                } else {
5624                    // Browser/generic handling case.  If there's a default browser, go straight
5625                    // to that (but only if there is no other higher-priority match).
5626                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5627                    int maxMatchPrio = 0;
5628                    ResolveInfo defaultBrowserMatch = null;
5629                    final int numCandidates = matchAllList.size();
5630                    for (int n = 0; n < numCandidates; n++) {
5631                        ResolveInfo info = matchAllList.get(n);
5632                        // track the highest overall match priority...
5633                        if (info.priority > maxMatchPrio) {
5634                            maxMatchPrio = info.priority;
5635                        }
5636                        // ...and the highest-priority default browser match
5637                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5638                            if (defaultBrowserMatch == null
5639                                    || (defaultBrowserMatch.priority < info.priority)) {
5640                                if (debug) {
5641                                    Slog.v(TAG, "Considering default browser match " + info);
5642                                }
5643                                defaultBrowserMatch = info;
5644                            }
5645                        }
5646                    }
5647                    if (defaultBrowserMatch != null
5648                            && defaultBrowserMatch.priority >= maxMatchPrio
5649                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5650                    {
5651                        if (debug) {
5652                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5653                        }
5654                        result.add(defaultBrowserMatch);
5655                    } else {
5656                        result.addAll(matchAllList);
5657                    }
5658                }
5659
5660                // If there is nothing selected, add all candidates and remove the ones that the user
5661                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5662                if (result.size() == 0) {
5663                    result.addAll(candidates);
5664                    result.removeAll(neverList);
5665                }
5666            }
5667        }
5668        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5669            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5670                    result.size());
5671            for (ResolveInfo info : result) {
5672                Slog.v(TAG, "  + " + info.activityInfo);
5673            }
5674        }
5675        return result;
5676    }
5677
5678    // Returns a packed value as a long:
5679    //
5680    // high 'int'-sized word: link status: undefined/ask/never/always.
5681    // low 'int'-sized word: relative priority among 'always' results.
5682    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5683        long result = ps.getDomainVerificationStatusForUser(userId);
5684        // if none available, get the master status
5685        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5686            if (ps.getIntentFilterVerificationInfo() != null) {
5687                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5688            }
5689        }
5690        return result;
5691    }
5692
5693    private ResolveInfo querySkipCurrentProfileIntents(
5694            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5695            int flags, int sourceUserId) {
5696        if (matchingFilters != null) {
5697            int size = matchingFilters.size();
5698            for (int i = 0; i < size; i ++) {
5699                CrossProfileIntentFilter filter = matchingFilters.get(i);
5700                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5701                    // Checking if there are activities in the target user that can handle the
5702                    // intent.
5703                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5704                            resolvedType, flags, sourceUserId);
5705                    if (resolveInfo != null) {
5706                        return resolveInfo;
5707                    }
5708                }
5709            }
5710        }
5711        return null;
5712    }
5713
5714    // Return matching ResolveInfo in target user if any.
5715    private ResolveInfo queryCrossProfileIntents(
5716            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5717            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5718        if (matchingFilters != null) {
5719            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5720            // match the same intent. For performance reasons, it is better not to
5721            // run queryIntent twice for the same userId
5722            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5723            int size = matchingFilters.size();
5724            for (int i = 0; i < size; i++) {
5725                CrossProfileIntentFilter filter = matchingFilters.get(i);
5726                int targetUserId = filter.getTargetUserId();
5727                boolean skipCurrentProfile =
5728                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5729                boolean skipCurrentProfileIfNoMatchFound =
5730                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5731                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5732                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5733                    // Checking if there are activities in the target user that can handle the
5734                    // intent.
5735                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5736                            resolvedType, flags, sourceUserId);
5737                    if (resolveInfo != null) return resolveInfo;
5738                    alreadyTriedUserIds.put(targetUserId, true);
5739                }
5740            }
5741        }
5742        return null;
5743    }
5744
5745    /**
5746     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5747     * will forward the intent to the filter's target user.
5748     * Otherwise, returns null.
5749     */
5750    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5751            String resolvedType, int flags, int sourceUserId) {
5752        int targetUserId = filter.getTargetUserId();
5753        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5754                resolvedType, flags, targetUserId);
5755        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5756            // If all the matches in the target profile are suspended, return null.
5757            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5758                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5759                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5760                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5761                            targetUserId);
5762                }
5763            }
5764        }
5765        return null;
5766    }
5767
5768    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5769            int sourceUserId, int targetUserId) {
5770        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5771        long ident = Binder.clearCallingIdentity();
5772        boolean targetIsProfile;
5773        try {
5774            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5775        } finally {
5776            Binder.restoreCallingIdentity(ident);
5777        }
5778        String className;
5779        if (targetIsProfile) {
5780            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5781        } else {
5782            className = FORWARD_INTENT_TO_PARENT;
5783        }
5784        ComponentName forwardingActivityComponentName = new ComponentName(
5785                mAndroidApplication.packageName, className);
5786        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5787                sourceUserId);
5788        if (!targetIsProfile) {
5789            forwardingActivityInfo.showUserIcon = targetUserId;
5790            forwardingResolveInfo.noResourceId = true;
5791        }
5792        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5793        forwardingResolveInfo.priority = 0;
5794        forwardingResolveInfo.preferredOrder = 0;
5795        forwardingResolveInfo.match = 0;
5796        forwardingResolveInfo.isDefault = true;
5797        forwardingResolveInfo.filter = filter;
5798        forwardingResolveInfo.targetUserId = targetUserId;
5799        return forwardingResolveInfo;
5800    }
5801
5802    @Override
5803    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5804            Intent[] specifics, String[] specificTypes, Intent intent,
5805            String resolvedType, int flags, int userId) {
5806        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5807                specificTypes, intent, resolvedType, flags, userId));
5808    }
5809
5810    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5811            Intent[] specifics, String[] specificTypes, Intent intent,
5812            String resolvedType, int flags, int userId) {
5813        if (!sUserManager.exists(userId)) return Collections.emptyList();
5814        flags = updateFlagsForResolve(flags, userId, intent);
5815        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5816                false /* requireFullPermission */, false /* checkShell */,
5817                "query intent activity options");
5818        final String resultsAction = intent.getAction();
5819
5820        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5821                | PackageManager.GET_RESOLVED_FILTER, userId);
5822
5823        if (DEBUG_INTENT_MATCHING) {
5824            Log.v(TAG, "Query " + intent + ": " + results);
5825        }
5826
5827        int specificsPos = 0;
5828        int N;
5829
5830        // todo: note that the algorithm used here is O(N^2).  This
5831        // isn't a problem in our current environment, but if we start running
5832        // into situations where we have more than 5 or 10 matches then this
5833        // should probably be changed to something smarter...
5834
5835        // First we go through and resolve each of the specific items
5836        // that were supplied, taking care of removing any corresponding
5837        // duplicate items in the generic resolve list.
5838        if (specifics != null) {
5839            for (int i=0; i<specifics.length; i++) {
5840                final Intent sintent = specifics[i];
5841                if (sintent == null) {
5842                    continue;
5843                }
5844
5845                if (DEBUG_INTENT_MATCHING) {
5846                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5847                }
5848
5849                String action = sintent.getAction();
5850                if (resultsAction != null && resultsAction.equals(action)) {
5851                    // If this action was explicitly requested, then don't
5852                    // remove things that have it.
5853                    action = null;
5854                }
5855
5856                ResolveInfo ri = null;
5857                ActivityInfo ai = null;
5858
5859                ComponentName comp = sintent.getComponent();
5860                if (comp == null) {
5861                    ri = resolveIntent(
5862                        sintent,
5863                        specificTypes != null ? specificTypes[i] : null,
5864                            flags, userId);
5865                    if (ri == null) {
5866                        continue;
5867                    }
5868                    if (ri == mResolveInfo) {
5869                        // ACK!  Must do something better with this.
5870                    }
5871                    ai = ri.activityInfo;
5872                    comp = new ComponentName(ai.applicationInfo.packageName,
5873                            ai.name);
5874                } else {
5875                    ai = getActivityInfo(comp, flags, userId);
5876                    if (ai == null) {
5877                        continue;
5878                    }
5879                }
5880
5881                // Look for any generic query activities that are duplicates
5882                // of this specific one, and remove them from the results.
5883                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5884                N = results.size();
5885                int j;
5886                for (j=specificsPos; j<N; j++) {
5887                    ResolveInfo sri = results.get(j);
5888                    if ((sri.activityInfo.name.equals(comp.getClassName())
5889                            && sri.activityInfo.applicationInfo.packageName.equals(
5890                                    comp.getPackageName()))
5891                        || (action != null && sri.filter.matchAction(action))) {
5892                        results.remove(j);
5893                        if (DEBUG_INTENT_MATCHING) Log.v(
5894                            TAG, "Removing duplicate item from " + j
5895                            + " due to specific " + specificsPos);
5896                        if (ri == null) {
5897                            ri = sri;
5898                        }
5899                        j--;
5900                        N--;
5901                    }
5902                }
5903
5904                // Add this specific item to its proper place.
5905                if (ri == null) {
5906                    ri = new ResolveInfo();
5907                    ri.activityInfo = ai;
5908                }
5909                results.add(specificsPos, ri);
5910                ri.specificIndex = i;
5911                specificsPos++;
5912            }
5913        }
5914
5915        // Now we go through the remaining generic results and remove any
5916        // duplicate actions that are found here.
5917        N = results.size();
5918        for (int i=specificsPos; i<N-1; i++) {
5919            final ResolveInfo rii = results.get(i);
5920            if (rii.filter == null) {
5921                continue;
5922            }
5923
5924            // Iterate over all of the actions of this result's intent
5925            // filter...  typically this should be just one.
5926            final Iterator<String> it = rii.filter.actionsIterator();
5927            if (it == null) {
5928                continue;
5929            }
5930            while (it.hasNext()) {
5931                final String action = it.next();
5932                if (resultsAction != null && resultsAction.equals(action)) {
5933                    // If this action was explicitly requested, then don't
5934                    // remove things that have it.
5935                    continue;
5936                }
5937                for (int j=i+1; j<N; j++) {
5938                    final ResolveInfo rij = results.get(j);
5939                    if (rij.filter != null && rij.filter.hasAction(action)) {
5940                        results.remove(j);
5941                        if (DEBUG_INTENT_MATCHING) Log.v(
5942                            TAG, "Removing duplicate item from " + j
5943                            + " due to action " + action + " at " + i);
5944                        j--;
5945                        N--;
5946                    }
5947                }
5948            }
5949
5950            // If the caller didn't request filter information, drop it now
5951            // so we don't have to marshall/unmarshall it.
5952            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5953                rii.filter = null;
5954            }
5955        }
5956
5957        // Filter out the caller activity if so requested.
5958        if (caller != null) {
5959            N = results.size();
5960            for (int i=0; i<N; i++) {
5961                ActivityInfo ainfo = results.get(i).activityInfo;
5962                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5963                        && caller.getClassName().equals(ainfo.name)) {
5964                    results.remove(i);
5965                    break;
5966                }
5967            }
5968        }
5969
5970        // If the caller didn't request filter information,
5971        // drop them now so we don't have to
5972        // marshall/unmarshall it.
5973        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5974            N = results.size();
5975            for (int i=0; i<N; i++) {
5976                results.get(i).filter = null;
5977            }
5978        }
5979
5980        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5981        return results;
5982    }
5983
5984    @Override
5985    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5986            String resolvedType, int flags, int userId) {
5987        return new ParceledListSlice<>(
5988                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5989    }
5990
5991    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5992            String resolvedType, int flags, int userId) {
5993        if (!sUserManager.exists(userId)) return Collections.emptyList();
5994        flags = updateFlagsForResolve(flags, userId, intent);
5995        ComponentName comp = intent.getComponent();
5996        if (comp == null) {
5997            if (intent.getSelector() != null) {
5998                intent = intent.getSelector();
5999                comp = intent.getComponent();
6000            }
6001        }
6002        if (comp != null) {
6003            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6004            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6005            if (ai != null) {
6006                ResolveInfo ri = new ResolveInfo();
6007                ri.activityInfo = ai;
6008                list.add(ri);
6009            }
6010            return list;
6011        }
6012
6013        // reader
6014        synchronized (mPackages) {
6015            String pkgName = intent.getPackage();
6016            if (pkgName == null) {
6017                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6018            }
6019            final PackageParser.Package pkg = mPackages.get(pkgName);
6020            if (pkg != null) {
6021                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6022                        userId);
6023            }
6024            return Collections.emptyList();
6025        }
6026    }
6027
6028    @Override
6029    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6030        if (!sUserManager.exists(userId)) return null;
6031        flags = updateFlagsForResolve(flags, userId, intent);
6032        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6033        if (query != null) {
6034            if (query.size() >= 1) {
6035                // If there is more than one service with the same priority,
6036                // just arbitrarily pick the first one.
6037                return query.get(0);
6038            }
6039        }
6040        return null;
6041    }
6042
6043    @Override
6044    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6045            String resolvedType, int flags, int userId) {
6046        return new ParceledListSlice<>(
6047                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6048    }
6049
6050    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6051            String resolvedType, int flags, int userId) {
6052        if (!sUserManager.exists(userId)) return Collections.emptyList();
6053        flags = updateFlagsForResolve(flags, userId, intent);
6054        ComponentName comp = intent.getComponent();
6055        if (comp == null) {
6056            if (intent.getSelector() != null) {
6057                intent = intent.getSelector();
6058                comp = intent.getComponent();
6059            }
6060        }
6061        if (comp != null) {
6062            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6063            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6064            if (si != null) {
6065                final ResolveInfo ri = new ResolveInfo();
6066                ri.serviceInfo = si;
6067                list.add(ri);
6068            }
6069            return list;
6070        }
6071
6072        // reader
6073        synchronized (mPackages) {
6074            String pkgName = intent.getPackage();
6075            if (pkgName == null) {
6076                return mServices.queryIntent(intent, resolvedType, flags, userId);
6077            }
6078            final PackageParser.Package pkg = mPackages.get(pkgName);
6079            if (pkg != null) {
6080                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6081                        userId);
6082            }
6083            return Collections.emptyList();
6084        }
6085    }
6086
6087    @Override
6088    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6089            String resolvedType, int flags, int userId) {
6090        return new ParceledListSlice<>(
6091                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6092    }
6093
6094    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6095            Intent intent, String resolvedType, int flags, int userId) {
6096        if (!sUserManager.exists(userId)) return Collections.emptyList();
6097        flags = updateFlagsForResolve(flags, userId, intent);
6098        ComponentName comp = intent.getComponent();
6099        if (comp == null) {
6100            if (intent.getSelector() != null) {
6101                intent = intent.getSelector();
6102                comp = intent.getComponent();
6103            }
6104        }
6105        if (comp != null) {
6106            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6107            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6108            if (pi != null) {
6109                final ResolveInfo ri = new ResolveInfo();
6110                ri.providerInfo = pi;
6111                list.add(ri);
6112            }
6113            return list;
6114        }
6115
6116        // reader
6117        synchronized (mPackages) {
6118            String pkgName = intent.getPackage();
6119            if (pkgName == null) {
6120                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6121            }
6122            final PackageParser.Package pkg = mPackages.get(pkgName);
6123            if (pkg != null) {
6124                return mProviders.queryIntentForPackage(
6125                        intent, resolvedType, flags, pkg.providers, userId);
6126            }
6127            return Collections.emptyList();
6128        }
6129    }
6130
6131    @Override
6132    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6133        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6134        flags = updateFlagsForPackage(flags, userId, null);
6135        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6136        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6137                true /* requireFullPermission */, false /* checkShell */,
6138                "get installed packages");
6139
6140        // writer
6141        synchronized (mPackages) {
6142            ArrayList<PackageInfo> list;
6143            if (listUninstalled) {
6144                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6145                for (PackageSetting ps : mSettings.mPackages.values()) {
6146                    final PackageInfo pi;
6147                    if (ps.pkg != null) {
6148                        pi = generatePackageInfo(ps, flags, userId);
6149                    } else {
6150                        pi = generatePackageInfo(ps, flags, userId);
6151                    }
6152                    if (pi != null) {
6153                        list.add(pi);
6154                    }
6155                }
6156            } else {
6157                list = new ArrayList<PackageInfo>(mPackages.size());
6158                for (PackageParser.Package p : mPackages.values()) {
6159                    final PackageInfo pi =
6160                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6161                    if (pi != null) {
6162                        list.add(pi);
6163                    }
6164                }
6165            }
6166
6167            return new ParceledListSlice<PackageInfo>(list);
6168        }
6169    }
6170
6171    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6172            String[] permissions, boolean[] tmp, int flags, int userId) {
6173        int numMatch = 0;
6174        final PermissionsState permissionsState = ps.getPermissionsState();
6175        for (int i=0; i<permissions.length; i++) {
6176            final String permission = permissions[i];
6177            if (permissionsState.hasPermission(permission, userId)) {
6178                tmp[i] = true;
6179                numMatch++;
6180            } else {
6181                tmp[i] = false;
6182            }
6183        }
6184        if (numMatch == 0) {
6185            return;
6186        }
6187        final PackageInfo pi;
6188        if (ps.pkg != null) {
6189            pi = generatePackageInfo(ps, flags, userId);
6190        } else {
6191            pi = generatePackageInfo(ps, flags, userId);
6192        }
6193        // The above might return null in cases of uninstalled apps or install-state
6194        // skew across users/profiles.
6195        if (pi != null) {
6196            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6197                if (numMatch == permissions.length) {
6198                    pi.requestedPermissions = permissions;
6199                } else {
6200                    pi.requestedPermissions = new String[numMatch];
6201                    numMatch = 0;
6202                    for (int i=0; i<permissions.length; i++) {
6203                        if (tmp[i]) {
6204                            pi.requestedPermissions[numMatch] = permissions[i];
6205                            numMatch++;
6206                        }
6207                    }
6208                }
6209            }
6210            list.add(pi);
6211        }
6212    }
6213
6214    @Override
6215    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6216            String[] permissions, int flags, int userId) {
6217        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6218        flags = updateFlagsForPackage(flags, userId, permissions);
6219        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6220
6221        // writer
6222        synchronized (mPackages) {
6223            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6224            boolean[] tmpBools = new boolean[permissions.length];
6225            if (listUninstalled) {
6226                for (PackageSetting ps : mSettings.mPackages.values()) {
6227                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6228                }
6229            } else {
6230                for (PackageParser.Package pkg : mPackages.values()) {
6231                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6232                    if (ps != null) {
6233                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6234                                userId);
6235                    }
6236                }
6237            }
6238
6239            return new ParceledListSlice<PackageInfo>(list);
6240        }
6241    }
6242
6243    @Override
6244    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6245        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6246        flags = updateFlagsForApplication(flags, userId, null);
6247        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6248
6249        // writer
6250        synchronized (mPackages) {
6251            ArrayList<ApplicationInfo> list;
6252            if (listUninstalled) {
6253                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6254                for (PackageSetting ps : mSettings.mPackages.values()) {
6255                    ApplicationInfo ai;
6256                    if (ps.pkg != null) {
6257                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6258                                ps.readUserState(userId), userId);
6259                    } else {
6260                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6261                    }
6262                    if (ai != null) {
6263                        list.add(ai);
6264                    }
6265                }
6266            } else {
6267                list = new ArrayList<ApplicationInfo>(mPackages.size());
6268                for (PackageParser.Package p : mPackages.values()) {
6269                    if (p.mExtras != null) {
6270                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6271                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6272                        if (ai != null) {
6273                            list.add(ai);
6274                        }
6275                    }
6276                }
6277            }
6278
6279            return new ParceledListSlice<ApplicationInfo>(list);
6280        }
6281    }
6282
6283    @Override
6284    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6285        if (isEphemeralDisabled()) {
6286            return null;
6287        }
6288
6289        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6290                "getEphemeralApplications");
6291        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6292                true /* requireFullPermission */, false /* checkShell */,
6293                "getEphemeralApplications");
6294        synchronized (mPackages) {
6295            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6296                    .getEphemeralApplicationsLPw(userId);
6297            if (ephemeralApps != null) {
6298                return new ParceledListSlice<>(ephemeralApps);
6299            }
6300        }
6301        return null;
6302    }
6303
6304    @Override
6305    public boolean isEphemeralApplication(String packageName, int userId) {
6306        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6307                true /* requireFullPermission */, false /* checkShell */,
6308                "isEphemeral");
6309        if (isEphemeralDisabled()) {
6310            return false;
6311        }
6312
6313        if (!isCallerSameApp(packageName)) {
6314            return false;
6315        }
6316        synchronized (mPackages) {
6317            PackageParser.Package pkg = mPackages.get(packageName);
6318            if (pkg != null) {
6319                return pkg.applicationInfo.isEphemeralApp();
6320            }
6321        }
6322        return false;
6323    }
6324
6325    @Override
6326    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6327        if (isEphemeralDisabled()) {
6328            return null;
6329        }
6330
6331        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6332                true /* requireFullPermission */, false /* checkShell */,
6333                "getCookie");
6334        if (!isCallerSameApp(packageName)) {
6335            return null;
6336        }
6337        synchronized (mPackages) {
6338            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6339                    packageName, userId);
6340        }
6341    }
6342
6343    @Override
6344    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6345        if (isEphemeralDisabled()) {
6346            return true;
6347        }
6348
6349        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6350                true /* requireFullPermission */, true /* checkShell */,
6351                "setCookie");
6352        if (!isCallerSameApp(packageName)) {
6353            return false;
6354        }
6355        synchronized (mPackages) {
6356            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6357                    packageName, cookie, userId);
6358        }
6359    }
6360
6361    @Override
6362    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6363        if (isEphemeralDisabled()) {
6364            return null;
6365        }
6366
6367        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6368                "getEphemeralApplicationIcon");
6369        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6370                true /* requireFullPermission */, false /* checkShell */,
6371                "getEphemeralApplicationIcon");
6372        synchronized (mPackages) {
6373            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6374                    packageName, userId);
6375        }
6376    }
6377
6378    private boolean isCallerSameApp(String packageName) {
6379        PackageParser.Package pkg = mPackages.get(packageName);
6380        return pkg != null
6381                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6382    }
6383
6384    @Override
6385    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6386        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6387    }
6388
6389    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6390        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6391
6392        // reader
6393        synchronized (mPackages) {
6394            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6395            final int userId = UserHandle.getCallingUserId();
6396            while (i.hasNext()) {
6397                final PackageParser.Package p = i.next();
6398                if (p.applicationInfo == null) continue;
6399
6400                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6401                        && !p.applicationInfo.isDirectBootAware();
6402                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6403                        && p.applicationInfo.isDirectBootAware();
6404
6405                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6406                        && (!mSafeMode || isSystemApp(p))
6407                        && (matchesUnaware || matchesAware)) {
6408                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6409                    if (ps != null) {
6410                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6411                                ps.readUserState(userId), userId);
6412                        if (ai != null) {
6413                            finalList.add(ai);
6414                        }
6415                    }
6416                }
6417            }
6418        }
6419
6420        return finalList;
6421    }
6422
6423    @Override
6424    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6425        if (!sUserManager.exists(userId)) return null;
6426        flags = updateFlagsForComponent(flags, userId, name);
6427        // reader
6428        synchronized (mPackages) {
6429            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6430            PackageSetting ps = provider != null
6431                    ? mSettings.mPackages.get(provider.owner.packageName)
6432                    : null;
6433            return ps != null
6434                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6435                    ? PackageParser.generateProviderInfo(provider, flags,
6436                            ps.readUserState(userId), userId)
6437                    : null;
6438        }
6439    }
6440
6441    /**
6442     * @deprecated
6443     */
6444    @Deprecated
6445    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6446        // reader
6447        synchronized (mPackages) {
6448            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6449                    .entrySet().iterator();
6450            final int userId = UserHandle.getCallingUserId();
6451            while (i.hasNext()) {
6452                Map.Entry<String, PackageParser.Provider> entry = i.next();
6453                PackageParser.Provider p = entry.getValue();
6454                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6455
6456                if (ps != null && p.syncable
6457                        && (!mSafeMode || (p.info.applicationInfo.flags
6458                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6459                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6460                            ps.readUserState(userId), userId);
6461                    if (info != null) {
6462                        outNames.add(entry.getKey());
6463                        outInfo.add(info);
6464                    }
6465                }
6466            }
6467        }
6468    }
6469
6470    @Override
6471    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6472            int uid, int flags) {
6473        final int userId = processName != null ? UserHandle.getUserId(uid)
6474                : UserHandle.getCallingUserId();
6475        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6476        flags = updateFlagsForComponent(flags, userId, processName);
6477
6478        ArrayList<ProviderInfo> finalList = null;
6479        // reader
6480        synchronized (mPackages) {
6481            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6482            while (i.hasNext()) {
6483                final PackageParser.Provider p = i.next();
6484                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6485                if (ps != null && p.info.authority != null
6486                        && (processName == null
6487                                || (p.info.processName.equals(processName)
6488                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6489                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6490                    if (finalList == null) {
6491                        finalList = new ArrayList<ProviderInfo>(3);
6492                    }
6493                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6494                            ps.readUserState(userId), userId);
6495                    if (info != null) {
6496                        finalList.add(info);
6497                    }
6498                }
6499            }
6500        }
6501
6502        if (finalList != null) {
6503            Collections.sort(finalList, mProviderInitOrderSorter);
6504            return new ParceledListSlice<ProviderInfo>(finalList);
6505        }
6506
6507        return ParceledListSlice.emptyList();
6508    }
6509
6510    @Override
6511    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6512        // reader
6513        synchronized (mPackages) {
6514            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6515            return PackageParser.generateInstrumentationInfo(i, flags);
6516        }
6517    }
6518
6519    @Override
6520    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6521            String targetPackage, int flags) {
6522        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6523    }
6524
6525    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6526            int flags) {
6527        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6528
6529        // reader
6530        synchronized (mPackages) {
6531            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6532            while (i.hasNext()) {
6533                final PackageParser.Instrumentation p = i.next();
6534                if (targetPackage == null
6535                        || targetPackage.equals(p.info.targetPackage)) {
6536                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6537                            flags);
6538                    if (ii != null) {
6539                        finalList.add(ii);
6540                    }
6541                }
6542            }
6543        }
6544
6545        return finalList;
6546    }
6547
6548    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6549        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6550        if (overlays == null) {
6551            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6552            return;
6553        }
6554        for (PackageParser.Package opkg : overlays.values()) {
6555            // Not much to do if idmap fails: we already logged the error
6556            // and we certainly don't want to abort installation of pkg simply
6557            // because an overlay didn't fit properly. For these reasons,
6558            // ignore the return value of createIdmapForPackagePairLI.
6559            createIdmapForPackagePairLI(pkg, opkg);
6560        }
6561    }
6562
6563    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6564            PackageParser.Package opkg) {
6565        if (!opkg.mTrustedOverlay) {
6566            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6567                    opkg.baseCodePath + ": overlay not trusted");
6568            return false;
6569        }
6570        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6571        if (overlaySet == null) {
6572            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6573                    opkg.baseCodePath + " but target package has no known overlays");
6574            return false;
6575        }
6576        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6577        // TODO: generate idmap for split APKs
6578        try {
6579            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6580        } catch (InstallerException e) {
6581            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6582                    + opkg.baseCodePath);
6583            return false;
6584        }
6585        PackageParser.Package[] overlayArray =
6586            overlaySet.values().toArray(new PackageParser.Package[0]);
6587        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6588            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6589                return p1.mOverlayPriority - p2.mOverlayPriority;
6590            }
6591        };
6592        Arrays.sort(overlayArray, cmp);
6593
6594        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6595        int i = 0;
6596        for (PackageParser.Package p : overlayArray) {
6597            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6598        }
6599        return true;
6600    }
6601
6602    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6603        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6604        try {
6605            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6606        } finally {
6607            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6608        }
6609    }
6610
6611    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6612        final File[] files = dir.listFiles();
6613        if (ArrayUtils.isEmpty(files)) {
6614            Log.d(TAG, "No files in app dir " + dir);
6615            return;
6616        }
6617
6618        if (DEBUG_PACKAGE_SCANNING) {
6619            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6620                    + " flags=0x" + Integer.toHexString(parseFlags));
6621        }
6622
6623        for (File file : files) {
6624            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6625                    && !PackageInstallerService.isStageName(file.getName());
6626            if (!isPackage) {
6627                // Ignore entries which are not packages
6628                continue;
6629            }
6630            try {
6631                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6632                        scanFlags, currentTime, null);
6633            } catch (PackageManagerException e) {
6634                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6635
6636                // Delete invalid userdata apps
6637                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6638                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6639                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6640                    removeCodePathLI(file);
6641                }
6642            }
6643        }
6644    }
6645
6646    private static File getSettingsProblemFile() {
6647        File dataDir = Environment.getDataDirectory();
6648        File systemDir = new File(dataDir, "system");
6649        File fname = new File(systemDir, "uiderrors.txt");
6650        return fname;
6651    }
6652
6653    static void reportSettingsProblem(int priority, String msg) {
6654        logCriticalInfo(priority, msg);
6655    }
6656
6657    static void logCriticalInfo(int priority, String msg) {
6658        Slog.println(priority, TAG, msg);
6659        EventLogTags.writePmCriticalInfo(msg);
6660        try {
6661            File fname = getSettingsProblemFile();
6662            FileOutputStream out = new FileOutputStream(fname, true);
6663            PrintWriter pw = new FastPrintWriter(out);
6664            SimpleDateFormat formatter = new SimpleDateFormat();
6665            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6666            pw.println(dateString + ": " + msg);
6667            pw.close();
6668            FileUtils.setPermissions(
6669                    fname.toString(),
6670                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6671                    -1, -1);
6672        } catch (java.io.IOException e) {
6673        }
6674    }
6675
6676    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6677        if (srcFile.isDirectory()) {
6678            final File baseFile = new File(pkg.baseCodePath);
6679            long maxModifiedTime = baseFile.lastModified();
6680            if (pkg.splitCodePaths != null) {
6681                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6682                    final File splitFile = new File(pkg.splitCodePaths[i]);
6683                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6684                }
6685            }
6686            return maxModifiedTime;
6687        }
6688        return srcFile.lastModified();
6689    }
6690
6691    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6692            final int policyFlags) throws PackageManagerException {
6693        // When upgrading from pre-N MR1, verify the package time stamp using the package
6694        // directory and not the APK file.
6695        final long lastModifiedTime = mIsPreNMR1Upgrade
6696                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6697        if (ps != null
6698                && ps.codePath.equals(srcFile)
6699                && ps.timeStamp == lastModifiedTime
6700                && !isCompatSignatureUpdateNeeded(pkg)
6701                && !isRecoverSignatureUpdateNeeded(pkg)) {
6702            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6703            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6704            ArraySet<PublicKey> signingKs;
6705            synchronized (mPackages) {
6706                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6707            }
6708            if (ps.signatures.mSignatures != null
6709                    && ps.signatures.mSignatures.length != 0
6710                    && signingKs != null) {
6711                // Optimization: reuse the existing cached certificates
6712                // if the package appears to be unchanged.
6713                pkg.mSignatures = ps.signatures.mSignatures;
6714                pkg.mSigningKeys = signingKs;
6715                return;
6716            }
6717
6718            Slog.w(TAG, "PackageSetting for " + ps.name
6719                    + " is missing signatures.  Collecting certs again to recover them.");
6720        } else {
6721            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6722        }
6723
6724        try {
6725            PackageParser.collectCertificates(pkg, policyFlags);
6726        } catch (PackageParserException e) {
6727            throw PackageManagerException.from(e);
6728        }
6729    }
6730
6731    /**
6732     *  Traces a package scan.
6733     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6734     */
6735    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6736            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6737        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6738        try {
6739            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6740        } finally {
6741            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6742        }
6743    }
6744
6745    /**
6746     *  Scans a package and returns the newly parsed package.
6747     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6748     */
6749    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6750            long currentTime, UserHandle user) throws PackageManagerException {
6751        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6752        PackageParser pp = new PackageParser();
6753        pp.setSeparateProcesses(mSeparateProcesses);
6754        pp.setOnlyCoreApps(mOnlyCore);
6755        pp.setDisplayMetrics(mMetrics);
6756
6757        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6758            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6759        }
6760
6761        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6762        final PackageParser.Package pkg;
6763        try {
6764            pkg = pp.parsePackage(scanFile, parseFlags);
6765        } catch (PackageParserException e) {
6766            throw PackageManagerException.from(e);
6767        } finally {
6768            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6769        }
6770
6771        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6772    }
6773
6774    /**
6775     *  Scans a package and returns the newly parsed package.
6776     *  @throws PackageManagerException on a parse error.
6777     */
6778    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6779            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6780            throws PackageManagerException {
6781        // If the package has children and this is the first dive in the function
6782        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6783        // packages (parent and children) would be successfully scanned before the
6784        // actual scan since scanning mutates internal state and we want to atomically
6785        // install the package and its children.
6786        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6787            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6788                scanFlags |= SCAN_CHECK_ONLY;
6789            }
6790        } else {
6791            scanFlags &= ~SCAN_CHECK_ONLY;
6792        }
6793
6794        // Scan the parent
6795        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6796                scanFlags, currentTime, user);
6797
6798        // Scan the children
6799        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6800        for (int i = 0; i < childCount; i++) {
6801            PackageParser.Package childPackage = pkg.childPackages.get(i);
6802            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6803                    currentTime, user);
6804        }
6805
6806
6807        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6808            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6809        }
6810
6811        return scannedPkg;
6812    }
6813
6814    /**
6815     *  Scans a package and returns the newly parsed package.
6816     *  @throws PackageManagerException on a parse error.
6817     */
6818    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6819            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6820            throws PackageManagerException {
6821        PackageSetting ps = null;
6822        PackageSetting updatedPkg;
6823        // reader
6824        synchronized (mPackages) {
6825            // Look to see if we already know about this package.
6826            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6827            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6828                // This package has been renamed to its original name.  Let's
6829                // use that.
6830                ps = mSettings.peekPackageLPr(oldName);
6831            }
6832            // If there was no original package, see one for the real package name.
6833            if (ps == null) {
6834                ps = mSettings.peekPackageLPr(pkg.packageName);
6835            }
6836            // Check to see if this package could be hiding/updating a system
6837            // package.  Must look for it either under the original or real
6838            // package name depending on our state.
6839            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6840            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6841
6842            // If this is a package we don't know about on the system partition, we
6843            // may need to remove disabled child packages on the system partition
6844            // or may need to not add child packages if the parent apk is updated
6845            // on the data partition and no longer defines this child package.
6846            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6847                // If this is a parent package for an updated system app and this system
6848                // app got an OTA update which no longer defines some of the child packages
6849                // we have to prune them from the disabled system packages.
6850                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6851                if (disabledPs != null) {
6852                    final int scannedChildCount = (pkg.childPackages != null)
6853                            ? pkg.childPackages.size() : 0;
6854                    final int disabledChildCount = disabledPs.childPackageNames != null
6855                            ? disabledPs.childPackageNames.size() : 0;
6856                    for (int i = 0; i < disabledChildCount; i++) {
6857                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6858                        boolean disabledPackageAvailable = false;
6859                        for (int j = 0; j < scannedChildCount; j++) {
6860                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6861                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6862                                disabledPackageAvailable = true;
6863                                break;
6864                            }
6865                         }
6866                         if (!disabledPackageAvailable) {
6867                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6868                         }
6869                    }
6870                }
6871            }
6872        }
6873
6874        boolean updatedPkgBetter = false;
6875        // First check if this is a system package that may involve an update
6876        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6877            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6878            // it needs to drop FLAG_PRIVILEGED.
6879            if (locationIsPrivileged(scanFile)) {
6880                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6881            } else {
6882                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6883            }
6884
6885            if (ps != null && !ps.codePath.equals(scanFile)) {
6886                // The path has changed from what was last scanned...  check the
6887                // version of the new path against what we have stored to determine
6888                // what to do.
6889                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6890                if (pkg.mVersionCode <= ps.versionCode) {
6891                    // The system package has been updated and the code path does not match
6892                    // Ignore entry. Skip it.
6893                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6894                            + " ignored: updated version " + ps.versionCode
6895                            + " better than this " + pkg.mVersionCode);
6896                    if (!updatedPkg.codePath.equals(scanFile)) {
6897                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6898                                + ps.name + " changing from " + updatedPkg.codePathString
6899                                + " to " + scanFile);
6900                        updatedPkg.codePath = scanFile;
6901                        updatedPkg.codePathString = scanFile.toString();
6902                        updatedPkg.resourcePath = scanFile;
6903                        updatedPkg.resourcePathString = scanFile.toString();
6904                    }
6905                    updatedPkg.pkg = pkg;
6906                    updatedPkg.versionCode = pkg.mVersionCode;
6907
6908                    // Update the disabled system child packages to point to the package too.
6909                    final int childCount = updatedPkg.childPackageNames != null
6910                            ? updatedPkg.childPackageNames.size() : 0;
6911                    for (int i = 0; i < childCount; i++) {
6912                        String childPackageName = updatedPkg.childPackageNames.get(i);
6913                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6914                                childPackageName);
6915                        if (updatedChildPkg != null) {
6916                            updatedChildPkg.pkg = pkg;
6917                            updatedChildPkg.versionCode = pkg.mVersionCode;
6918                        }
6919                    }
6920
6921                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6922                            + scanFile + " ignored: updated version " + ps.versionCode
6923                            + " better than this " + pkg.mVersionCode);
6924                } else {
6925                    // The current app on the system partition is better than
6926                    // what we have updated to on the data partition; switch
6927                    // back to the system partition version.
6928                    // At this point, its safely assumed that package installation for
6929                    // apps in system partition will go through. If not there won't be a working
6930                    // version of the app
6931                    // writer
6932                    synchronized (mPackages) {
6933                        // Just remove the loaded entries from package lists.
6934                        mPackages.remove(ps.name);
6935                    }
6936
6937                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6938                            + " reverting from " + ps.codePathString
6939                            + ": new version " + pkg.mVersionCode
6940                            + " better than installed " + ps.versionCode);
6941
6942                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6943                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6944                    synchronized (mInstallLock) {
6945                        args.cleanUpResourcesLI();
6946                    }
6947                    synchronized (mPackages) {
6948                        mSettings.enableSystemPackageLPw(ps.name);
6949                    }
6950                    updatedPkgBetter = true;
6951                }
6952            }
6953        }
6954
6955        if (updatedPkg != null) {
6956            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6957            // initially
6958            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6959
6960            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6961            // flag set initially
6962            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6963                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6964            }
6965        }
6966
6967        // Verify certificates against what was last scanned
6968        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6969
6970        /*
6971         * A new system app appeared, but we already had a non-system one of the
6972         * same name installed earlier.
6973         */
6974        boolean shouldHideSystemApp = false;
6975        if (updatedPkg == null && ps != null
6976                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6977            /*
6978             * Check to make sure the signatures match first. If they don't,
6979             * wipe the installed application and its data.
6980             */
6981            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6982                    != PackageManager.SIGNATURE_MATCH) {
6983                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6984                        + " signatures don't match existing userdata copy; removing");
6985                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6986                        "scanPackageInternalLI")) {
6987                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6988                }
6989                ps = null;
6990            } else {
6991                /*
6992                 * If the newly-added system app is an older version than the
6993                 * already installed version, hide it. It will be scanned later
6994                 * and re-added like an update.
6995                 */
6996                if (pkg.mVersionCode <= ps.versionCode) {
6997                    shouldHideSystemApp = true;
6998                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6999                            + " but new version " + pkg.mVersionCode + " better than installed "
7000                            + ps.versionCode + "; hiding system");
7001                } else {
7002                    /*
7003                     * The newly found system app is a newer version that the
7004                     * one previously installed. Simply remove the
7005                     * already-installed application and replace it with our own
7006                     * while keeping the application data.
7007                     */
7008                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7009                            + " reverting from " + ps.codePathString + ": new version "
7010                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7011                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7012                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7013                    synchronized (mInstallLock) {
7014                        args.cleanUpResourcesLI();
7015                    }
7016                }
7017            }
7018        }
7019
7020        // The apk is forward locked (not public) if its code and resources
7021        // are kept in different files. (except for app in either system or
7022        // vendor path).
7023        // TODO grab this value from PackageSettings
7024        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7025            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7026                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7027            }
7028        }
7029
7030        // TODO: extend to support forward-locked splits
7031        String resourcePath = null;
7032        String baseResourcePath = null;
7033        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7034            if (ps != null && ps.resourcePathString != null) {
7035                resourcePath = ps.resourcePathString;
7036                baseResourcePath = ps.resourcePathString;
7037            } else {
7038                // Should not happen at all. Just log an error.
7039                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7040            }
7041        } else {
7042            resourcePath = pkg.codePath;
7043            baseResourcePath = pkg.baseCodePath;
7044        }
7045
7046        // Set application objects path explicitly.
7047        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7048        pkg.setApplicationInfoCodePath(pkg.codePath);
7049        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7050        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7051        pkg.setApplicationInfoResourcePath(resourcePath);
7052        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7053        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7054
7055        // Note that we invoke the following method only if we are about to unpack an application
7056        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7057                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7058
7059        /*
7060         * If the system app should be overridden by a previously installed
7061         * data, hide the system app now and let the /data/app scan pick it up
7062         * again.
7063         */
7064        if (shouldHideSystemApp) {
7065            synchronized (mPackages) {
7066                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7067            }
7068        }
7069
7070        return scannedPkg;
7071    }
7072
7073    private static String fixProcessName(String defProcessName,
7074            String processName, int uid) {
7075        if (processName == null) {
7076            return defProcessName;
7077        }
7078        return processName;
7079    }
7080
7081    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7082            throws PackageManagerException {
7083        if (pkgSetting.signatures.mSignatures != null) {
7084            // Already existing package. Make sure signatures match
7085            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7086                    == PackageManager.SIGNATURE_MATCH;
7087            if (!match) {
7088                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7089                        == PackageManager.SIGNATURE_MATCH;
7090            }
7091            if (!match) {
7092                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7093                        == PackageManager.SIGNATURE_MATCH;
7094            }
7095            if (!match) {
7096                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7097                        + pkg.packageName + " signatures do not match the "
7098                        + "previously installed version; ignoring!");
7099            }
7100        }
7101
7102        // Check for shared user signatures
7103        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7104            // Already existing package. Make sure signatures match
7105            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7106                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7107            if (!match) {
7108                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7109                        == PackageManager.SIGNATURE_MATCH;
7110            }
7111            if (!match) {
7112                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7113                        == PackageManager.SIGNATURE_MATCH;
7114            }
7115            if (!match) {
7116                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7117                        "Package " + pkg.packageName
7118                        + " has no signatures that match those in shared user "
7119                        + pkgSetting.sharedUser.name + "; ignoring!");
7120            }
7121        }
7122    }
7123
7124    /**
7125     * Enforces that only the system UID or root's UID can call a method exposed
7126     * via Binder.
7127     *
7128     * @param message used as message if SecurityException is thrown
7129     * @throws SecurityException if the caller is not system or root
7130     */
7131    private static final void enforceSystemOrRoot(String message) {
7132        final int uid = Binder.getCallingUid();
7133        if (uid != Process.SYSTEM_UID && uid != 0) {
7134            throw new SecurityException(message);
7135        }
7136    }
7137
7138    @Override
7139    public void performFstrimIfNeeded() {
7140        enforceSystemOrRoot("Only the system can request fstrim");
7141
7142        // Before everything else, see whether we need to fstrim.
7143        try {
7144            IMountService ms = PackageHelper.getMountService();
7145            if (ms != null) {
7146                boolean doTrim = false;
7147                final long interval = android.provider.Settings.Global.getLong(
7148                        mContext.getContentResolver(),
7149                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7150                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7151                if (interval > 0) {
7152                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7153                    if (timeSinceLast > interval) {
7154                        doTrim = true;
7155                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7156                                + "; running immediately");
7157                    }
7158                }
7159                if (doTrim) {
7160                    final boolean dexOptDialogShown;
7161                    synchronized (mPackages) {
7162                        dexOptDialogShown = mDexOptDialogShown;
7163                    }
7164                    if (!isFirstBoot() && dexOptDialogShown) {
7165                        try {
7166                            ActivityManagerNative.getDefault().showBootMessage(
7167                                    mContext.getResources().getString(
7168                                            R.string.android_upgrading_fstrim), true);
7169                        } catch (RemoteException e) {
7170                        }
7171                    }
7172                    ms.runMaintenance();
7173                }
7174            } else {
7175                Slog.e(TAG, "Mount service unavailable!");
7176            }
7177        } catch (RemoteException e) {
7178            // Can't happen; MountService is local
7179        }
7180    }
7181
7182    @Override
7183    public void updatePackagesIfNeeded() {
7184        enforceSystemOrRoot("Only the system can request package update");
7185
7186        // We need to re-extract after an OTA.
7187        boolean causeUpgrade = isUpgrade();
7188
7189        // First boot or factory reset.
7190        // Note: we also handle devices that are upgrading to N right now as if it is their
7191        //       first boot, as they do not have profile data.
7192        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7193
7194        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7195        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7196
7197        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7198            return;
7199        }
7200
7201        List<PackageParser.Package> pkgs;
7202        synchronized (mPackages) {
7203            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7204        }
7205
7206        final long startTime = System.nanoTime();
7207        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7208                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7209
7210        final int elapsedTimeSeconds =
7211                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7212
7213        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7214        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7215        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7216        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7217        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7218    }
7219
7220    /**
7221     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7222     * containing statistics about the invocation. The array consists of three elements,
7223     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7224     * and {@code numberOfPackagesFailed}.
7225     */
7226    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7227            String compilerFilter) {
7228
7229        int numberOfPackagesVisited = 0;
7230        int numberOfPackagesOptimized = 0;
7231        int numberOfPackagesSkipped = 0;
7232        int numberOfPackagesFailed = 0;
7233        final int numberOfPackagesToDexopt = pkgs.size();
7234
7235        for (PackageParser.Package pkg : pkgs) {
7236            numberOfPackagesVisited++;
7237
7238            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7239                if (DEBUG_DEXOPT) {
7240                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7241                }
7242                numberOfPackagesSkipped++;
7243                continue;
7244            }
7245
7246            if (DEBUG_DEXOPT) {
7247                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7248                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7249            }
7250
7251            if (showDialog) {
7252                try {
7253                    ActivityManagerNative.getDefault().showBootMessage(
7254                            mContext.getResources().getString(R.string.android_upgrading_apk,
7255                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7256                } catch (RemoteException e) {
7257                }
7258                synchronized (mPackages) {
7259                    mDexOptDialogShown = true;
7260                }
7261            }
7262
7263            // If the OTA updates a system app which was previously preopted to a non-preopted state
7264            // the app might end up being verified at runtime. That's because by default the apps
7265            // are verify-profile but for preopted apps there's no profile.
7266            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7267            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7268            // filter (by default interpret-only).
7269            // Note that at this stage unused apps are already filtered.
7270            if (isSystemApp(pkg) &&
7271                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7272                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7273                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7274            }
7275
7276            // checkProfiles is false to avoid merging profiles during boot which
7277            // might interfere with background compilation (b/28612421).
7278            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7279            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7280            // trade-off worth doing to save boot time work.
7281            int dexOptStatus = performDexOptTraced(pkg.packageName,
7282                    false /* checkProfiles */,
7283                    compilerFilter,
7284                    false /* force */);
7285            switch (dexOptStatus) {
7286                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7287                    numberOfPackagesOptimized++;
7288                    break;
7289                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7290                    numberOfPackagesSkipped++;
7291                    break;
7292                case PackageDexOptimizer.DEX_OPT_FAILED:
7293                    numberOfPackagesFailed++;
7294                    break;
7295                default:
7296                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7297                    break;
7298            }
7299        }
7300
7301        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7302                numberOfPackagesFailed };
7303    }
7304
7305    @Override
7306    public void notifyPackageUse(String packageName, int reason) {
7307        synchronized (mPackages) {
7308            PackageParser.Package p = mPackages.get(packageName);
7309            if (p == null) {
7310                return;
7311            }
7312            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7313        }
7314    }
7315
7316    // TODO: this is not used nor needed. Delete it.
7317    @Override
7318    public boolean performDexOptIfNeeded(String packageName) {
7319        int dexOptStatus = performDexOptTraced(packageName,
7320                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7321        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7322    }
7323
7324    @Override
7325    public boolean performDexOpt(String packageName,
7326            boolean checkProfiles, int compileReason, boolean force) {
7327        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7328                getCompilerFilterForReason(compileReason), force);
7329        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7330    }
7331
7332    @Override
7333    public boolean performDexOptMode(String packageName,
7334            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7335        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7336                targetCompilerFilter, force);
7337        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7338    }
7339
7340    private int performDexOptTraced(String packageName,
7341                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7342        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7343        try {
7344            return performDexOptInternal(packageName, checkProfiles,
7345                    targetCompilerFilter, force);
7346        } finally {
7347            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7348        }
7349    }
7350
7351    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7352    // if the package can now be considered up to date for the given filter.
7353    private int performDexOptInternal(String packageName,
7354                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7355        PackageParser.Package p;
7356        synchronized (mPackages) {
7357            p = mPackages.get(packageName);
7358            if (p == null) {
7359                // Package could not be found. Report failure.
7360                return PackageDexOptimizer.DEX_OPT_FAILED;
7361            }
7362            mPackageUsage.maybeWriteAsync(mPackages);
7363            mCompilerStats.maybeWriteAsync();
7364        }
7365        long callingId = Binder.clearCallingIdentity();
7366        try {
7367            synchronized (mInstallLock) {
7368                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7369                        targetCompilerFilter, force);
7370            }
7371        } finally {
7372            Binder.restoreCallingIdentity(callingId);
7373        }
7374    }
7375
7376    public ArraySet<String> getOptimizablePackages() {
7377        ArraySet<String> pkgs = new ArraySet<String>();
7378        synchronized (mPackages) {
7379            for (PackageParser.Package p : mPackages.values()) {
7380                if (PackageDexOptimizer.canOptimizePackage(p)) {
7381                    pkgs.add(p.packageName);
7382                }
7383            }
7384        }
7385        return pkgs;
7386    }
7387
7388    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7389            boolean checkProfiles, String targetCompilerFilter,
7390            boolean force) {
7391        // Select the dex optimizer based on the force parameter.
7392        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7393        //       allocate an object here.
7394        PackageDexOptimizer pdo = force
7395                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7396                : mPackageDexOptimizer;
7397
7398        // Optimize all dependencies first. Note: we ignore the return value and march on
7399        // on errors.
7400        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7401        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7402        if (!deps.isEmpty()) {
7403            for (PackageParser.Package depPackage : deps) {
7404                // TODO: Analyze and investigate if we (should) profile libraries.
7405                // Currently this will do a full compilation of the library by default.
7406                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7407                        false /* checkProfiles */,
7408                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7409                        getOrCreateCompilerPackageStats(depPackage));
7410            }
7411        }
7412        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7413                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7414    }
7415
7416    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7417        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7418            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7419            Set<String> collectedNames = new HashSet<>();
7420            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7421
7422            retValue.remove(p);
7423
7424            return retValue;
7425        } else {
7426            return Collections.emptyList();
7427        }
7428    }
7429
7430    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7431            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7432        if (!collectedNames.contains(p.packageName)) {
7433            collectedNames.add(p.packageName);
7434            collected.add(p);
7435
7436            if (p.usesLibraries != null) {
7437                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7438            }
7439            if (p.usesOptionalLibraries != null) {
7440                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7441                        collectedNames);
7442            }
7443        }
7444    }
7445
7446    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7447            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7448        for (String libName : libs) {
7449            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7450            if (libPkg != null) {
7451                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7452            }
7453        }
7454    }
7455
7456    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7457        synchronized (mPackages) {
7458            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7459            if (lib != null && lib.apk != null) {
7460                return mPackages.get(lib.apk);
7461            }
7462        }
7463        return null;
7464    }
7465
7466    public void shutdown() {
7467        mPackageUsage.writeNow(mPackages);
7468        mCompilerStats.writeNow();
7469    }
7470
7471    @Override
7472    public void dumpProfiles(String packageName) {
7473        PackageParser.Package pkg;
7474        synchronized (mPackages) {
7475            pkg = mPackages.get(packageName);
7476            if (pkg == null) {
7477                throw new IllegalArgumentException("Unknown package: " + packageName);
7478            }
7479        }
7480        /* Only the shell, root, or the app user should be able to dump profiles. */
7481        int callingUid = Binder.getCallingUid();
7482        if (callingUid != Process.SHELL_UID &&
7483            callingUid != Process.ROOT_UID &&
7484            callingUid != pkg.applicationInfo.uid) {
7485            throw new SecurityException("dumpProfiles");
7486        }
7487
7488        synchronized (mInstallLock) {
7489            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7490            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7491            try {
7492                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7493                String gid = Integer.toString(sharedGid);
7494                String codePaths = TextUtils.join(";", allCodePaths);
7495                mInstaller.dumpProfiles(gid, packageName, codePaths);
7496            } catch (InstallerException e) {
7497                Slog.w(TAG, "Failed to dump profiles", e);
7498            }
7499            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7500        }
7501    }
7502
7503    @Override
7504    public void forceDexOpt(String packageName) {
7505        enforceSystemOrRoot("forceDexOpt");
7506
7507        PackageParser.Package pkg;
7508        synchronized (mPackages) {
7509            pkg = mPackages.get(packageName);
7510            if (pkg == null) {
7511                throw new IllegalArgumentException("Unknown package: " + packageName);
7512            }
7513        }
7514
7515        synchronized (mInstallLock) {
7516            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7517
7518            // Whoever is calling forceDexOpt wants a fully compiled package.
7519            // Don't use profiles since that may cause compilation to be skipped.
7520            final int res = performDexOptInternalWithDependenciesLI(pkg,
7521                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7522                    true /* force */);
7523
7524            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7525            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7526                throw new IllegalStateException("Failed to dexopt: " + res);
7527            }
7528        }
7529    }
7530
7531    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7532        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7533            Slog.w(TAG, "Unable to update from " + oldPkg.name
7534                    + " to " + newPkg.packageName
7535                    + ": old package not in system partition");
7536            return false;
7537        } else if (mPackages.get(oldPkg.name) != null) {
7538            Slog.w(TAG, "Unable to update from " + oldPkg.name
7539                    + " to " + newPkg.packageName
7540                    + ": old package still exists");
7541            return false;
7542        }
7543        return true;
7544    }
7545
7546    void removeCodePathLI(File codePath) {
7547        if (codePath.isDirectory()) {
7548            try {
7549                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7550            } catch (InstallerException e) {
7551                Slog.w(TAG, "Failed to remove code path", e);
7552            }
7553        } else {
7554            codePath.delete();
7555        }
7556    }
7557
7558    private int[] resolveUserIds(int userId) {
7559        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7560    }
7561
7562    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7563        if (pkg == null) {
7564            Slog.wtf(TAG, "Package was null!", new Throwable());
7565            return;
7566        }
7567        clearAppDataLeafLIF(pkg, userId, flags);
7568        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7569        for (int i = 0; i < childCount; i++) {
7570            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7571        }
7572    }
7573
7574    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7575        final PackageSetting ps;
7576        synchronized (mPackages) {
7577            ps = mSettings.mPackages.get(pkg.packageName);
7578        }
7579        for (int realUserId : resolveUserIds(userId)) {
7580            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7581            try {
7582                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7583                        ceDataInode);
7584            } catch (InstallerException e) {
7585                Slog.w(TAG, String.valueOf(e));
7586            }
7587        }
7588    }
7589
7590    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7591        if (pkg == null) {
7592            Slog.wtf(TAG, "Package was null!", new Throwable());
7593            return;
7594        }
7595        destroyAppDataLeafLIF(pkg, userId, flags);
7596        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7597        for (int i = 0; i < childCount; i++) {
7598            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7599        }
7600    }
7601
7602    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7603        final PackageSetting ps;
7604        synchronized (mPackages) {
7605            ps = mSettings.mPackages.get(pkg.packageName);
7606        }
7607        for (int realUserId : resolveUserIds(userId)) {
7608            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7609            try {
7610                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7611                        ceDataInode);
7612            } catch (InstallerException e) {
7613                Slog.w(TAG, String.valueOf(e));
7614            }
7615        }
7616    }
7617
7618    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7619        if (pkg == null) {
7620            Slog.wtf(TAG, "Package was null!", new Throwable());
7621            return;
7622        }
7623        destroyAppProfilesLeafLIF(pkg);
7624        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7625        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7626        for (int i = 0; i < childCount; i++) {
7627            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7628            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7629                    true /* removeBaseMarker */);
7630        }
7631    }
7632
7633    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7634            boolean removeBaseMarker) {
7635        if (pkg.isForwardLocked()) {
7636            return;
7637        }
7638
7639        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7640            try {
7641                path = PackageManagerServiceUtils.realpath(new File(path));
7642            } catch (IOException e) {
7643                // TODO: Should we return early here ?
7644                Slog.w(TAG, "Failed to get canonical path", e);
7645                continue;
7646            }
7647
7648            final String useMarker = path.replace('/', '@');
7649            for (int realUserId : resolveUserIds(userId)) {
7650                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7651                if (removeBaseMarker) {
7652                    File foreignUseMark = new File(profileDir, useMarker);
7653                    if (foreignUseMark.exists()) {
7654                        if (!foreignUseMark.delete()) {
7655                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7656                                    + pkg.packageName);
7657                        }
7658                    }
7659                }
7660
7661                File[] markers = profileDir.listFiles();
7662                if (markers != null) {
7663                    final String searchString = "@" + pkg.packageName + "@";
7664                    // We also delete all markers that contain the package name we're
7665                    // uninstalling. These are associated with secondary dex-files belonging
7666                    // to the package. Reconstructing the path of these dex files is messy
7667                    // in general.
7668                    for (File marker : markers) {
7669                        if (marker.getName().indexOf(searchString) > 0) {
7670                            if (!marker.delete()) {
7671                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7672                                    + pkg.packageName);
7673                            }
7674                        }
7675                    }
7676                }
7677            }
7678        }
7679    }
7680
7681    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7682        try {
7683            mInstaller.destroyAppProfiles(pkg.packageName);
7684        } catch (InstallerException e) {
7685            Slog.w(TAG, String.valueOf(e));
7686        }
7687    }
7688
7689    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7690        if (pkg == null) {
7691            Slog.wtf(TAG, "Package was null!", new Throwable());
7692            return;
7693        }
7694        clearAppProfilesLeafLIF(pkg);
7695        // We don't remove the base foreign use marker when clearing profiles because
7696        // we will rename it when the app is updated. Unlike the actual profile contents,
7697        // the foreign use marker is good across installs.
7698        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7699        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7700        for (int i = 0; i < childCount; i++) {
7701            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7702        }
7703    }
7704
7705    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7706        try {
7707            mInstaller.clearAppProfiles(pkg.packageName);
7708        } catch (InstallerException e) {
7709            Slog.w(TAG, String.valueOf(e));
7710        }
7711    }
7712
7713    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7714            long lastUpdateTime) {
7715        // Set parent install/update time
7716        PackageSetting ps = (PackageSetting) pkg.mExtras;
7717        if (ps != null) {
7718            ps.firstInstallTime = firstInstallTime;
7719            ps.lastUpdateTime = lastUpdateTime;
7720        }
7721        // Set children install/update time
7722        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7723        for (int i = 0; i < childCount; i++) {
7724            PackageParser.Package childPkg = pkg.childPackages.get(i);
7725            ps = (PackageSetting) childPkg.mExtras;
7726            if (ps != null) {
7727                ps.firstInstallTime = firstInstallTime;
7728                ps.lastUpdateTime = lastUpdateTime;
7729            }
7730        }
7731    }
7732
7733    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7734            PackageParser.Package changingLib) {
7735        if (file.path != null) {
7736            usesLibraryFiles.add(file.path);
7737            return;
7738        }
7739        PackageParser.Package p = mPackages.get(file.apk);
7740        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7741            // If we are doing this while in the middle of updating a library apk,
7742            // then we need to make sure to use that new apk for determining the
7743            // dependencies here.  (We haven't yet finished committing the new apk
7744            // to the package manager state.)
7745            if (p == null || p.packageName.equals(changingLib.packageName)) {
7746                p = changingLib;
7747            }
7748        }
7749        if (p != null) {
7750            usesLibraryFiles.addAll(p.getAllCodePaths());
7751        }
7752    }
7753
7754    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7755            PackageParser.Package changingLib) throws PackageManagerException {
7756        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7757            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7758            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7759            for (int i=0; i<N; i++) {
7760                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7761                if (file == null) {
7762                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7763                            "Package " + pkg.packageName + " requires unavailable shared library "
7764                            + pkg.usesLibraries.get(i) + "; failing!");
7765                }
7766                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7767            }
7768            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7769            for (int i=0; i<N; i++) {
7770                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7771                if (file == null) {
7772                    Slog.w(TAG, "Package " + pkg.packageName
7773                            + " desires unavailable shared library "
7774                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7775                } else {
7776                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7777                }
7778            }
7779            N = usesLibraryFiles.size();
7780            if (N > 0) {
7781                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7782            } else {
7783                pkg.usesLibraryFiles = null;
7784            }
7785        }
7786    }
7787
7788    private static boolean hasString(List<String> list, List<String> which) {
7789        if (list == null) {
7790            return false;
7791        }
7792        for (int i=list.size()-1; i>=0; i--) {
7793            for (int j=which.size()-1; j>=0; j--) {
7794                if (which.get(j).equals(list.get(i))) {
7795                    return true;
7796                }
7797            }
7798        }
7799        return false;
7800    }
7801
7802    private void updateAllSharedLibrariesLPw() {
7803        for (PackageParser.Package pkg : mPackages.values()) {
7804            try {
7805                updateSharedLibrariesLPw(pkg, null);
7806            } catch (PackageManagerException e) {
7807                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7808            }
7809        }
7810    }
7811
7812    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7813            PackageParser.Package changingPkg) {
7814        ArrayList<PackageParser.Package> res = null;
7815        for (PackageParser.Package pkg : mPackages.values()) {
7816            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7817                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7818                if (res == null) {
7819                    res = new ArrayList<PackageParser.Package>();
7820                }
7821                res.add(pkg);
7822                try {
7823                    updateSharedLibrariesLPw(pkg, changingPkg);
7824                } catch (PackageManagerException e) {
7825                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7826                }
7827            }
7828        }
7829        return res;
7830    }
7831
7832    /**
7833     * Derive the value of the {@code cpuAbiOverride} based on the provided
7834     * value and an optional stored value from the package settings.
7835     */
7836    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7837        String cpuAbiOverride = null;
7838
7839        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7840            cpuAbiOverride = null;
7841        } else if (abiOverride != null) {
7842            cpuAbiOverride = abiOverride;
7843        } else if (settings != null) {
7844            cpuAbiOverride = settings.cpuAbiOverrideString;
7845        }
7846
7847        return cpuAbiOverride;
7848    }
7849
7850    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7851            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7852                    throws PackageManagerException {
7853        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7854        // If the package has children and this is the first dive in the function
7855        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7856        // whether all packages (parent and children) would be successfully scanned
7857        // before the actual scan since scanning mutates internal state and we want
7858        // to atomically install the package and its children.
7859        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7860            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7861                scanFlags |= SCAN_CHECK_ONLY;
7862            }
7863        } else {
7864            scanFlags &= ~SCAN_CHECK_ONLY;
7865        }
7866
7867        final PackageParser.Package scannedPkg;
7868        try {
7869            // Scan the parent
7870            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7871            // Scan the children
7872            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7873            for (int i = 0; i < childCount; i++) {
7874                PackageParser.Package childPkg = pkg.childPackages.get(i);
7875                scanPackageLI(childPkg, policyFlags,
7876                        scanFlags, currentTime, user);
7877            }
7878        } finally {
7879            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7880        }
7881
7882        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7883            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7884        }
7885
7886        return scannedPkg;
7887    }
7888
7889    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7890            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7891        boolean success = false;
7892        try {
7893            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7894                    currentTime, user);
7895            success = true;
7896            return res;
7897        } finally {
7898            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7899                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7900                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7901                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7902                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7903            }
7904        }
7905    }
7906
7907    /**
7908     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7909     */
7910    private static boolean apkHasCode(String fileName) {
7911        StrictJarFile jarFile = null;
7912        try {
7913            jarFile = new StrictJarFile(fileName,
7914                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7915            return jarFile.findEntry("classes.dex") != null;
7916        } catch (IOException ignore) {
7917        } finally {
7918            try {
7919                if (jarFile != null) {
7920                    jarFile.close();
7921                }
7922            } catch (IOException ignore) {}
7923        }
7924        return false;
7925    }
7926
7927    /**
7928     * Enforces code policy for the package. This ensures that if an APK has
7929     * declared hasCode="true" in its manifest that the APK actually contains
7930     * code.
7931     *
7932     * @throws PackageManagerException If bytecode could not be found when it should exist
7933     */
7934    private static void enforceCodePolicy(PackageParser.Package pkg)
7935            throws PackageManagerException {
7936        final boolean shouldHaveCode =
7937                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7938        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7939            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7940                    "Package " + pkg.baseCodePath + " code is missing");
7941        }
7942
7943        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7944            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7945                final boolean splitShouldHaveCode =
7946                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7947                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7948                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7949                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7950                }
7951            }
7952        }
7953    }
7954
7955    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7956            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7957            throws PackageManagerException {
7958        final File scanFile = new File(pkg.codePath);
7959        if (pkg.applicationInfo.getCodePath() == null ||
7960                pkg.applicationInfo.getResourcePath() == null) {
7961            // Bail out. The resource and code paths haven't been set.
7962            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7963                    "Code and resource paths haven't been set correctly");
7964        }
7965
7966        // Apply policy
7967        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7968            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7969            if (pkg.applicationInfo.isDirectBootAware()) {
7970                // we're direct boot aware; set for all components
7971                for (PackageParser.Service s : pkg.services) {
7972                    s.info.encryptionAware = s.info.directBootAware = true;
7973                }
7974                for (PackageParser.Provider p : pkg.providers) {
7975                    p.info.encryptionAware = p.info.directBootAware = true;
7976                }
7977                for (PackageParser.Activity a : pkg.activities) {
7978                    a.info.encryptionAware = a.info.directBootAware = true;
7979                }
7980                for (PackageParser.Activity r : pkg.receivers) {
7981                    r.info.encryptionAware = r.info.directBootAware = true;
7982                }
7983            }
7984        } else {
7985            // Only allow system apps to be flagged as core apps.
7986            pkg.coreApp = false;
7987            // clear flags not applicable to regular apps
7988            pkg.applicationInfo.privateFlags &=
7989                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7990            pkg.applicationInfo.privateFlags &=
7991                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7992        }
7993        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7994
7995        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7996            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7997        }
7998
7999        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8000            enforceCodePolicy(pkg);
8001        }
8002
8003        if (mCustomResolverComponentName != null &&
8004                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8005            setUpCustomResolverActivity(pkg);
8006        }
8007
8008        if (pkg.packageName.equals("android")) {
8009            synchronized (mPackages) {
8010                if (mAndroidApplication != null) {
8011                    Slog.w(TAG, "*************************************************");
8012                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8013                    Slog.w(TAG, " file=" + scanFile);
8014                    Slog.w(TAG, "*************************************************");
8015                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8016                            "Core android package being redefined.  Skipping.");
8017                }
8018
8019                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8020                    // Set up information for our fall-back user intent resolution activity.
8021                    mPlatformPackage = pkg;
8022                    pkg.mVersionCode = mSdkVersion;
8023                    mAndroidApplication = pkg.applicationInfo;
8024
8025                    if (!mResolverReplaced) {
8026                        mResolveActivity.applicationInfo = mAndroidApplication;
8027                        mResolveActivity.name = ResolverActivity.class.getName();
8028                        mResolveActivity.packageName = mAndroidApplication.packageName;
8029                        mResolveActivity.processName = "system:ui";
8030                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8031                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8032                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8033                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8034                        mResolveActivity.exported = true;
8035                        mResolveActivity.enabled = true;
8036                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8037                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8038                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8039                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8040                                | ActivityInfo.CONFIG_ORIENTATION
8041                                | ActivityInfo.CONFIG_KEYBOARD
8042                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8043                        mResolveInfo.activityInfo = mResolveActivity;
8044                        mResolveInfo.priority = 0;
8045                        mResolveInfo.preferredOrder = 0;
8046                        mResolveInfo.match = 0;
8047                        mResolveComponentName = new ComponentName(
8048                                mAndroidApplication.packageName, mResolveActivity.name);
8049                    }
8050                }
8051            }
8052        }
8053
8054        if (DEBUG_PACKAGE_SCANNING) {
8055            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8056                Log.d(TAG, "Scanning package " + pkg.packageName);
8057        }
8058
8059        synchronized (mPackages) {
8060            if (mPackages.containsKey(pkg.packageName)
8061                    || mSharedLibraries.containsKey(pkg.packageName)) {
8062                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8063                        "Application package " + pkg.packageName
8064                                + " already installed.  Skipping duplicate.");
8065            }
8066
8067            // If we're only installing presumed-existing packages, require that the
8068            // scanned APK is both already known and at the path previously established
8069            // for it.  Previously unknown packages we pick up normally, but if we have an
8070            // a priori expectation about this package's install presence, enforce it.
8071            // With a singular exception for new system packages. When an OTA contains
8072            // a new system package, we allow the codepath to change from a system location
8073            // to the user-installed location. If we don't allow this change, any newer,
8074            // user-installed version of the application will be ignored.
8075            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8076                if (mExpectingBetter.containsKey(pkg.packageName)) {
8077                    logCriticalInfo(Log.WARN,
8078                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8079                } else {
8080                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8081                    if (known != null) {
8082                        if (DEBUG_PACKAGE_SCANNING) {
8083                            Log.d(TAG, "Examining " + pkg.codePath
8084                                    + " and requiring known paths " + known.codePathString
8085                                    + " & " + known.resourcePathString);
8086                        }
8087                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8088                                || !pkg.applicationInfo.getResourcePath().equals(
8089                                known.resourcePathString)) {
8090                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8091                                    "Application package " + pkg.packageName
8092                                            + " found at " + pkg.applicationInfo.getCodePath()
8093                                            + " but expected at " + known.codePathString
8094                                            + "; ignoring.");
8095                        }
8096                    }
8097                }
8098            }
8099        }
8100
8101        // Initialize package source and resource directories
8102        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8103        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8104
8105        SharedUserSetting suid = null;
8106        PackageSetting pkgSetting = null;
8107
8108        if (!isSystemApp(pkg)) {
8109            // Only system apps can use these features.
8110            pkg.mOriginalPackages = null;
8111            pkg.mRealPackage = null;
8112            pkg.mAdoptPermissions = null;
8113        }
8114
8115        // Getting the package setting may have a side-effect, so if we
8116        // are only checking if scan would succeed, stash a copy of the
8117        // old setting to restore at the end.
8118        PackageSetting nonMutatedPs = null;
8119
8120        // writer
8121        synchronized (mPackages) {
8122            if (pkg.mSharedUserId != null) {
8123                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8124                if (suid == null) {
8125                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8126                            "Creating application package " + pkg.packageName
8127                            + " for shared user failed");
8128                }
8129                if (DEBUG_PACKAGE_SCANNING) {
8130                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8131                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8132                                + "): packages=" + suid.packages);
8133                }
8134            }
8135
8136            // Check if we are renaming from an original package name.
8137            PackageSetting origPackage = null;
8138            String realName = null;
8139            if (pkg.mOriginalPackages != null) {
8140                // This package may need to be renamed to a previously
8141                // installed name.  Let's check on that...
8142                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8143                if (pkg.mOriginalPackages.contains(renamed)) {
8144                    // This package had originally been installed as the
8145                    // original name, and we have already taken care of
8146                    // transitioning to the new one.  Just update the new
8147                    // one to continue using the old name.
8148                    realName = pkg.mRealPackage;
8149                    if (!pkg.packageName.equals(renamed)) {
8150                        // Callers into this function may have already taken
8151                        // care of renaming the package; only do it here if
8152                        // it is not already done.
8153                        pkg.setPackageName(renamed);
8154                    }
8155
8156                } else {
8157                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8158                        if ((origPackage = mSettings.peekPackageLPr(
8159                                pkg.mOriginalPackages.get(i))) != null) {
8160                            // We do have the package already installed under its
8161                            // original name...  should we use it?
8162                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8163                                // New package is not compatible with original.
8164                                origPackage = null;
8165                                continue;
8166                            } else if (origPackage.sharedUser != null) {
8167                                // Make sure uid is compatible between packages.
8168                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8169                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8170                                            + " to " + pkg.packageName + ": old uid "
8171                                            + origPackage.sharedUser.name
8172                                            + " differs from " + pkg.mSharedUserId);
8173                                    origPackage = null;
8174                                    continue;
8175                                }
8176                                // TODO: Add case when shared user id is added [b/28144775]
8177                            } else {
8178                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8179                                        + pkg.packageName + " to old name " + origPackage.name);
8180                            }
8181                            break;
8182                        }
8183                    }
8184                }
8185            }
8186
8187            if (mTransferedPackages.contains(pkg.packageName)) {
8188                Slog.w(TAG, "Package " + pkg.packageName
8189                        + " was transferred to another, but its .apk remains");
8190            }
8191
8192            // See comments in nonMutatedPs declaration
8193            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8194                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8195                if (foundPs != null) {
8196                    nonMutatedPs = new PackageSetting(foundPs);
8197                }
8198            }
8199
8200            // Just create the setting, don't add it yet. For already existing packages
8201            // the PkgSetting exists already and doesn't have to be created.
8202            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8203                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8204                    pkg.applicationInfo.primaryCpuAbi,
8205                    pkg.applicationInfo.secondaryCpuAbi,
8206                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8207                    user, false);
8208            if (pkgSetting == null) {
8209                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8210                        "Creating application package " + pkg.packageName + " failed");
8211            }
8212
8213            if (pkgSetting.origPackage != null) {
8214                // If we are first transitioning from an original package,
8215                // fix up the new package's name now.  We need to do this after
8216                // looking up the package under its new name, so getPackageLP
8217                // can take care of fiddling things correctly.
8218                pkg.setPackageName(origPackage.name);
8219
8220                // File a report about this.
8221                String msg = "New package " + pkgSetting.realName
8222                        + " renamed to replace old package " + pkgSetting.name;
8223                reportSettingsProblem(Log.WARN, msg);
8224
8225                // Make a note of it.
8226                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8227                    mTransferedPackages.add(origPackage.name);
8228                }
8229
8230                // No longer need to retain this.
8231                pkgSetting.origPackage = null;
8232            }
8233
8234            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8235                // Make a note of it.
8236                mTransferedPackages.add(pkg.packageName);
8237            }
8238
8239            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8240                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8241            }
8242
8243            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8244                // Check all shared libraries and map to their actual file path.
8245                // We only do this here for apps not on a system dir, because those
8246                // are the only ones that can fail an install due to this.  We
8247                // will take care of the system apps by updating all of their
8248                // library paths after the scan is done.
8249                updateSharedLibrariesLPw(pkg, null);
8250            }
8251
8252            if (mFoundPolicyFile) {
8253                SELinuxMMAC.assignSeinfoValue(pkg);
8254            }
8255
8256            pkg.applicationInfo.uid = pkgSetting.appId;
8257            pkg.mExtras = pkgSetting;
8258            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8259                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8260                    // We just determined the app is signed correctly, so bring
8261                    // over the latest parsed certs.
8262                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8263                } else {
8264                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8265                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8266                                "Package " + pkg.packageName + " upgrade keys do not match the "
8267                                + "previously installed version");
8268                    } else {
8269                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8270                        String msg = "System package " + pkg.packageName
8271                            + " signature changed; retaining data.";
8272                        reportSettingsProblem(Log.WARN, msg);
8273                    }
8274                }
8275            } else {
8276                try {
8277                    verifySignaturesLP(pkgSetting, pkg);
8278                    // We just determined the app is signed correctly, so bring
8279                    // over the latest parsed certs.
8280                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8281                } catch (PackageManagerException e) {
8282                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8283                        throw e;
8284                    }
8285                    // The signature has changed, but this package is in the system
8286                    // image...  let's recover!
8287                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8288                    // However...  if this package is part of a shared user, but it
8289                    // doesn't match the signature of the shared user, let's fail.
8290                    // What this means is that you can't change the signatures
8291                    // associated with an overall shared user, which doesn't seem all
8292                    // that unreasonable.
8293                    if (pkgSetting.sharedUser != null) {
8294                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8295                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8296                            throw new PackageManagerException(
8297                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8298                                            "Signature mismatch for shared user: "
8299                                            + pkgSetting.sharedUser);
8300                        }
8301                    }
8302                    // File a report about this.
8303                    String msg = "System package " + pkg.packageName
8304                        + " signature changed; retaining data.";
8305                    reportSettingsProblem(Log.WARN, msg);
8306                }
8307            }
8308            // Verify that this new package doesn't have any content providers
8309            // that conflict with existing packages.  Only do this if the
8310            // package isn't already installed, since we don't want to break
8311            // things that are installed.
8312            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8313                final int N = pkg.providers.size();
8314                int i;
8315                for (i=0; i<N; i++) {
8316                    PackageParser.Provider p = pkg.providers.get(i);
8317                    if (p.info.authority != null) {
8318                        String names[] = p.info.authority.split(";");
8319                        for (int j = 0; j < names.length; j++) {
8320                            if (mProvidersByAuthority.containsKey(names[j])) {
8321                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8322                                final String otherPackageName =
8323                                        ((other != null && other.getComponentName() != null) ?
8324                                                other.getComponentName().getPackageName() : "?");
8325                                throw new PackageManagerException(
8326                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8327                                                "Can't install because provider name " + names[j]
8328                                                + " (in package " + pkg.applicationInfo.packageName
8329                                                + ") is already used by " + otherPackageName);
8330                            }
8331                        }
8332                    }
8333                }
8334            }
8335
8336            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8337                // This package wants to adopt ownership of permissions from
8338                // another package.
8339                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8340                    final String origName = pkg.mAdoptPermissions.get(i);
8341                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8342                    if (orig != null) {
8343                        if (verifyPackageUpdateLPr(orig, pkg)) {
8344                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8345                                    + pkg.packageName);
8346                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8347                        }
8348                    }
8349                }
8350            }
8351        }
8352
8353        final String pkgName = pkg.packageName;
8354
8355        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8356        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8357        pkg.applicationInfo.processName = fixProcessName(
8358                pkg.applicationInfo.packageName,
8359                pkg.applicationInfo.processName,
8360                pkg.applicationInfo.uid);
8361
8362        if (pkg != mPlatformPackage) {
8363            // Get all of our default paths setup
8364            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8365        }
8366
8367        final String path = scanFile.getPath();
8368        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8369
8370        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8371            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8372
8373            // Some system apps still use directory structure for native libraries
8374            // in which case we might end up not detecting abi solely based on apk
8375            // structure. Try to detect abi based on directory structure.
8376            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8377                    pkg.applicationInfo.primaryCpuAbi == null) {
8378                setBundledAppAbisAndRoots(pkg, pkgSetting);
8379                setNativeLibraryPaths(pkg);
8380            }
8381
8382        } else {
8383            if ((scanFlags & SCAN_MOVE) != 0) {
8384                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8385                // but we already have this packages package info in the PackageSetting. We just
8386                // use that and derive the native library path based on the new codepath.
8387                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8388                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8389            }
8390
8391            // Set native library paths again. For moves, the path will be updated based on the
8392            // ABIs we've determined above. For non-moves, the path will be updated based on the
8393            // ABIs we determined during compilation, but the path will depend on the final
8394            // package path (after the rename away from the stage path).
8395            setNativeLibraryPaths(pkg);
8396        }
8397
8398        // This is a special case for the "system" package, where the ABI is
8399        // dictated by the zygote configuration (and init.rc). We should keep track
8400        // of this ABI so that we can deal with "normal" applications that run under
8401        // the same UID correctly.
8402        if (mPlatformPackage == pkg) {
8403            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8404                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8405        }
8406
8407        // If there's a mismatch between the abi-override in the package setting
8408        // and the abiOverride specified for the install. Warn about this because we
8409        // would've already compiled the app without taking the package setting into
8410        // account.
8411        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8412            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8413                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8414                        " for package " + pkg.packageName);
8415            }
8416        }
8417
8418        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8419        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8420        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8421
8422        // Copy the derived override back to the parsed package, so that we can
8423        // update the package settings accordingly.
8424        pkg.cpuAbiOverride = cpuAbiOverride;
8425
8426        if (DEBUG_ABI_SELECTION) {
8427            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8428                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8429                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8430        }
8431
8432        // Push the derived path down into PackageSettings so we know what to
8433        // clean up at uninstall time.
8434        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8435
8436        if (DEBUG_ABI_SELECTION) {
8437            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8438                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8439                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8440        }
8441
8442        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8443            // We don't do this here during boot because we can do it all
8444            // at once after scanning all existing packages.
8445            //
8446            // We also do this *before* we perform dexopt on this package, so that
8447            // we can avoid redundant dexopts, and also to make sure we've got the
8448            // code and package path correct.
8449            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8450                    pkg, true /* boot complete */);
8451        }
8452
8453        if (mFactoryTest && pkg.requestedPermissions.contains(
8454                android.Manifest.permission.FACTORY_TEST)) {
8455            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8456        }
8457
8458        if (isSystemApp(pkg)) {
8459            pkgSetting.isOrphaned = true;
8460        }
8461
8462        ArrayList<PackageParser.Package> clientLibPkgs = null;
8463
8464        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8465            if (nonMutatedPs != null) {
8466                synchronized (mPackages) {
8467                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8468                }
8469            }
8470            return pkg;
8471        }
8472
8473        // Only privileged apps and updated privileged apps can add child packages.
8474        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8475            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8476                throw new PackageManagerException("Only privileged apps and updated "
8477                        + "privileged apps can add child packages. Ignoring package "
8478                        + pkg.packageName);
8479            }
8480            final int childCount = pkg.childPackages.size();
8481            for (int i = 0; i < childCount; i++) {
8482                PackageParser.Package childPkg = pkg.childPackages.get(i);
8483                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8484                        childPkg.packageName)) {
8485                    throw new PackageManagerException("Cannot override a child package of "
8486                            + "another disabled system app. Ignoring package " + pkg.packageName);
8487                }
8488            }
8489        }
8490
8491        // writer
8492        synchronized (mPackages) {
8493            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8494                // Only system apps can add new shared libraries.
8495                if (pkg.libraryNames != null) {
8496                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8497                        String name = pkg.libraryNames.get(i);
8498                        boolean allowed = false;
8499                        if (pkg.isUpdatedSystemApp()) {
8500                            // New library entries can only be added through the
8501                            // system image.  This is important to get rid of a lot
8502                            // of nasty edge cases: for example if we allowed a non-
8503                            // system update of the app to add a library, then uninstalling
8504                            // the update would make the library go away, and assumptions
8505                            // we made such as through app install filtering would now
8506                            // have allowed apps on the device which aren't compatible
8507                            // with it.  Better to just have the restriction here, be
8508                            // conservative, and create many fewer cases that can negatively
8509                            // impact the user experience.
8510                            final PackageSetting sysPs = mSettings
8511                                    .getDisabledSystemPkgLPr(pkg.packageName);
8512                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8513                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8514                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8515                                        allowed = true;
8516                                        break;
8517                                    }
8518                                }
8519                            }
8520                        } else {
8521                            allowed = true;
8522                        }
8523                        if (allowed) {
8524                            if (!mSharedLibraries.containsKey(name)) {
8525                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8526                            } else if (!name.equals(pkg.packageName)) {
8527                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8528                                        + name + " already exists; skipping");
8529                            }
8530                        } else {
8531                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8532                                    + name + " that is not declared on system image; skipping");
8533                        }
8534                    }
8535                    if ((scanFlags & SCAN_BOOTING) == 0) {
8536                        // If we are not booting, we need to update any applications
8537                        // that are clients of our shared library.  If we are booting,
8538                        // this will all be done once the scan is complete.
8539                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8540                    }
8541                }
8542            }
8543        }
8544
8545        if ((scanFlags & SCAN_BOOTING) != 0) {
8546            // No apps can run during boot scan, so they don't need to be frozen
8547        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8548            // Caller asked to not kill app, so it's probably not frozen
8549        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8550            // Caller asked us to ignore frozen check for some reason; they
8551            // probably didn't know the package name
8552        } else {
8553            // We're doing major surgery on this package, so it better be frozen
8554            // right now to keep it from launching
8555            checkPackageFrozen(pkgName);
8556        }
8557
8558        // Also need to kill any apps that are dependent on the library.
8559        if (clientLibPkgs != null) {
8560            for (int i=0; i<clientLibPkgs.size(); i++) {
8561                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8562                killApplication(clientPkg.applicationInfo.packageName,
8563                        clientPkg.applicationInfo.uid, "update lib");
8564            }
8565        }
8566
8567        // Make sure we're not adding any bogus keyset info
8568        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8569        ksms.assertScannedPackageValid(pkg);
8570
8571        // writer
8572        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8573
8574        boolean createIdmapFailed = false;
8575        synchronized (mPackages) {
8576            // We don't expect installation to fail beyond this point
8577
8578            if (pkgSetting.pkg != null) {
8579                // Note that |user| might be null during the initial boot scan. If a codePath
8580                // for an app has changed during a boot scan, it's due to an app update that's
8581                // part of the system partition and marker changes must be applied to all users.
8582                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8583                    (user != null) ? user : UserHandle.ALL);
8584            }
8585
8586            // Add the new setting to mSettings
8587            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8588            // Add the new setting to mPackages
8589            mPackages.put(pkg.applicationInfo.packageName, pkg);
8590            // Make sure we don't accidentally delete its data.
8591            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8592            while (iter.hasNext()) {
8593                PackageCleanItem item = iter.next();
8594                if (pkgName.equals(item.packageName)) {
8595                    iter.remove();
8596                }
8597            }
8598
8599            // Take care of first install / last update times.
8600            if (currentTime != 0) {
8601                if (pkgSetting.firstInstallTime == 0) {
8602                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8603                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8604                    pkgSetting.lastUpdateTime = currentTime;
8605                }
8606            } else if (pkgSetting.firstInstallTime == 0) {
8607                // We need *something*.  Take time time stamp of the file.
8608                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8609            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8610                if (scanFileTime != pkgSetting.timeStamp) {
8611                    // A package on the system image has changed; consider this
8612                    // to be an update.
8613                    pkgSetting.lastUpdateTime = scanFileTime;
8614                }
8615            }
8616
8617            // Add the package's KeySets to the global KeySetManagerService
8618            ksms.addScannedPackageLPw(pkg);
8619
8620            int N = pkg.providers.size();
8621            StringBuilder r = null;
8622            int i;
8623            for (i=0; i<N; i++) {
8624                PackageParser.Provider p = pkg.providers.get(i);
8625                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8626                        p.info.processName, pkg.applicationInfo.uid);
8627                mProviders.addProvider(p);
8628                p.syncable = p.info.isSyncable;
8629                if (p.info.authority != null) {
8630                    String names[] = p.info.authority.split(";");
8631                    p.info.authority = null;
8632                    for (int j = 0; j < names.length; j++) {
8633                        if (j == 1 && p.syncable) {
8634                            // We only want the first authority for a provider to possibly be
8635                            // syncable, so if we already added this provider using a different
8636                            // authority clear the syncable flag. We copy the provider before
8637                            // changing it because the mProviders object contains a reference
8638                            // to a provider that we don't want to change.
8639                            // Only do this for the second authority since the resulting provider
8640                            // object can be the same for all future authorities for this provider.
8641                            p = new PackageParser.Provider(p);
8642                            p.syncable = false;
8643                        }
8644                        if (!mProvidersByAuthority.containsKey(names[j])) {
8645                            mProvidersByAuthority.put(names[j], p);
8646                            if (p.info.authority == null) {
8647                                p.info.authority = names[j];
8648                            } else {
8649                                p.info.authority = p.info.authority + ";" + names[j];
8650                            }
8651                            if (DEBUG_PACKAGE_SCANNING) {
8652                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8653                                    Log.d(TAG, "Registered content provider: " + names[j]
8654                                            + ", className = " + p.info.name + ", isSyncable = "
8655                                            + p.info.isSyncable);
8656                            }
8657                        } else {
8658                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8659                            Slog.w(TAG, "Skipping provider name " + names[j] +
8660                                    " (in package " + pkg.applicationInfo.packageName +
8661                                    "): name already used by "
8662                                    + ((other != null && other.getComponentName() != null)
8663                                            ? other.getComponentName().getPackageName() : "?"));
8664                        }
8665                    }
8666                }
8667                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8668                    if (r == null) {
8669                        r = new StringBuilder(256);
8670                    } else {
8671                        r.append(' ');
8672                    }
8673                    r.append(p.info.name);
8674                }
8675            }
8676            if (r != null) {
8677                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8678            }
8679
8680            N = pkg.services.size();
8681            r = null;
8682            for (i=0; i<N; i++) {
8683                PackageParser.Service s = pkg.services.get(i);
8684                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8685                        s.info.processName, pkg.applicationInfo.uid);
8686                mServices.addService(s);
8687                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8688                    if (r == null) {
8689                        r = new StringBuilder(256);
8690                    } else {
8691                        r.append(' ');
8692                    }
8693                    r.append(s.info.name);
8694                }
8695            }
8696            if (r != null) {
8697                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8698            }
8699
8700            N = pkg.receivers.size();
8701            r = null;
8702            for (i=0; i<N; i++) {
8703                PackageParser.Activity a = pkg.receivers.get(i);
8704                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8705                        a.info.processName, pkg.applicationInfo.uid);
8706                mReceivers.addActivity(a, "receiver");
8707                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8708                    if (r == null) {
8709                        r = new StringBuilder(256);
8710                    } else {
8711                        r.append(' ');
8712                    }
8713                    r.append(a.info.name);
8714                }
8715            }
8716            if (r != null) {
8717                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8718            }
8719
8720            N = pkg.activities.size();
8721            r = null;
8722            for (i=0; i<N; i++) {
8723                PackageParser.Activity a = pkg.activities.get(i);
8724                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8725                        a.info.processName, pkg.applicationInfo.uid);
8726                mActivities.addActivity(a, "activity");
8727                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8728                    if (r == null) {
8729                        r = new StringBuilder(256);
8730                    } else {
8731                        r.append(' ');
8732                    }
8733                    r.append(a.info.name);
8734                }
8735            }
8736            if (r != null) {
8737                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8738            }
8739
8740            N = pkg.permissionGroups.size();
8741            r = null;
8742            for (i=0; i<N; i++) {
8743                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8744                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8745                final String curPackageName = cur == null ? null : cur.info.packageName;
8746                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8747                if (cur == null || isPackageUpdate) {
8748                    mPermissionGroups.put(pg.info.name, pg);
8749                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8750                        if (r == null) {
8751                            r = new StringBuilder(256);
8752                        } else {
8753                            r.append(' ');
8754                        }
8755                        if (isPackageUpdate) {
8756                            r.append("UPD:");
8757                        }
8758                        r.append(pg.info.name);
8759                    }
8760                } else {
8761                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8762                            + pg.info.packageName + " ignored: original from "
8763                            + cur.info.packageName);
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("DUP:");
8771                        r.append(pg.info.name);
8772                    }
8773                }
8774            }
8775            if (r != null) {
8776                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8777            }
8778
8779            N = pkg.permissions.size();
8780            r = null;
8781            for (i=0; i<N; i++) {
8782                PackageParser.Permission p = pkg.permissions.get(i);
8783
8784                // Assume by default that we did not install this permission into the system.
8785                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8786
8787                // Now that permission groups have a special meaning, we ignore permission
8788                // groups for legacy apps to prevent unexpected behavior. In particular,
8789                // permissions for one app being granted to someone just becase they happen
8790                // to be in a group defined by another app (before this had no implications).
8791                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8792                    p.group = mPermissionGroups.get(p.info.group);
8793                    // Warn for a permission in an unknown group.
8794                    if (p.info.group != null && p.group == null) {
8795                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8796                                + p.info.packageName + " in an unknown group " + p.info.group);
8797                    }
8798                }
8799
8800                ArrayMap<String, BasePermission> permissionMap =
8801                        p.tree ? mSettings.mPermissionTrees
8802                                : mSettings.mPermissions;
8803                BasePermission bp = permissionMap.get(p.info.name);
8804
8805                // Allow system apps to redefine non-system permissions
8806                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8807                    final boolean currentOwnerIsSystem = (bp.perm != null
8808                            && isSystemApp(bp.perm.owner));
8809                    if (isSystemApp(p.owner)) {
8810                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8811                            // It's a built-in permission and no owner, take ownership now
8812                            bp.packageSetting = pkgSetting;
8813                            bp.perm = p;
8814                            bp.uid = pkg.applicationInfo.uid;
8815                            bp.sourcePackage = p.info.packageName;
8816                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8817                        } else if (!currentOwnerIsSystem) {
8818                            String msg = "New decl " + p.owner + " of permission  "
8819                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8820                            reportSettingsProblem(Log.WARN, msg);
8821                            bp = null;
8822                        }
8823                    }
8824                }
8825
8826                if (bp == null) {
8827                    bp = new BasePermission(p.info.name, p.info.packageName,
8828                            BasePermission.TYPE_NORMAL);
8829                    permissionMap.put(p.info.name, bp);
8830                }
8831
8832                if (bp.perm == null) {
8833                    if (bp.sourcePackage == null
8834                            || bp.sourcePackage.equals(p.info.packageName)) {
8835                        BasePermission tree = findPermissionTreeLP(p.info.name);
8836                        if (tree == null
8837                                || tree.sourcePackage.equals(p.info.packageName)) {
8838                            bp.packageSetting = pkgSetting;
8839                            bp.perm = p;
8840                            bp.uid = pkg.applicationInfo.uid;
8841                            bp.sourcePackage = p.info.packageName;
8842                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8843                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8844                                if (r == null) {
8845                                    r = new StringBuilder(256);
8846                                } else {
8847                                    r.append(' ');
8848                                }
8849                                r.append(p.info.name);
8850                            }
8851                        } else {
8852                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8853                                    + p.info.packageName + " ignored: base tree "
8854                                    + tree.name + " is from package "
8855                                    + tree.sourcePackage);
8856                        }
8857                    } else {
8858                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8859                                + p.info.packageName + " ignored: original from "
8860                                + bp.sourcePackage);
8861                    }
8862                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8863                    if (r == null) {
8864                        r = new StringBuilder(256);
8865                    } else {
8866                        r.append(' ');
8867                    }
8868                    r.append("DUP:");
8869                    r.append(p.info.name);
8870                }
8871                if (bp.perm == p) {
8872                    bp.protectionLevel = p.info.protectionLevel;
8873                }
8874            }
8875
8876            if (r != null) {
8877                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8878            }
8879
8880            N = pkg.instrumentation.size();
8881            r = null;
8882            for (i=0; i<N; i++) {
8883                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8884                a.info.packageName = pkg.applicationInfo.packageName;
8885                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8886                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8887                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8888                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8889                a.info.dataDir = pkg.applicationInfo.dataDir;
8890                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8891                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8892
8893                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8894                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8895                mInstrumentation.put(a.getComponentName(), a);
8896                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8897                    if (r == null) {
8898                        r = new StringBuilder(256);
8899                    } else {
8900                        r.append(' ');
8901                    }
8902                    r.append(a.info.name);
8903                }
8904            }
8905            if (r != null) {
8906                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8907            }
8908
8909            if (pkg.protectedBroadcasts != null) {
8910                N = pkg.protectedBroadcasts.size();
8911                for (i=0; i<N; i++) {
8912                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8913                }
8914            }
8915
8916            pkgSetting.setTimeStamp(scanFileTime);
8917
8918            // Create idmap files for pairs of (packages, overlay packages).
8919            // Note: "android", ie framework-res.apk, is handled by native layers.
8920            if (pkg.mOverlayTarget != null) {
8921                // This is an overlay package.
8922                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8923                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8924                        mOverlays.put(pkg.mOverlayTarget,
8925                                new ArrayMap<String, PackageParser.Package>());
8926                    }
8927                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8928                    map.put(pkg.packageName, pkg);
8929                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8930                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8931                        createIdmapFailed = true;
8932                    }
8933                }
8934            } else if (mOverlays.containsKey(pkg.packageName) &&
8935                    !pkg.packageName.equals("android")) {
8936                // This is a regular package, with one or more known overlay packages.
8937                createIdmapsForPackageLI(pkg);
8938            }
8939        }
8940
8941        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8942
8943        if (createIdmapFailed) {
8944            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8945                    "scanPackageLI failed to createIdmap");
8946        }
8947        return pkg;
8948    }
8949
8950    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8951            PackageParser.Package update, UserHandle user) {
8952        if (existing.applicationInfo == null || update.applicationInfo == null) {
8953            // This isn't due to an app installation.
8954            return;
8955        }
8956
8957        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8958        final File newCodePath = new File(update.applicationInfo.getCodePath());
8959
8960        // The codePath hasn't changed, so there's nothing for us to do.
8961        if (Objects.equals(oldCodePath, newCodePath)) {
8962            return;
8963        }
8964
8965        File canonicalNewCodePath;
8966        try {
8967            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
8968        } catch (IOException e) {
8969            Slog.w(TAG, "Failed to get canonical path.", e);
8970            return;
8971        }
8972
8973        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
8974        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
8975        // that the last component of the path (i.e, the name) doesn't need canonicalization
8976        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
8977        // but may change in the future. Hopefully this function won't exist at that point.
8978        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
8979                oldCodePath.getName());
8980
8981        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
8982        // with "@".
8983        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
8984        if (!oldMarkerPrefix.endsWith("@")) {
8985            oldMarkerPrefix += "@";
8986        }
8987        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
8988        if (!newMarkerPrefix.endsWith("@")) {
8989            newMarkerPrefix += "@";
8990        }
8991
8992        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
8993        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
8994        for (String updatedPath : updatedPaths) {
8995            String updatedPathName = new File(updatedPath).getName();
8996            markerSuffixes.add(updatedPathName.replace('/', '@'));
8997        }
8998
8999        for (int userId : resolveUserIds(user.getIdentifier())) {
9000            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9001
9002            for (String markerSuffix : markerSuffixes) {
9003                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9004                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9005                if (oldForeignUseMark.exists()) {
9006                    try {
9007                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9008                                newForeignUseMark.getAbsolutePath());
9009                    } catch (ErrnoException e) {
9010                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9011                        oldForeignUseMark.delete();
9012                    }
9013                }
9014            }
9015        }
9016    }
9017
9018    /**
9019     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9020     * is derived purely on the basis of the contents of {@code scanFile} and
9021     * {@code cpuAbiOverride}.
9022     *
9023     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9024     */
9025    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9026                                 String cpuAbiOverride, boolean extractLibs)
9027            throws PackageManagerException {
9028        // TODO: We can probably be smarter about this stuff. For installed apps,
9029        // we can calculate this information at install time once and for all. For
9030        // system apps, we can probably assume that this information doesn't change
9031        // after the first boot scan. As things stand, we do lots of unnecessary work.
9032
9033        // Give ourselves some initial paths; we'll come back for another
9034        // pass once we've determined ABI below.
9035        setNativeLibraryPaths(pkg);
9036
9037        // We would never need to extract libs for forward-locked and external packages,
9038        // since the container service will do it for us. We shouldn't attempt to
9039        // extract libs from system app when it was not updated.
9040        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9041                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9042            extractLibs = false;
9043        }
9044
9045        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9046        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9047
9048        NativeLibraryHelper.Handle handle = null;
9049        try {
9050            handle = NativeLibraryHelper.Handle.create(pkg);
9051            // TODO(multiArch): This can be null for apps that didn't go through the
9052            // usual installation process. We can calculate it again, like we
9053            // do during install time.
9054            //
9055            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9056            // unnecessary.
9057            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9058
9059            // Null out the abis so that they can be recalculated.
9060            pkg.applicationInfo.primaryCpuAbi = null;
9061            pkg.applicationInfo.secondaryCpuAbi = null;
9062            if (isMultiArch(pkg.applicationInfo)) {
9063                // Warn if we've set an abiOverride for multi-lib packages..
9064                // By definition, we need to copy both 32 and 64 bit libraries for
9065                // such packages.
9066                if (pkg.cpuAbiOverride != null
9067                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9068                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9069                }
9070
9071                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9072                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9073                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9074                    if (extractLibs) {
9075                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9076                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9077                                useIsaSpecificSubdirs);
9078                    } else {
9079                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9080                    }
9081                }
9082
9083                maybeThrowExceptionForMultiArchCopy(
9084                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9085
9086                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9087                    if (extractLibs) {
9088                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9089                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9090                                useIsaSpecificSubdirs);
9091                    } else {
9092                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9093                    }
9094                }
9095
9096                maybeThrowExceptionForMultiArchCopy(
9097                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9098
9099                if (abi64 >= 0) {
9100                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9101                }
9102
9103                if (abi32 >= 0) {
9104                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9105                    if (abi64 >= 0) {
9106                        if (pkg.use32bitAbi) {
9107                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9108                            pkg.applicationInfo.primaryCpuAbi = abi;
9109                        } else {
9110                            pkg.applicationInfo.secondaryCpuAbi = abi;
9111                        }
9112                    } else {
9113                        pkg.applicationInfo.primaryCpuAbi = abi;
9114                    }
9115                }
9116
9117            } else {
9118                String[] abiList = (cpuAbiOverride != null) ?
9119                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9120
9121                // Enable gross and lame hacks for apps that are built with old
9122                // SDK tools. We must scan their APKs for renderscript bitcode and
9123                // not launch them if it's present. Don't bother checking on devices
9124                // that don't have 64 bit support.
9125                boolean needsRenderScriptOverride = false;
9126                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9127                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9128                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9129                    needsRenderScriptOverride = true;
9130                }
9131
9132                final int copyRet;
9133                if (extractLibs) {
9134                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9135                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9136                } else {
9137                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9138                }
9139
9140                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9141                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9142                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9143                }
9144
9145                if (copyRet >= 0) {
9146                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9147                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9148                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9149                } else if (needsRenderScriptOverride) {
9150                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9151                }
9152            }
9153        } catch (IOException ioe) {
9154            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9155        } finally {
9156            IoUtils.closeQuietly(handle);
9157        }
9158
9159        // Now that we've calculated the ABIs and determined if it's an internal app,
9160        // we will go ahead and populate the nativeLibraryPath.
9161        setNativeLibraryPaths(pkg);
9162    }
9163
9164    /**
9165     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9166     * i.e, so that all packages can be run inside a single process if required.
9167     *
9168     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9169     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9170     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9171     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9172     * updating a package that belongs to a shared user.
9173     *
9174     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9175     * adds unnecessary complexity.
9176     */
9177    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9178            PackageParser.Package scannedPackage, boolean bootComplete) {
9179        String requiredInstructionSet = null;
9180        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9181            requiredInstructionSet = VMRuntime.getInstructionSet(
9182                     scannedPackage.applicationInfo.primaryCpuAbi);
9183        }
9184
9185        PackageSetting requirer = null;
9186        for (PackageSetting ps : packagesForUser) {
9187            // If packagesForUser contains scannedPackage, we skip it. This will happen
9188            // when scannedPackage is an update of an existing package. Without this check,
9189            // we will never be able to change the ABI of any package belonging to a shared
9190            // user, even if it's compatible with other packages.
9191            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9192                if (ps.primaryCpuAbiString == null) {
9193                    continue;
9194                }
9195
9196                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9197                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9198                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9199                    // this but there's not much we can do.
9200                    String errorMessage = "Instruction set mismatch, "
9201                            + ((requirer == null) ? "[caller]" : requirer)
9202                            + " requires " + requiredInstructionSet + " whereas " + ps
9203                            + " requires " + instructionSet;
9204                    Slog.w(TAG, errorMessage);
9205                }
9206
9207                if (requiredInstructionSet == null) {
9208                    requiredInstructionSet = instructionSet;
9209                    requirer = ps;
9210                }
9211            }
9212        }
9213
9214        if (requiredInstructionSet != null) {
9215            String adjustedAbi;
9216            if (requirer != null) {
9217                // requirer != null implies that either scannedPackage was null or that scannedPackage
9218                // did not require an ABI, in which case we have to adjust scannedPackage to match
9219                // the ABI of the set (which is the same as requirer's ABI)
9220                adjustedAbi = requirer.primaryCpuAbiString;
9221                if (scannedPackage != null) {
9222                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9223                }
9224            } else {
9225                // requirer == null implies that we're updating all ABIs in the set to
9226                // match scannedPackage.
9227                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9228            }
9229
9230            for (PackageSetting ps : packagesForUser) {
9231                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9232                    if (ps.primaryCpuAbiString != null) {
9233                        continue;
9234                    }
9235
9236                    ps.primaryCpuAbiString = adjustedAbi;
9237                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9238                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9239                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9240                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9241                                + " (requirer="
9242                                + (requirer == null ? "null" : requirer.pkg.packageName)
9243                                + ", scannedPackage="
9244                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9245                                + ")");
9246                        try {
9247                            mInstaller.rmdex(ps.codePathString,
9248                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9249                        } catch (InstallerException ignored) {
9250                        }
9251                    }
9252                }
9253            }
9254        }
9255    }
9256
9257    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9258        synchronized (mPackages) {
9259            mResolverReplaced = true;
9260            // Set up information for custom user intent resolution activity.
9261            mResolveActivity.applicationInfo = pkg.applicationInfo;
9262            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9263            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9264            mResolveActivity.processName = pkg.applicationInfo.packageName;
9265            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9266            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9267                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9268            mResolveActivity.theme = 0;
9269            mResolveActivity.exported = true;
9270            mResolveActivity.enabled = true;
9271            mResolveInfo.activityInfo = mResolveActivity;
9272            mResolveInfo.priority = 0;
9273            mResolveInfo.preferredOrder = 0;
9274            mResolveInfo.match = 0;
9275            mResolveComponentName = mCustomResolverComponentName;
9276            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9277                    mResolveComponentName);
9278        }
9279    }
9280
9281    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9282        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9283
9284        // Set up information for ephemeral installer activity
9285        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9286        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9287        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9288        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9289        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9290        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9291                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9292        mEphemeralInstallerActivity.theme = 0;
9293        mEphemeralInstallerActivity.exported = true;
9294        mEphemeralInstallerActivity.enabled = true;
9295        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9296        mEphemeralInstallerInfo.priority = 0;
9297        mEphemeralInstallerInfo.preferredOrder = 1;
9298        mEphemeralInstallerInfo.isDefault = true;
9299        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9300                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9301
9302        if (DEBUG_EPHEMERAL) {
9303            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9304        }
9305    }
9306
9307    private static String calculateBundledApkRoot(final String codePathString) {
9308        final File codePath = new File(codePathString);
9309        final File codeRoot;
9310        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9311            codeRoot = Environment.getRootDirectory();
9312        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9313            codeRoot = Environment.getOemDirectory();
9314        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9315            codeRoot = Environment.getVendorDirectory();
9316        } else {
9317            // Unrecognized code path; take its top real segment as the apk root:
9318            // e.g. /something/app/blah.apk => /something
9319            try {
9320                File f = codePath.getCanonicalFile();
9321                File parent = f.getParentFile();    // non-null because codePath is a file
9322                File tmp;
9323                while ((tmp = parent.getParentFile()) != null) {
9324                    f = parent;
9325                    parent = tmp;
9326                }
9327                codeRoot = f;
9328                Slog.w(TAG, "Unrecognized code path "
9329                        + codePath + " - using " + codeRoot);
9330            } catch (IOException e) {
9331                // Can't canonicalize the code path -- shenanigans?
9332                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9333                return Environment.getRootDirectory().getPath();
9334            }
9335        }
9336        return codeRoot.getPath();
9337    }
9338
9339    /**
9340     * Derive and set the location of native libraries for the given package,
9341     * which varies depending on where and how the package was installed.
9342     */
9343    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9344        final ApplicationInfo info = pkg.applicationInfo;
9345        final String codePath = pkg.codePath;
9346        final File codeFile = new File(codePath);
9347        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9348        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9349
9350        info.nativeLibraryRootDir = null;
9351        info.nativeLibraryRootRequiresIsa = false;
9352        info.nativeLibraryDir = null;
9353        info.secondaryNativeLibraryDir = null;
9354
9355        if (isApkFile(codeFile)) {
9356            // Monolithic install
9357            if (bundledApp) {
9358                // If "/system/lib64/apkname" exists, assume that is the per-package
9359                // native library directory to use; otherwise use "/system/lib/apkname".
9360                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9361                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9362                        getPrimaryInstructionSet(info));
9363
9364                // This is a bundled system app so choose the path based on the ABI.
9365                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9366                // is just the default path.
9367                final String apkName = deriveCodePathName(codePath);
9368                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9369                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9370                        apkName).getAbsolutePath();
9371
9372                if (info.secondaryCpuAbi != null) {
9373                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9374                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9375                            secondaryLibDir, apkName).getAbsolutePath();
9376                }
9377            } else if (asecApp) {
9378                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9379                        .getAbsolutePath();
9380            } else {
9381                final String apkName = deriveCodePathName(codePath);
9382                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9383                        .getAbsolutePath();
9384            }
9385
9386            info.nativeLibraryRootRequiresIsa = false;
9387            info.nativeLibraryDir = info.nativeLibraryRootDir;
9388        } else {
9389            // Cluster install
9390            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9391            info.nativeLibraryRootRequiresIsa = true;
9392
9393            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9394                    getPrimaryInstructionSet(info)).getAbsolutePath();
9395
9396            if (info.secondaryCpuAbi != null) {
9397                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9398                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9399            }
9400        }
9401    }
9402
9403    /**
9404     * Calculate the abis and roots for a bundled app. These can uniquely
9405     * be determined from the contents of the system partition, i.e whether
9406     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9407     * of this information, and instead assume that the system was built
9408     * sensibly.
9409     */
9410    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9411                                           PackageSetting pkgSetting) {
9412        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9413
9414        // If "/system/lib64/apkname" exists, assume that is the per-package
9415        // native library directory to use; otherwise use "/system/lib/apkname".
9416        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9417        setBundledAppAbi(pkg, apkRoot, apkName);
9418        // pkgSetting might be null during rescan following uninstall of updates
9419        // to a bundled app, so accommodate that possibility.  The settings in
9420        // that case will be established later from the parsed package.
9421        //
9422        // If the settings aren't null, sync them up with what we've just derived.
9423        // note that apkRoot isn't stored in the package settings.
9424        if (pkgSetting != null) {
9425            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9426            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9427        }
9428    }
9429
9430    /**
9431     * Deduces the ABI of a bundled app and sets the relevant fields on the
9432     * parsed pkg object.
9433     *
9434     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9435     *        under which system libraries are installed.
9436     * @param apkName the name of the installed package.
9437     */
9438    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9439        final File codeFile = new File(pkg.codePath);
9440
9441        final boolean has64BitLibs;
9442        final boolean has32BitLibs;
9443        if (isApkFile(codeFile)) {
9444            // Monolithic install
9445            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9446            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9447        } else {
9448            // Cluster install
9449            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9450            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9451                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9452                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9453                has64BitLibs = (new File(rootDir, isa)).exists();
9454            } else {
9455                has64BitLibs = false;
9456            }
9457            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9458                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9459                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9460                has32BitLibs = (new File(rootDir, isa)).exists();
9461            } else {
9462                has32BitLibs = false;
9463            }
9464        }
9465
9466        if (has64BitLibs && !has32BitLibs) {
9467            // The package has 64 bit libs, but not 32 bit libs. Its primary
9468            // ABI should be 64 bit. We can safely assume here that the bundled
9469            // native libraries correspond to the most preferred ABI in the list.
9470
9471            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9472            pkg.applicationInfo.secondaryCpuAbi = null;
9473        } else if (has32BitLibs && !has64BitLibs) {
9474            // The package has 32 bit libs but not 64 bit libs. Its primary
9475            // ABI should be 32 bit.
9476
9477            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9478            pkg.applicationInfo.secondaryCpuAbi = null;
9479        } else if (has32BitLibs && has64BitLibs) {
9480            // The application has both 64 and 32 bit bundled libraries. We check
9481            // here that the app declares multiArch support, and warn if it doesn't.
9482            //
9483            // We will be lenient here and record both ABIs. The primary will be the
9484            // ABI that's higher on the list, i.e, a device that's configured to prefer
9485            // 64 bit apps will see a 64 bit primary ABI,
9486
9487            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9488                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9489            }
9490
9491            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9492                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9493                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9494            } else {
9495                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9496                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9497            }
9498        } else {
9499            pkg.applicationInfo.primaryCpuAbi = null;
9500            pkg.applicationInfo.secondaryCpuAbi = null;
9501        }
9502    }
9503
9504    private void killApplication(String pkgName, int appId, String reason) {
9505        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9506    }
9507
9508    private void killApplication(String pkgName, int appId, int userId, String reason) {
9509        // Request the ActivityManager to kill the process(only for existing packages)
9510        // so that we do not end up in a confused state while the user is still using the older
9511        // version of the application while the new one gets installed.
9512        final long token = Binder.clearCallingIdentity();
9513        try {
9514            IActivityManager am = ActivityManagerNative.getDefault();
9515            if (am != null) {
9516                try {
9517                    am.killApplication(pkgName, appId, userId, reason);
9518                } catch (RemoteException e) {
9519                }
9520            }
9521        } finally {
9522            Binder.restoreCallingIdentity(token);
9523        }
9524    }
9525
9526    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9527        // Remove the parent package setting
9528        PackageSetting ps = (PackageSetting) pkg.mExtras;
9529        if (ps != null) {
9530            removePackageLI(ps, chatty);
9531        }
9532        // Remove the child package setting
9533        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9534        for (int i = 0; i < childCount; i++) {
9535            PackageParser.Package childPkg = pkg.childPackages.get(i);
9536            ps = (PackageSetting) childPkg.mExtras;
9537            if (ps != null) {
9538                removePackageLI(ps, chatty);
9539            }
9540        }
9541    }
9542
9543    void removePackageLI(PackageSetting ps, boolean chatty) {
9544        if (DEBUG_INSTALL) {
9545            if (chatty)
9546                Log.d(TAG, "Removing package " + ps.name);
9547        }
9548
9549        // writer
9550        synchronized (mPackages) {
9551            mPackages.remove(ps.name);
9552            final PackageParser.Package pkg = ps.pkg;
9553            if (pkg != null) {
9554                cleanPackageDataStructuresLILPw(pkg, chatty);
9555            }
9556        }
9557    }
9558
9559    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9560        if (DEBUG_INSTALL) {
9561            if (chatty)
9562                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9563        }
9564
9565        // writer
9566        synchronized (mPackages) {
9567            // Remove the parent package
9568            mPackages.remove(pkg.applicationInfo.packageName);
9569            cleanPackageDataStructuresLILPw(pkg, chatty);
9570
9571            // Remove the child packages
9572            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9573            for (int i = 0; i < childCount; i++) {
9574                PackageParser.Package childPkg = pkg.childPackages.get(i);
9575                mPackages.remove(childPkg.applicationInfo.packageName);
9576                cleanPackageDataStructuresLILPw(childPkg, chatty);
9577            }
9578        }
9579    }
9580
9581    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9582        int N = pkg.providers.size();
9583        StringBuilder r = null;
9584        int i;
9585        for (i=0; i<N; i++) {
9586            PackageParser.Provider p = pkg.providers.get(i);
9587            mProviders.removeProvider(p);
9588            if (p.info.authority == null) {
9589
9590                /* There was another ContentProvider with this authority when
9591                 * this app was installed so this authority is null,
9592                 * Ignore it as we don't have to unregister the provider.
9593                 */
9594                continue;
9595            }
9596            String names[] = p.info.authority.split(";");
9597            for (int j = 0; j < names.length; j++) {
9598                if (mProvidersByAuthority.get(names[j]) == p) {
9599                    mProvidersByAuthority.remove(names[j]);
9600                    if (DEBUG_REMOVE) {
9601                        if (chatty)
9602                            Log.d(TAG, "Unregistered content provider: " + names[j]
9603                                    + ", className = " + p.info.name + ", isSyncable = "
9604                                    + p.info.isSyncable);
9605                    }
9606                }
9607            }
9608            if (DEBUG_REMOVE && chatty) {
9609                if (r == null) {
9610                    r = new StringBuilder(256);
9611                } else {
9612                    r.append(' ');
9613                }
9614                r.append(p.info.name);
9615            }
9616        }
9617        if (r != null) {
9618            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9619        }
9620
9621        N = pkg.services.size();
9622        r = null;
9623        for (i=0; i<N; i++) {
9624            PackageParser.Service s = pkg.services.get(i);
9625            mServices.removeService(s);
9626            if (chatty) {
9627                if (r == null) {
9628                    r = new StringBuilder(256);
9629                } else {
9630                    r.append(' ');
9631                }
9632                r.append(s.info.name);
9633            }
9634        }
9635        if (r != null) {
9636            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9637        }
9638
9639        N = pkg.receivers.size();
9640        r = null;
9641        for (i=0; i<N; i++) {
9642            PackageParser.Activity a = pkg.receivers.get(i);
9643            mReceivers.removeActivity(a, "receiver");
9644            if (DEBUG_REMOVE && chatty) {
9645                if (r == null) {
9646                    r = new StringBuilder(256);
9647                } else {
9648                    r.append(' ');
9649                }
9650                r.append(a.info.name);
9651            }
9652        }
9653        if (r != null) {
9654            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9655        }
9656
9657        N = pkg.activities.size();
9658        r = null;
9659        for (i=0; i<N; i++) {
9660            PackageParser.Activity a = pkg.activities.get(i);
9661            mActivities.removeActivity(a, "activity");
9662            if (DEBUG_REMOVE && chatty) {
9663                if (r == null) {
9664                    r = new StringBuilder(256);
9665                } else {
9666                    r.append(' ');
9667                }
9668                r.append(a.info.name);
9669            }
9670        }
9671        if (r != null) {
9672            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9673        }
9674
9675        N = pkg.permissions.size();
9676        r = null;
9677        for (i=0; i<N; i++) {
9678            PackageParser.Permission p = pkg.permissions.get(i);
9679            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9680            if (bp == null) {
9681                bp = mSettings.mPermissionTrees.get(p.info.name);
9682            }
9683            if (bp != null && bp.perm == p) {
9684                bp.perm = null;
9685                if (DEBUG_REMOVE && chatty) {
9686                    if (r == null) {
9687                        r = new StringBuilder(256);
9688                    } else {
9689                        r.append(' ');
9690                    }
9691                    r.append(p.info.name);
9692                }
9693            }
9694            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9695                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9696                if (appOpPkgs != null) {
9697                    appOpPkgs.remove(pkg.packageName);
9698                }
9699            }
9700        }
9701        if (r != null) {
9702            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9703        }
9704
9705        N = pkg.requestedPermissions.size();
9706        r = null;
9707        for (i=0; i<N; i++) {
9708            String perm = pkg.requestedPermissions.get(i);
9709            BasePermission bp = mSettings.mPermissions.get(perm);
9710            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9711                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9712                if (appOpPkgs != null) {
9713                    appOpPkgs.remove(pkg.packageName);
9714                    if (appOpPkgs.isEmpty()) {
9715                        mAppOpPermissionPackages.remove(perm);
9716                    }
9717                }
9718            }
9719        }
9720        if (r != null) {
9721            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9722        }
9723
9724        N = pkg.instrumentation.size();
9725        r = null;
9726        for (i=0; i<N; i++) {
9727            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9728            mInstrumentation.remove(a.getComponentName());
9729            if (DEBUG_REMOVE && chatty) {
9730                if (r == null) {
9731                    r = new StringBuilder(256);
9732                } else {
9733                    r.append(' ');
9734                }
9735                r.append(a.info.name);
9736            }
9737        }
9738        if (r != null) {
9739            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9740        }
9741
9742        r = null;
9743        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9744            // Only system apps can hold shared libraries.
9745            if (pkg.libraryNames != null) {
9746                for (i=0; i<pkg.libraryNames.size(); i++) {
9747                    String name = pkg.libraryNames.get(i);
9748                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9749                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9750                        mSharedLibraries.remove(name);
9751                        if (DEBUG_REMOVE && chatty) {
9752                            if (r == null) {
9753                                r = new StringBuilder(256);
9754                            } else {
9755                                r.append(' ');
9756                            }
9757                            r.append(name);
9758                        }
9759                    }
9760                }
9761            }
9762        }
9763        if (r != null) {
9764            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9765        }
9766    }
9767
9768    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9769        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9770            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9771                return true;
9772            }
9773        }
9774        return false;
9775    }
9776
9777    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9778    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9779    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9780
9781    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9782        // Update the parent permissions
9783        updatePermissionsLPw(pkg.packageName, pkg, flags);
9784        // Update the child permissions
9785        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9786        for (int i = 0; i < childCount; i++) {
9787            PackageParser.Package childPkg = pkg.childPackages.get(i);
9788            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9789        }
9790    }
9791
9792    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9793            int flags) {
9794        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9795        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9796    }
9797
9798    private void updatePermissionsLPw(String changingPkg,
9799            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9800        // Make sure there are no dangling permission trees.
9801        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9802        while (it.hasNext()) {
9803            final BasePermission bp = it.next();
9804            if (bp.packageSetting == null) {
9805                // We may not yet have parsed the package, so just see if
9806                // we still know about its settings.
9807                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9808            }
9809            if (bp.packageSetting == null) {
9810                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9811                        + " from package " + bp.sourcePackage);
9812                it.remove();
9813            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9814                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9815                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9816                            + " from package " + bp.sourcePackage);
9817                    flags |= UPDATE_PERMISSIONS_ALL;
9818                    it.remove();
9819                }
9820            }
9821        }
9822
9823        // Make sure all dynamic permissions have been assigned to a package,
9824        // and make sure there are no dangling permissions.
9825        it = mSettings.mPermissions.values().iterator();
9826        while (it.hasNext()) {
9827            final BasePermission bp = it.next();
9828            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9829                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9830                        + bp.name + " pkg=" + bp.sourcePackage
9831                        + " info=" + bp.pendingInfo);
9832                if (bp.packageSetting == null && bp.pendingInfo != null) {
9833                    final BasePermission tree = findPermissionTreeLP(bp.name);
9834                    if (tree != null && tree.perm != null) {
9835                        bp.packageSetting = tree.packageSetting;
9836                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9837                                new PermissionInfo(bp.pendingInfo));
9838                        bp.perm.info.packageName = tree.perm.info.packageName;
9839                        bp.perm.info.name = bp.name;
9840                        bp.uid = tree.uid;
9841                    }
9842                }
9843            }
9844            if (bp.packageSetting == null) {
9845                // We may not yet have parsed the package, so just see if
9846                // we still know about its settings.
9847                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9848            }
9849            if (bp.packageSetting == null) {
9850                Slog.w(TAG, "Removing dangling permission: " + bp.name
9851                        + " from package " + bp.sourcePackage);
9852                it.remove();
9853            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9854                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9855                    Slog.i(TAG, "Removing old permission: " + bp.name
9856                            + " from package " + bp.sourcePackage);
9857                    flags |= UPDATE_PERMISSIONS_ALL;
9858                    it.remove();
9859                }
9860            }
9861        }
9862
9863        // Now update the permissions for all packages, in particular
9864        // replace the granted permissions of the system packages.
9865        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9866            for (PackageParser.Package pkg : mPackages.values()) {
9867                if (pkg != pkgInfo) {
9868                    // Only replace for packages on requested volume
9869                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9870                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9871                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9872                    grantPermissionsLPw(pkg, replace, changingPkg);
9873                }
9874            }
9875        }
9876
9877        if (pkgInfo != null) {
9878            // Only replace for packages on requested volume
9879            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9880            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9881                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9882            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9883        }
9884    }
9885
9886    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9887            String packageOfInterest) {
9888        // IMPORTANT: There are two types of permissions: install and runtime.
9889        // Install time permissions are granted when the app is installed to
9890        // all device users and users added in the future. Runtime permissions
9891        // are granted at runtime explicitly to specific users. Normal and signature
9892        // protected permissions are install time permissions. Dangerous permissions
9893        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9894        // otherwise they are runtime permissions. This function does not manage
9895        // runtime permissions except for the case an app targeting Lollipop MR1
9896        // being upgraded to target a newer SDK, in which case dangerous permissions
9897        // are transformed from install time to runtime ones.
9898
9899        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9900        if (ps == null) {
9901            return;
9902        }
9903
9904        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9905
9906        PermissionsState permissionsState = ps.getPermissionsState();
9907        PermissionsState origPermissions = permissionsState;
9908
9909        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9910
9911        boolean runtimePermissionsRevoked = false;
9912        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9913
9914        boolean changedInstallPermission = false;
9915
9916        if (replace) {
9917            ps.installPermissionsFixed = false;
9918            if (!ps.isSharedUser()) {
9919                origPermissions = new PermissionsState(permissionsState);
9920                permissionsState.reset();
9921            } else {
9922                // We need to know only about runtime permission changes since the
9923                // calling code always writes the install permissions state but
9924                // the runtime ones are written only if changed. The only cases of
9925                // changed runtime permissions here are promotion of an install to
9926                // runtime and revocation of a runtime from a shared user.
9927                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9928                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9929                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9930                    runtimePermissionsRevoked = true;
9931                }
9932            }
9933        }
9934
9935        permissionsState.setGlobalGids(mGlobalGids);
9936
9937        final int N = pkg.requestedPermissions.size();
9938        for (int i=0; i<N; i++) {
9939            final String name = pkg.requestedPermissions.get(i);
9940            final BasePermission bp = mSettings.mPermissions.get(name);
9941
9942            if (DEBUG_INSTALL) {
9943                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9944            }
9945
9946            if (bp == null || bp.packageSetting == null) {
9947                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9948                    Slog.w(TAG, "Unknown permission " + name
9949                            + " in package " + pkg.packageName);
9950                }
9951                continue;
9952            }
9953
9954            final String perm = bp.name;
9955            boolean allowedSig = false;
9956            int grant = GRANT_DENIED;
9957
9958            // Keep track of app op permissions.
9959            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9960                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9961                if (pkgs == null) {
9962                    pkgs = new ArraySet<>();
9963                    mAppOpPermissionPackages.put(bp.name, pkgs);
9964                }
9965                pkgs.add(pkg.packageName);
9966            }
9967
9968            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9969            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9970                    >= Build.VERSION_CODES.M;
9971            switch (level) {
9972                case PermissionInfo.PROTECTION_NORMAL: {
9973                    // For all apps normal permissions are install time ones.
9974                    grant = GRANT_INSTALL;
9975                } break;
9976
9977                case PermissionInfo.PROTECTION_DANGEROUS: {
9978                    // If a permission review is required for legacy apps we represent
9979                    // their permissions as always granted runtime ones since we need
9980                    // to keep the review required permission flag per user while an
9981                    // install permission's state is shared across all users.
9982                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9983                        // For legacy apps dangerous permissions are install time ones.
9984                        grant = GRANT_INSTALL;
9985                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9986                        // For legacy apps that became modern, install becomes runtime.
9987                        grant = GRANT_UPGRADE;
9988                    } else if (mPromoteSystemApps
9989                            && isSystemApp(ps)
9990                            && mExistingSystemPackages.contains(ps.name)) {
9991                        // For legacy system apps, install becomes runtime.
9992                        // We cannot check hasInstallPermission() for system apps since those
9993                        // permissions were granted implicitly and not persisted pre-M.
9994                        grant = GRANT_UPGRADE;
9995                    } else {
9996                        // For modern apps keep runtime permissions unchanged.
9997                        grant = GRANT_RUNTIME;
9998                    }
9999                } break;
10000
10001                case PermissionInfo.PROTECTION_SIGNATURE: {
10002                    // For all apps signature permissions are install time ones.
10003                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10004                    if (allowedSig) {
10005                        grant = GRANT_INSTALL;
10006                    }
10007                } break;
10008            }
10009
10010            if (DEBUG_INSTALL) {
10011                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10012            }
10013
10014            if (grant != GRANT_DENIED) {
10015                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10016                    // If this is an existing, non-system package, then
10017                    // we can't add any new permissions to it.
10018                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10019                        // Except...  if this is a permission that was added
10020                        // to the platform (note: need to only do this when
10021                        // updating the platform).
10022                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10023                            grant = GRANT_DENIED;
10024                        }
10025                    }
10026                }
10027
10028                switch (grant) {
10029                    case GRANT_INSTALL: {
10030                        // Revoke this as runtime permission to handle the case of
10031                        // a runtime permission being downgraded to an install one.
10032                        // Also in permission review mode we keep dangerous permissions
10033                        // for legacy apps
10034                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10035                            if (origPermissions.getRuntimePermissionState(
10036                                    bp.name, userId) != null) {
10037                                // Revoke the runtime permission and clear the flags.
10038                                origPermissions.revokeRuntimePermission(bp, userId);
10039                                origPermissions.updatePermissionFlags(bp, userId,
10040                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10041                                // If we revoked a permission permission, we have to write.
10042                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10043                                        changedRuntimePermissionUserIds, userId);
10044                            }
10045                        }
10046                        // Grant an install permission.
10047                        if (permissionsState.grantInstallPermission(bp) !=
10048                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10049                            changedInstallPermission = true;
10050                        }
10051                    } break;
10052
10053                    case GRANT_RUNTIME: {
10054                        // Grant previously granted runtime permissions.
10055                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10056                            PermissionState permissionState = origPermissions
10057                                    .getRuntimePermissionState(bp.name, userId);
10058                            int flags = permissionState != null
10059                                    ? permissionState.getFlags() : 0;
10060                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10061                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10062                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10063                                    // If we cannot put the permission as it was, we have to write.
10064                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10065                                            changedRuntimePermissionUserIds, userId);
10066                                }
10067                                // If the app supports runtime permissions no need for a review.
10068                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10069                                        && appSupportsRuntimePermissions
10070                                        && (flags & PackageManager
10071                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10072                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10073                                    // Since we changed the flags, we have to write.
10074                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10075                                            changedRuntimePermissionUserIds, userId);
10076                                }
10077                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10078                                    && !appSupportsRuntimePermissions) {
10079                                // For legacy apps that need a permission review, every new
10080                                // runtime permission is granted but it is pending a review.
10081                                // We also need to review only platform defined runtime
10082                                // permissions as these are the only ones the platform knows
10083                                // how to disable the API to simulate revocation as legacy
10084                                // apps don't expect to run with revoked permissions.
10085                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10086                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10087                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10088                                        // We changed the flags, hence have to write.
10089                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10090                                                changedRuntimePermissionUserIds, userId);
10091                                    }
10092                                }
10093                                if (permissionsState.grantRuntimePermission(bp, userId)
10094                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10095                                    // We changed the permission, hence have to write.
10096                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10097                                            changedRuntimePermissionUserIds, userId);
10098                                }
10099                            }
10100                            // Propagate the permission flags.
10101                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10102                        }
10103                    } break;
10104
10105                    case GRANT_UPGRADE: {
10106                        // Grant runtime permissions for a previously held install permission.
10107                        PermissionState permissionState = origPermissions
10108                                .getInstallPermissionState(bp.name);
10109                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10110
10111                        if (origPermissions.revokeInstallPermission(bp)
10112                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10113                            // We will be transferring the permission flags, so clear them.
10114                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10115                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10116                            changedInstallPermission = true;
10117                        }
10118
10119                        // If the permission is not to be promoted to runtime we ignore it and
10120                        // also its other flags as they are not applicable to install permissions.
10121                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10122                            for (int userId : currentUserIds) {
10123                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10124                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10125                                    // Transfer the permission flags.
10126                                    permissionsState.updatePermissionFlags(bp, userId,
10127                                            flags, flags);
10128                                    // If we granted the permission, we have to write.
10129                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10130                                            changedRuntimePermissionUserIds, userId);
10131                                }
10132                            }
10133                        }
10134                    } break;
10135
10136                    default: {
10137                        if (packageOfInterest == null
10138                                || packageOfInterest.equals(pkg.packageName)) {
10139                            Slog.w(TAG, "Not granting permission " + perm
10140                                    + " to package " + pkg.packageName
10141                                    + " because it was previously installed without");
10142                        }
10143                    } break;
10144                }
10145            } else {
10146                if (permissionsState.revokeInstallPermission(bp) !=
10147                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10148                    // Also drop the permission flags.
10149                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10150                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10151                    changedInstallPermission = true;
10152                    Slog.i(TAG, "Un-granting permission " + perm
10153                            + " from package " + pkg.packageName
10154                            + " (protectionLevel=" + bp.protectionLevel
10155                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10156                            + ")");
10157                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10158                    // Don't print warning for app op permissions, since it is fine for them
10159                    // not to be granted, there is a UI for the user to decide.
10160                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10161                        Slog.w(TAG, "Not granting permission " + perm
10162                                + " to package " + pkg.packageName
10163                                + " (protectionLevel=" + bp.protectionLevel
10164                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10165                                + ")");
10166                    }
10167                }
10168            }
10169        }
10170
10171        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10172                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10173            // This is the first that we have heard about this package, so the
10174            // permissions we have now selected are fixed until explicitly
10175            // changed.
10176            ps.installPermissionsFixed = true;
10177        }
10178
10179        // Persist the runtime permissions state for users with changes. If permissions
10180        // were revoked because no app in the shared user declares them we have to
10181        // write synchronously to avoid losing runtime permissions state.
10182        for (int userId : changedRuntimePermissionUserIds) {
10183            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10184        }
10185
10186        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10187    }
10188
10189    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10190        boolean allowed = false;
10191        final int NP = PackageParser.NEW_PERMISSIONS.length;
10192        for (int ip=0; ip<NP; ip++) {
10193            final PackageParser.NewPermissionInfo npi
10194                    = PackageParser.NEW_PERMISSIONS[ip];
10195            if (npi.name.equals(perm)
10196                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10197                allowed = true;
10198                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10199                        + pkg.packageName);
10200                break;
10201            }
10202        }
10203        return allowed;
10204    }
10205
10206    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10207            BasePermission bp, PermissionsState origPermissions) {
10208        boolean allowed;
10209        allowed = (compareSignatures(
10210                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10211                        == PackageManager.SIGNATURE_MATCH)
10212                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10213                        == PackageManager.SIGNATURE_MATCH);
10214        if (!allowed && (bp.protectionLevel
10215                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10216            if (isSystemApp(pkg)) {
10217                // For updated system applications, a system permission
10218                // is granted only if it had been defined by the original application.
10219                if (pkg.isUpdatedSystemApp()) {
10220                    final PackageSetting sysPs = mSettings
10221                            .getDisabledSystemPkgLPr(pkg.packageName);
10222                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10223                        // If the original was granted this permission, we take
10224                        // that grant decision as read and propagate it to the
10225                        // update.
10226                        if (sysPs.isPrivileged()) {
10227                            allowed = true;
10228                        }
10229                    } else {
10230                        // The system apk may have been updated with an older
10231                        // version of the one on the data partition, but which
10232                        // granted a new system permission that it didn't have
10233                        // before.  In this case we do want to allow the app to
10234                        // now get the new permission if the ancestral apk is
10235                        // privileged to get it.
10236                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10237                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10238                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10239                                    allowed = true;
10240                                    break;
10241                                }
10242                            }
10243                        }
10244                        // Also if a privileged parent package on the system image or any of
10245                        // its children requested a privileged permission, the updated child
10246                        // packages can also get the permission.
10247                        if (pkg.parentPackage != null) {
10248                            final PackageSetting disabledSysParentPs = mSettings
10249                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10250                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10251                                    && disabledSysParentPs.isPrivileged()) {
10252                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10253                                    allowed = true;
10254                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10255                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10256                                    for (int i = 0; i < count; i++) {
10257                                        PackageParser.Package disabledSysChildPkg =
10258                                                disabledSysParentPs.pkg.childPackages.get(i);
10259                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10260                                                perm)) {
10261                                            allowed = true;
10262                                            break;
10263                                        }
10264                                    }
10265                                }
10266                            }
10267                        }
10268                    }
10269                } else {
10270                    allowed = isPrivilegedApp(pkg);
10271                }
10272            }
10273        }
10274        if (!allowed) {
10275            if (!allowed && (bp.protectionLevel
10276                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10277                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10278                // If this was a previously normal/dangerous permission that got moved
10279                // to a system permission as part of the runtime permission redesign, then
10280                // we still want to blindly grant it to old apps.
10281                allowed = true;
10282            }
10283            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10284                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10285                // If this permission is to be granted to the system installer and
10286                // this app is an installer, then it gets the permission.
10287                allowed = true;
10288            }
10289            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10290                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10291                // If this permission is to be granted to the system verifier and
10292                // this app is a verifier, then it gets the permission.
10293                allowed = true;
10294            }
10295            if (!allowed && (bp.protectionLevel
10296                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10297                    && isSystemApp(pkg)) {
10298                // Any pre-installed system app is allowed to get this permission.
10299                allowed = true;
10300            }
10301            if (!allowed && (bp.protectionLevel
10302                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10303                // For development permissions, a development permission
10304                // is granted only if it was already granted.
10305                allowed = origPermissions.hasInstallPermission(perm);
10306            }
10307            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10308                    && pkg.packageName.equals(mSetupWizardPackage)) {
10309                // If this permission is to be granted to the system setup wizard and
10310                // this app is a setup wizard, then it gets the permission.
10311                allowed = true;
10312            }
10313        }
10314        return allowed;
10315    }
10316
10317    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10318        final int permCount = pkg.requestedPermissions.size();
10319        for (int j = 0; j < permCount; j++) {
10320            String requestedPermission = pkg.requestedPermissions.get(j);
10321            if (permission.equals(requestedPermission)) {
10322                return true;
10323            }
10324        }
10325        return false;
10326    }
10327
10328    final class ActivityIntentResolver
10329            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10330        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10331                boolean defaultOnly, int userId) {
10332            if (!sUserManager.exists(userId)) return null;
10333            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10334            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10335        }
10336
10337        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10338                int userId) {
10339            if (!sUserManager.exists(userId)) return null;
10340            mFlags = flags;
10341            return super.queryIntent(intent, resolvedType,
10342                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10343        }
10344
10345        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10346                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10347            if (!sUserManager.exists(userId)) return null;
10348            if (packageActivities == null) {
10349                return null;
10350            }
10351            mFlags = flags;
10352            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10353            final int N = packageActivities.size();
10354            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10355                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10356
10357            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10358            for (int i = 0; i < N; ++i) {
10359                intentFilters = packageActivities.get(i).intents;
10360                if (intentFilters != null && intentFilters.size() > 0) {
10361                    PackageParser.ActivityIntentInfo[] array =
10362                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10363                    intentFilters.toArray(array);
10364                    listCut.add(array);
10365                }
10366            }
10367            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10368        }
10369
10370        /**
10371         * Finds a privileged activity that matches the specified activity names.
10372         */
10373        private PackageParser.Activity findMatchingActivity(
10374                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10375            for (PackageParser.Activity sysActivity : activityList) {
10376                if (sysActivity.info.name.equals(activityInfo.name)) {
10377                    return sysActivity;
10378                }
10379                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10380                    return sysActivity;
10381                }
10382                if (sysActivity.info.targetActivity != null) {
10383                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10384                        return sysActivity;
10385                    }
10386                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10387                        return sysActivity;
10388                    }
10389                }
10390            }
10391            return null;
10392        }
10393
10394        public class IterGenerator<E> {
10395            public Iterator<E> generate(ActivityIntentInfo info) {
10396                return null;
10397            }
10398        }
10399
10400        public class ActionIterGenerator extends IterGenerator<String> {
10401            @Override
10402            public Iterator<String> generate(ActivityIntentInfo info) {
10403                return info.actionsIterator();
10404            }
10405        }
10406
10407        public class CategoriesIterGenerator extends IterGenerator<String> {
10408            @Override
10409            public Iterator<String> generate(ActivityIntentInfo info) {
10410                return info.categoriesIterator();
10411            }
10412        }
10413
10414        public class SchemesIterGenerator extends IterGenerator<String> {
10415            @Override
10416            public Iterator<String> generate(ActivityIntentInfo info) {
10417                return info.schemesIterator();
10418            }
10419        }
10420
10421        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10422            @Override
10423            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10424                return info.authoritiesIterator();
10425            }
10426        }
10427
10428        /**
10429         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10430         * MODIFIED. Do not pass in a list that should not be changed.
10431         */
10432        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10433                IterGenerator<T> generator, Iterator<T> searchIterator) {
10434            // loop through the set of actions; every one must be found in the intent filter
10435            while (searchIterator.hasNext()) {
10436                // we must have at least one filter in the list to consider a match
10437                if (intentList.size() == 0) {
10438                    break;
10439                }
10440
10441                final T searchAction = searchIterator.next();
10442
10443                // loop through the set of intent filters
10444                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10445                while (intentIter.hasNext()) {
10446                    final ActivityIntentInfo intentInfo = intentIter.next();
10447                    boolean selectionFound = false;
10448
10449                    // loop through the intent filter's selection criteria; at least one
10450                    // of them must match the searched criteria
10451                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10452                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10453                        final T intentSelection = intentSelectionIter.next();
10454                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10455                            selectionFound = true;
10456                            break;
10457                        }
10458                    }
10459
10460                    // the selection criteria wasn't found in this filter's set; this filter
10461                    // is not a potential match
10462                    if (!selectionFound) {
10463                        intentIter.remove();
10464                    }
10465                }
10466            }
10467        }
10468
10469        private boolean isProtectedAction(ActivityIntentInfo filter) {
10470            final Iterator<String> actionsIter = filter.actionsIterator();
10471            while (actionsIter != null && actionsIter.hasNext()) {
10472                final String filterAction = actionsIter.next();
10473                if (PROTECTED_ACTIONS.contains(filterAction)) {
10474                    return true;
10475                }
10476            }
10477            return false;
10478        }
10479
10480        /**
10481         * Adjusts the priority of the given intent filter according to policy.
10482         * <p>
10483         * <ul>
10484         * <li>The priority for non privileged applications is capped to '0'</li>
10485         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10486         * <li>The priority for unbundled updates to privileged applications is capped to the
10487         *      priority defined on the system partition</li>
10488         * </ul>
10489         * <p>
10490         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10491         * allowed to obtain any priority on any action.
10492         */
10493        private void adjustPriority(
10494                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10495            // nothing to do; priority is fine as-is
10496            if (intent.getPriority() <= 0) {
10497                return;
10498            }
10499
10500            final ActivityInfo activityInfo = intent.activity.info;
10501            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10502
10503            final boolean privilegedApp =
10504                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10505            if (!privilegedApp) {
10506                // non-privileged applications can never define a priority >0
10507                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10508                        + " package: " + applicationInfo.packageName
10509                        + " activity: " + intent.activity.className
10510                        + " origPrio: " + intent.getPriority());
10511                intent.setPriority(0);
10512                return;
10513            }
10514
10515            if (systemActivities == null) {
10516                // the system package is not disabled; we're parsing the system partition
10517                if (isProtectedAction(intent)) {
10518                    if (mDeferProtectedFilters) {
10519                        // We can't deal with these just yet. No component should ever obtain a
10520                        // >0 priority for a protected actions, with ONE exception -- the setup
10521                        // wizard. The setup wizard, however, cannot be known until we're able to
10522                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10523                        // until all intent filters have been processed. Chicken, meet egg.
10524                        // Let the filter temporarily have a high priority and rectify the
10525                        // priorities after all system packages have been scanned.
10526                        mProtectedFilters.add(intent);
10527                        if (DEBUG_FILTERS) {
10528                            Slog.i(TAG, "Protected action; save for later;"
10529                                    + " package: " + applicationInfo.packageName
10530                                    + " activity: " + intent.activity.className
10531                                    + " origPrio: " + intent.getPriority());
10532                        }
10533                        return;
10534                    } else {
10535                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10536                            Slog.i(TAG, "No setup wizard;"
10537                                + " All protected intents capped to priority 0");
10538                        }
10539                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10540                            if (DEBUG_FILTERS) {
10541                                Slog.i(TAG, "Found setup wizard;"
10542                                    + " allow priority " + intent.getPriority() + ";"
10543                                    + " package: " + intent.activity.info.packageName
10544                                    + " activity: " + intent.activity.className
10545                                    + " priority: " + intent.getPriority());
10546                            }
10547                            // setup wizard gets whatever it wants
10548                            return;
10549                        }
10550                        Slog.w(TAG, "Protected action; cap priority to 0;"
10551                                + " package: " + intent.activity.info.packageName
10552                                + " activity: " + intent.activity.className
10553                                + " origPrio: " + intent.getPriority());
10554                        intent.setPriority(0);
10555                        return;
10556                    }
10557                }
10558                // privileged apps on the system image get whatever priority they request
10559                return;
10560            }
10561
10562            // privileged app unbundled update ... try to find the same activity
10563            final PackageParser.Activity foundActivity =
10564                    findMatchingActivity(systemActivities, activityInfo);
10565            if (foundActivity == null) {
10566                // this is a new activity; it cannot obtain >0 priority
10567                if (DEBUG_FILTERS) {
10568                    Slog.i(TAG, "New activity; cap priority to 0;"
10569                            + " package: " + applicationInfo.packageName
10570                            + " activity: " + intent.activity.className
10571                            + " origPrio: " + intent.getPriority());
10572                }
10573                intent.setPriority(0);
10574                return;
10575            }
10576
10577            // found activity, now check for filter equivalence
10578
10579            // a shallow copy is enough; we modify the list, not its contents
10580            final List<ActivityIntentInfo> intentListCopy =
10581                    new ArrayList<>(foundActivity.intents);
10582            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10583
10584            // find matching action subsets
10585            final Iterator<String> actionsIterator = intent.actionsIterator();
10586            if (actionsIterator != null) {
10587                getIntentListSubset(
10588                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10589                if (intentListCopy.size() == 0) {
10590                    // no more intents to match; we're not equivalent
10591                    if (DEBUG_FILTERS) {
10592                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10593                                + " package: " + applicationInfo.packageName
10594                                + " activity: " + intent.activity.className
10595                                + " origPrio: " + intent.getPriority());
10596                    }
10597                    intent.setPriority(0);
10598                    return;
10599                }
10600            }
10601
10602            // find matching category subsets
10603            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10604            if (categoriesIterator != null) {
10605                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10606                        categoriesIterator);
10607                if (intentListCopy.size() == 0) {
10608                    // no more intents to match; we're not equivalent
10609                    if (DEBUG_FILTERS) {
10610                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10611                                + " package: " + applicationInfo.packageName
10612                                + " activity: " + intent.activity.className
10613                                + " origPrio: " + intent.getPriority());
10614                    }
10615                    intent.setPriority(0);
10616                    return;
10617                }
10618            }
10619
10620            // find matching schemes subsets
10621            final Iterator<String> schemesIterator = intent.schemesIterator();
10622            if (schemesIterator != null) {
10623                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10624                        schemesIterator);
10625                if (intentListCopy.size() == 0) {
10626                    // no more intents to match; we're not equivalent
10627                    if (DEBUG_FILTERS) {
10628                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10629                                + " package: " + applicationInfo.packageName
10630                                + " activity: " + intent.activity.className
10631                                + " origPrio: " + intent.getPriority());
10632                    }
10633                    intent.setPriority(0);
10634                    return;
10635                }
10636            }
10637
10638            // find matching authorities subsets
10639            final Iterator<IntentFilter.AuthorityEntry>
10640                    authoritiesIterator = intent.authoritiesIterator();
10641            if (authoritiesIterator != null) {
10642                getIntentListSubset(intentListCopy,
10643                        new AuthoritiesIterGenerator(),
10644                        authoritiesIterator);
10645                if (intentListCopy.size() == 0) {
10646                    // no more intents to match; we're not equivalent
10647                    if (DEBUG_FILTERS) {
10648                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10649                                + " package: " + applicationInfo.packageName
10650                                + " activity: " + intent.activity.className
10651                                + " origPrio: " + intent.getPriority());
10652                    }
10653                    intent.setPriority(0);
10654                    return;
10655                }
10656            }
10657
10658            // we found matching filter(s); app gets the max priority of all intents
10659            int cappedPriority = 0;
10660            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10661                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10662            }
10663            if (intent.getPriority() > cappedPriority) {
10664                if (DEBUG_FILTERS) {
10665                    Slog.i(TAG, "Found matching filter(s);"
10666                            + " cap priority to " + cappedPriority + ";"
10667                            + " package: " + applicationInfo.packageName
10668                            + " activity: " + intent.activity.className
10669                            + " origPrio: " + intent.getPriority());
10670                }
10671                intent.setPriority(cappedPriority);
10672                return;
10673            }
10674            // all this for nothing; the requested priority was <= what was on the system
10675        }
10676
10677        public final void addActivity(PackageParser.Activity a, String type) {
10678            mActivities.put(a.getComponentName(), a);
10679            if (DEBUG_SHOW_INFO)
10680                Log.v(
10681                TAG, "  " + type + " " +
10682                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10683            if (DEBUG_SHOW_INFO)
10684                Log.v(TAG, "    Class=" + a.info.name);
10685            final int NI = a.intents.size();
10686            for (int j=0; j<NI; j++) {
10687                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10688                if ("activity".equals(type)) {
10689                    final PackageSetting ps =
10690                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10691                    final List<PackageParser.Activity> systemActivities =
10692                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10693                    adjustPriority(systemActivities, intent);
10694                }
10695                if (DEBUG_SHOW_INFO) {
10696                    Log.v(TAG, "    IntentFilter:");
10697                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10698                }
10699                if (!intent.debugCheck()) {
10700                    Log.w(TAG, "==> For Activity " + a.info.name);
10701                }
10702                addFilter(intent);
10703            }
10704        }
10705
10706        public final void removeActivity(PackageParser.Activity a, String type) {
10707            mActivities.remove(a.getComponentName());
10708            if (DEBUG_SHOW_INFO) {
10709                Log.v(TAG, "  " + type + " "
10710                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10711                                : a.info.name) + ":");
10712                Log.v(TAG, "    Class=" + a.info.name);
10713            }
10714            final int NI = a.intents.size();
10715            for (int j=0; j<NI; j++) {
10716                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10717                if (DEBUG_SHOW_INFO) {
10718                    Log.v(TAG, "    IntentFilter:");
10719                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10720                }
10721                removeFilter(intent);
10722            }
10723        }
10724
10725        @Override
10726        protected boolean allowFilterResult(
10727                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10728            ActivityInfo filterAi = filter.activity.info;
10729            for (int i=dest.size()-1; i>=0; i--) {
10730                ActivityInfo destAi = dest.get(i).activityInfo;
10731                if (destAi.name == filterAi.name
10732                        && destAi.packageName == filterAi.packageName) {
10733                    return false;
10734                }
10735            }
10736            return true;
10737        }
10738
10739        @Override
10740        protected ActivityIntentInfo[] newArray(int size) {
10741            return new ActivityIntentInfo[size];
10742        }
10743
10744        @Override
10745        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10746            if (!sUserManager.exists(userId)) return true;
10747            PackageParser.Package p = filter.activity.owner;
10748            if (p != null) {
10749                PackageSetting ps = (PackageSetting)p.mExtras;
10750                if (ps != null) {
10751                    // System apps are never considered stopped for purposes of
10752                    // filtering, because there may be no way for the user to
10753                    // actually re-launch them.
10754                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10755                            && ps.getStopped(userId);
10756                }
10757            }
10758            return false;
10759        }
10760
10761        @Override
10762        protected boolean isPackageForFilter(String packageName,
10763                PackageParser.ActivityIntentInfo info) {
10764            return packageName.equals(info.activity.owner.packageName);
10765        }
10766
10767        @Override
10768        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10769                int match, int userId) {
10770            if (!sUserManager.exists(userId)) return null;
10771            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10772                return null;
10773            }
10774            final PackageParser.Activity activity = info.activity;
10775            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10776            if (ps == null) {
10777                return null;
10778            }
10779            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10780                    ps.readUserState(userId), userId);
10781            if (ai == null) {
10782                return null;
10783            }
10784            final ResolveInfo res = new ResolveInfo();
10785            res.activityInfo = ai;
10786            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10787                res.filter = info;
10788            }
10789            if (info != null) {
10790                res.handleAllWebDataURI = info.handleAllWebDataURI();
10791            }
10792            res.priority = info.getPriority();
10793            res.preferredOrder = activity.owner.mPreferredOrder;
10794            //System.out.println("Result: " + res.activityInfo.className +
10795            //                   " = " + res.priority);
10796            res.match = match;
10797            res.isDefault = info.hasDefault;
10798            res.labelRes = info.labelRes;
10799            res.nonLocalizedLabel = info.nonLocalizedLabel;
10800            if (userNeedsBadging(userId)) {
10801                res.noResourceId = true;
10802            } else {
10803                res.icon = info.icon;
10804            }
10805            res.iconResourceId = info.icon;
10806            res.system = res.activityInfo.applicationInfo.isSystemApp();
10807            return res;
10808        }
10809
10810        @Override
10811        protected void sortResults(List<ResolveInfo> results) {
10812            Collections.sort(results, mResolvePrioritySorter);
10813        }
10814
10815        @Override
10816        protected void dumpFilter(PrintWriter out, String prefix,
10817                PackageParser.ActivityIntentInfo filter) {
10818            out.print(prefix); out.print(
10819                    Integer.toHexString(System.identityHashCode(filter.activity)));
10820                    out.print(' ');
10821                    filter.activity.printComponentShortName(out);
10822                    out.print(" filter ");
10823                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10824        }
10825
10826        @Override
10827        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10828            return filter.activity;
10829        }
10830
10831        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10832            PackageParser.Activity activity = (PackageParser.Activity)label;
10833            out.print(prefix); out.print(
10834                    Integer.toHexString(System.identityHashCode(activity)));
10835                    out.print(' ');
10836                    activity.printComponentShortName(out);
10837            if (count > 1) {
10838                out.print(" ("); out.print(count); out.print(" filters)");
10839            }
10840            out.println();
10841        }
10842
10843        // Keys are String (activity class name), values are Activity.
10844        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10845                = new ArrayMap<ComponentName, PackageParser.Activity>();
10846        private int mFlags;
10847    }
10848
10849    private final class ServiceIntentResolver
10850            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10851        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10852                boolean defaultOnly, int userId) {
10853            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10854            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10855        }
10856
10857        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10858                int userId) {
10859            if (!sUserManager.exists(userId)) return null;
10860            mFlags = flags;
10861            return super.queryIntent(intent, resolvedType,
10862                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10863        }
10864
10865        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10866                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10867            if (!sUserManager.exists(userId)) return null;
10868            if (packageServices == null) {
10869                return null;
10870            }
10871            mFlags = flags;
10872            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10873            final int N = packageServices.size();
10874            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10875                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10876
10877            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10878            for (int i = 0; i < N; ++i) {
10879                intentFilters = packageServices.get(i).intents;
10880                if (intentFilters != null && intentFilters.size() > 0) {
10881                    PackageParser.ServiceIntentInfo[] array =
10882                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10883                    intentFilters.toArray(array);
10884                    listCut.add(array);
10885                }
10886            }
10887            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10888        }
10889
10890        public final void addService(PackageParser.Service s) {
10891            mServices.put(s.getComponentName(), s);
10892            if (DEBUG_SHOW_INFO) {
10893                Log.v(TAG, "  "
10894                        + (s.info.nonLocalizedLabel != null
10895                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10896                Log.v(TAG, "    Class=" + s.info.name);
10897            }
10898            final int NI = s.intents.size();
10899            int j;
10900            for (j=0; j<NI; j++) {
10901                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10902                if (DEBUG_SHOW_INFO) {
10903                    Log.v(TAG, "    IntentFilter:");
10904                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10905                }
10906                if (!intent.debugCheck()) {
10907                    Log.w(TAG, "==> For Service " + s.info.name);
10908                }
10909                addFilter(intent);
10910            }
10911        }
10912
10913        public final void removeService(PackageParser.Service s) {
10914            mServices.remove(s.getComponentName());
10915            if (DEBUG_SHOW_INFO) {
10916                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10917                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10918                Log.v(TAG, "    Class=" + s.info.name);
10919            }
10920            final int NI = s.intents.size();
10921            int j;
10922            for (j=0; j<NI; j++) {
10923                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10924                if (DEBUG_SHOW_INFO) {
10925                    Log.v(TAG, "    IntentFilter:");
10926                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10927                }
10928                removeFilter(intent);
10929            }
10930        }
10931
10932        @Override
10933        protected boolean allowFilterResult(
10934                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10935            ServiceInfo filterSi = filter.service.info;
10936            for (int i=dest.size()-1; i>=0; i--) {
10937                ServiceInfo destAi = dest.get(i).serviceInfo;
10938                if (destAi.name == filterSi.name
10939                        && destAi.packageName == filterSi.packageName) {
10940                    return false;
10941                }
10942            }
10943            return true;
10944        }
10945
10946        @Override
10947        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10948            return new PackageParser.ServiceIntentInfo[size];
10949        }
10950
10951        @Override
10952        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10953            if (!sUserManager.exists(userId)) return true;
10954            PackageParser.Package p = filter.service.owner;
10955            if (p != null) {
10956                PackageSetting ps = (PackageSetting)p.mExtras;
10957                if (ps != null) {
10958                    // System apps are never considered stopped for purposes of
10959                    // filtering, because there may be no way for the user to
10960                    // actually re-launch them.
10961                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10962                            && ps.getStopped(userId);
10963                }
10964            }
10965            return false;
10966        }
10967
10968        @Override
10969        protected boolean isPackageForFilter(String packageName,
10970                PackageParser.ServiceIntentInfo info) {
10971            return packageName.equals(info.service.owner.packageName);
10972        }
10973
10974        @Override
10975        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10976                int match, int userId) {
10977            if (!sUserManager.exists(userId)) return null;
10978            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10979            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10980                return null;
10981            }
10982            final PackageParser.Service service = info.service;
10983            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10984            if (ps == null) {
10985                return null;
10986            }
10987            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10988                    ps.readUserState(userId), userId);
10989            if (si == null) {
10990                return null;
10991            }
10992            final ResolveInfo res = new ResolveInfo();
10993            res.serviceInfo = si;
10994            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10995                res.filter = filter;
10996            }
10997            res.priority = info.getPriority();
10998            res.preferredOrder = service.owner.mPreferredOrder;
10999            res.match = match;
11000            res.isDefault = info.hasDefault;
11001            res.labelRes = info.labelRes;
11002            res.nonLocalizedLabel = info.nonLocalizedLabel;
11003            res.icon = info.icon;
11004            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11005            return res;
11006        }
11007
11008        @Override
11009        protected void sortResults(List<ResolveInfo> results) {
11010            Collections.sort(results, mResolvePrioritySorter);
11011        }
11012
11013        @Override
11014        protected void dumpFilter(PrintWriter out, String prefix,
11015                PackageParser.ServiceIntentInfo filter) {
11016            out.print(prefix); out.print(
11017                    Integer.toHexString(System.identityHashCode(filter.service)));
11018                    out.print(' ');
11019                    filter.service.printComponentShortName(out);
11020                    out.print(" filter ");
11021                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11022        }
11023
11024        @Override
11025        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11026            return filter.service;
11027        }
11028
11029        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11030            PackageParser.Service service = (PackageParser.Service)label;
11031            out.print(prefix); out.print(
11032                    Integer.toHexString(System.identityHashCode(service)));
11033                    out.print(' ');
11034                    service.printComponentShortName(out);
11035            if (count > 1) {
11036                out.print(" ("); out.print(count); out.print(" filters)");
11037            }
11038            out.println();
11039        }
11040
11041//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11042//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11043//            final List<ResolveInfo> retList = Lists.newArrayList();
11044//            while (i.hasNext()) {
11045//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11046//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11047//                    retList.add(resolveInfo);
11048//                }
11049//            }
11050//            return retList;
11051//        }
11052
11053        // Keys are String (activity class name), values are Activity.
11054        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11055                = new ArrayMap<ComponentName, PackageParser.Service>();
11056        private int mFlags;
11057    };
11058
11059    private final class ProviderIntentResolver
11060            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11061        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11062                boolean defaultOnly, int userId) {
11063            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11064            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11065        }
11066
11067        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11068                int userId) {
11069            if (!sUserManager.exists(userId))
11070                return null;
11071            mFlags = flags;
11072            return super.queryIntent(intent, resolvedType,
11073                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11074        }
11075
11076        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11077                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11078            if (!sUserManager.exists(userId))
11079                return null;
11080            if (packageProviders == null) {
11081                return null;
11082            }
11083            mFlags = flags;
11084            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11085            final int N = packageProviders.size();
11086            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11087                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11088
11089            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11090            for (int i = 0; i < N; ++i) {
11091                intentFilters = packageProviders.get(i).intents;
11092                if (intentFilters != null && intentFilters.size() > 0) {
11093                    PackageParser.ProviderIntentInfo[] array =
11094                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11095                    intentFilters.toArray(array);
11096                    listCut.add(array);
11097                }
11098            }
11099            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11100        }
11101
11102        public final void addProvider(PackageParser.Provider p) {
11103            if (mProviders.containsKey(p.getComponentName())) {
11104                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11105                return;
11106            }
11107
11108            mProviders.put(p.getComponentName(), p);
11109            if (DEBUG_SHOW_INFO) {
11110                Log.v(TAG, "  "
11111                        + (p.info.nonLocalizedLabel != null
11112                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11113                Log.v(TAG, "    Class=" + p.info.name);
11114            }
11115            final int NI = p.intents.size();
11116            int j;
11117            for (j = 0; j < NI; j++) {
11118                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11119                if (DEBUG_SHOW_INFO) {
11120                    Log.v(TAG, "    IntentFilter:");
11121                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11122                }
11123                if (!intent.debugCheck()) {
11124                    Log.w(TAG, "==> For Provider " + p.info.name);
11125                }
11126                addFilter(intent);
11127            }
11128        }
11129
11130        public final void removeProvider(PackageParser.Provider p) {
11131            mProviders.remove(p.getComponentName());
11132            if (DEBUG_SHOW_INFO) {
11133                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11134                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11135                Log.v(TAG, "    Class=" + p.info.name);
11136            }
11137            final int NI = p.intents.size();
11138            int j;
11139            for (j = 0; j < NI; j++) {
11140                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11141                if (DEBUG_SHOW_INFO) {
11142                    Log.v(TAG, "    IntentFilter:");
11143                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11144                }
11145                removeFilter(intent);
11146            }
11147        }
11148
11149        @Override
11150        protected boolean allowFilterResult(
11151                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11152            ProviderInfo filterPi = filter.provider.info;
11153            for (int i = dest.size() - 1; i >= 0; i--) {
11154                ProviderInfo destPi = dest.get(i).providerInfo;
11155                if (destPi.name == filterPi.name
11156                        && destPi.packageName == filterPi.packageName) {
11157                    return false;
11158                }
11159            }
11160            return true;
11161        }
11162
11163        @Override
11164        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11165            return new PackageParser.ProviderIntentInfo[size];
11166        }
11167
11168        @Override
11169        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11170            if (!sUserManager.exists(userId))
11171                return true;
11172            PackageParser.Package p = filter.provider.owner;
11173            if (p != null) {
11174                PackageSetting ps = (PackageSetting) p.mExtras;
11175                if (ps != null) {
11176                    // System apps are never considered stopped for purposes of
11177                    // filtering, because there may be no way for the user to
11178                    // actually re-launch them.
11179                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11180                            && ps.getStopped(userId);
11181                }
11182            }
11183            return false;
11184        }
11185
11186        @Override
11187        protected boolean isPackageForFilter(String packageName,
11188                PackageParser.ProviderIntentInfo info) {
11189            return packageName.equals(info.provider.owner.packageName);
11190        }
11191
11192        @Override
11193        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11194                int match, int userId) {
11195            if (!sUserManager.exists(userId))
11196                return null;
11197            final PackageParser.ProviderIntentInfo info = filter;
11198            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11199                return null;
11200            }
11201            final PackageParser.Provider provider = info.provider;
11202            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11203            if (ps == null) {
11204                return null;
11205            }
11206            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11207                    ps.readUserState(userId), userId);
11208            if (pi == null) {
11209                return null;
11210            }
11211            final ResolveInfo res = new ResolveInfo();
11212            res.providerInfo = pi;
11213            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11214                res.filter = filter;
11215            }
11216            res.priority = info.getPriority();
11217            res.preferredOrder = provider.owner.mPreferredOrder;
11218            res.match = match;
11219            res.isDefault = info.hasDefault;
11220            res.labelRes = info.labelRes;
11221            res.nonLocalizedLabel = info.nonLocalizedLabel;
11222            res.icon = info.icon;
11223            res.system = res.providerInfo.applicationInfo.isSystemApp();
11224            return res;
11225        }
11226
11227        @Override
11228        protected void sortResults(List<ResolveInfo> results) {
11229            Collections.sort(results, mResolvePrioritySorter);
11230        }
11231
11232        @Override
11233        protected void dumpFilter(PrintWriter out, String prefix,
11234                PackageParser.ProviderIntentInfo filter) {
11235            out.print(prefix);
11236            out.print(
11237                    Integer.toHexString(System.identityHashCode(filter.provider)));
11238            out.print(' ');
11239            filter.provider.printComponentShortName(out);
11240            out.print(" filter ");
11241            out.println(Integer.toHexString(System.identityHashCode(filter)));
11242        }
11243
11244        @Override
11245        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11246            return filter.provider;
11247        }
11248
11249        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11250            PackageParser.Provider provider = (PackageParser.Provider)label;
11251            out.print(prefix); out.print(
11252                    Integer.toHexString(System.identityHashCode(provider)));
11253                    out.print(' ');
11254                    provider.printComponentShortName(out);
11255            if (count > 1) {
11256                out.print(" ("); out.print(count); out.print(" filters)");
11257            }
11258            out.println();
11259        }
11260
11261        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11262                = new ArrayMap<ComponentName, PackageParser.Provider>();
11263        private int mFlags;
11264    }
11265
11266    private static final class EphemeralIntentResolver
11267            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11268        @Override
11269        protected EphemeralResolveIntentInfo[] newArray(int size) {
11270            return new EphemeralResolveIntentInfo[size];
11271        }
11272
11273        @Override
11274        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11275            return true;
11276        }
11277
11278        @Override
11279        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11280                int userId) {
11281            if (!sUserManager.exists(userId)) {
11282                return null;
11283            }
11284            return info.getEphemeralResolveInfo();
11285        }
11286    }
11287
11288    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11289            new Comparator<ResolveInfo>() {
11290        public int compare(ResolveInfo r1, ResolveInfo r2) {
11291            int v1 = r1.priority;
11292            int v2 = r2.priority;
11293            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11294            if (v1 != v2) {
11295                return (v1 > v2) ? -1 : 1;
11296            }
11297            v1 = r1.preferredOrder;
11298            v2 = r2.preferredOrder;
11299            if (v1 != v2) {
11300                return (v1 > v2) ? -1 : 1;
11301            }
11302            if (r1.isDefault != r2.isDefault) {
11303                return r1.isDefault ? -1 : 1;
11304            }
11305            v1 = r1.match;
11306            v2 = r2.match;
11307            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11308            if (v1 != v2) {
11309                return (v1 > v2) ? -1 : 1;
11310            }
11311            if (r1.system != r2.system) {
11312                return r1.system ? -1 : 1;
11313            }
11314            if (r1.activityInfo != null) {
11315                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11316            }
11317            if (r1.serviceInfo != null) {
11318                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11319            }
11320            if (r1.providerInfo != null) {
11321                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11322            }
11323            return 0;
11324        }
11325    };
11326
11327    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11328            new Comparator<ProviderInfo>() {
11329        public int compare(ProviderInfo p1, ProviderInfo p2) {
11330            final int v1 = p1.initOrder;
11331            final int v2 = p2.initOrder;
11332            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11333        }
11334    };
11335
11336    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11337            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11338            final int[] userIds) {
11339        mHandler.post(new Runnable() {
11340            @Override
11341            public void run() {
11342                try {
11343                    final IActivityManager am = ActivityManagerNative.getDefault();
11344                    if (am == null) return;
11345                    final int[] resolvedUserIds;
11346                    if (userIds == null) {
11347                        resolvedUserIds = am.getRunningUserIds();
11348                    } else {
11349                        resolvedUserIds = userIds;
11350                    }
11351                    for (int id : resolvedUserIds) {
11352                        final Intent intent = new Intent(action,
11353                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11354                        if (extras != null) {
11355                            intent.putExtras(extras);
11356                        }
11357                        if (targetPkg != null) {
11358                            intent.setPackage(targetPkg);
11359                        }
11360                        // Modify the UID when posting to other users
11361                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11362                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11363                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11364                            intent.putExtra(Intent.EXTRA_UID, uid);
11365                        }
11366                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11367                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11368                        if (DEBUG_BROADCASTS) {
11369                            RuntimeException here = new RuntimeException("here");
11370                            here.fillInStackTrace();
11371                            Slog.d(TAG, "Sending to user " + id + ": "
11372                                    + intent.toShortString(false, true, false, false)
11373                                    + " " + intent.getExtras(), here);
11374                        }
11375                        am.broadcastIntent(null, intent, null, finishedReceiver,
11376                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11377                                null, finishedReceiver != null, false, id);
11378                    }
11379                } catch (RemoteException ex) {
11380                }
11381            }
11382        });
11383    }
11384
11385    /**
11386     * Check if the external storage media is available. This is true if there
11387     * is a mounted external storage medium or if the external storage is
11388     * emulated.
11389     */
11390    private boolean isExternalMediaAvailable() {
11391        return mMediaMounted || Environment.isExternalStorageEmulated();
11392    }
11393
11394    @Override
11395    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11396        // writer
11397        synchronized (mPackages) {
11398            if (!isExternalMediaAvailable()) {
11399                // If the external storage is no longer mounted at this point,
11400                // the caller may not have been able to delete all of this
11401                // packages files and can not delete any more.  Bail.
11402                return null;
11403            }
11404            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11405            if (lastPackage != null) {
11406                pkgs.remove(lastPackage);
11407            }
11408            if (pkgs.size() > 0) {
11409                return pkgs.get(0);
11410            }
11411        }
11412        return null;
11413    }
11414
11415    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11416        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11417                userId, andCode ? 1 : 0, packageName);
11418        if (mSystemReady) {
11419            msg.sendToTarget();
11420        } else {
11421            if (mPostSystemReadyMessages == null) {
11422                mPostSystemReadyMessages = new ArrayList<>();
11423            }
11424            mPostSystemReadyMessages.add(msg);
11425        }
11426    }
11427
11428    void startCleaningPackages() {
11429        // reader
11430        if (!isExternalMediaAvailable()) {
11431            return;
11432        }
11433        synchronized (mPackages) {
11434            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11435                return;
11436            }
11437        }
11438        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11439        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11440        IActivityManager am = ActivityManagerNative.getDefault();
11441        if (am != null) {
11442            try {
11443                am.startService(null, intent, null, mContext.getOpPackageName(),
11444                        UserHandle.USER_SYSTEM);
11445            } catch (RemoteException e) {
11446            }
11447        }
11448    }
11449
11450    @Override
11451    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11452            int installFlags, String installerPackageName, int userId) {
11453        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11454
11455        final int callingUid = Binder.getCallingUid();
11456        enforceCrossUserPermission(callingUid, userId,
11457                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11458
11459        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11460            try {
11461                if (observer != null) {
11462                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11463                }
11464            } catch (RemoteException re) {
11465            }
11466            return;
11467        }
11468
11469        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11470            installFlags |= PackageManager.INSTALL_FROM_ADB;
11471
11472        } else {
11473            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11474            // about installerPackageName.
11475
11476            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11477            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11478        }
11479
11480        UserHandle user;
11481        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11482            user = UserHandle.ALL;
11483        } else {
11484            user = new UserHandle(userId);
11485        }
11486
11487        // Only system components can circumvent runtime permissions when installing.
11488        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11489                && mContext.checkCallingOrSelfPermission(Manifest.permission
11490                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11491            throw new SecurityException("You need the "
11492                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11493                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11494        }
11495
11496        final File originFile = new File(originPath);
11497        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11498
11499        final Message msg = mHandler.obtainMessage(INIT_COPY);
11500        final VerificationInfo verificationInfo = new VerificationInfo(
11501                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11502        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11503                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11504                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11505                null /*certificates*/);
11506        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11507        msg.obj = params;
11508
11509        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11510                System.identityHashCode(msg.obj));
11511        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11512                System.identityHashCode(msg.obj));
11513
11514        mHandler.sendMessage(msg);
11515    }
11516
11517    void installStage(String packageName, File stagedDir, String stagedCid,
11518            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11519            String installerPackageName, int installerUid, UserHandle user,
11520            Certificate[][] certificates) {
11521        if (DEBUG_EPHEMERAL) {
11522            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11523                Slog.d(TAG, "Ephemeral install of " + packageName);
11524            }
11525        }
11526        final VerificationInfo verificationInfo = new VerificationInfo(
11527                sessionParams.originatingUri, sessionParams.referrerUri,
11528                sessionParams.originatingUid, installerUid);
11529
11530        final OriginInfo origin;
11531        if (stagedDir != null) {
11532            origin = OriginInfo.fromStagedFile(stagedDir);
11533        } else {
11534            origin = OriginInfo.fromStagedContainer(stagedCid);
11535        }
11536
11537        final Message msg = mHandler.obtainMessage(INIT_COPY);
11538        final InstallParams params = new InstallParams(origin, null, observer,
11539                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11540                verificationInfo, user, sessionParams.abiOverride,
11541                sessionParams.grantedRuntimePermissions, certificates);
11542        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11543        msg.obj = params;
11544
11545        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11546                System.identityHashCode(msg.obj));
11547        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11548                System.identityHashCode(msg.obj));
11549
11550        mHandler.sendMessage(msg);
11551    }
11552
11553    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11554            int userId) {
11555        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11556        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11557    }
11558
11559    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11560            int appId, int userId) {
11561        Bundle extras = new Bundle(1);
11562        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11563
11564        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11565                packageName, extras, 0, null, null, new int[] {userId});
11566        try {
11567            IActivityManager am = ActivityManagerNative.getDefault();
11568            if (isSystem && am.isUserRunning(userId, 0)) {
11569                // The just-installed/enabled app is bundled on the system, so presumed
11570                // to be able to run automatically without needing an explicit launch.
11571                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11572                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11573                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11574                        .setPackage(packageName);
11575                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11576                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11577            }
11578        } catch (RemoteException e) {
11579            // shouldn't happen
11580            Slog.w(TAG, "Unable to bootstrap installed package", e);
11581        }
11582    }
11583
11584    @Override
11585    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11586            int userId) {
11587        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11588        PackageSetting pkgSetting;
11589        final int uid = Binder.getCallingUid();
11590        enforceCrossUserPermission(uid, userId,
11591                true /* requireFullPermission */, true /* checkShell */,
11592                "setApplicationHiddenSetting for user " + userId);
11593
11594        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11595            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11596            return false;
11597        }
11598
11599        long callingId = Binder.clearCallingIdentity();
11600        try {
11601            boolean sendAdded = false;
11602            boolean sendRemoved = false;
11603            // writer
11604            synchronized (mPackages) {
11605                pkgSetting = mSettings.mPackages.get(packageName);
11606                if (pkgSetting == null) {
11607                    return false;
11608                }
11609                // Do not allow "android" is being disabled
11610                if ("android".equals(packageName)) {
11611                    Slog.w(TAG, "Cannot hide package: android");
11612                    return false;
11613                }
11614                // Only allow protected packages to hide themselves.
11615                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11616                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11617                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11618                    return false;
11619                }
11620
11621                if (pkgSetting.getHidden(userId) != hidden) {
11622                    pkgSetting.setHidden(hidden, userId);
11623                    mSettings.writePackageRestrictionsLPr(userId);
11624                    if (hidden) {
11625                        sendRemoved = true;
11626                    } else {
11627                        sendAdded = true;
11628                    }
11629                }
11630            }
11631            if (sendAdded) {
11632                sendPackageAddedForUser(packageName, pkgSetting, userId);
11633                return true;
11634            }
11635            if (sendRemoved) {
11636                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11637                        "hiding pkg");
11638                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11639                return true;
11640            }
11641        } finally {
11642            Binder.restoreCallingIdentity(callingId);
11643        }
11644        return false;
11645    }
11646
11647    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11648            int userId) {
11649        final PackageRemovedInfo info = new PackageRemovedInfo();
11650        info.removedPackage = packageName;
11651        info.removedUsers = new int[] {userId};
11652        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11653        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11654    }
11655
11656    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11657        if (pkgList.length > 0) {
11658            Bundle extras = new Bundle(1);
11659            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11660
11661            sendPackageBroadcast(
11662                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11663                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11664                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11665                    new int[] {userId});
11666        }
11667    }
11668
11669    /**
11670     * Returns true if application is not found or there was an error. Otherwise it returns
11671     * the hidden state of the package for the given user.
11672     */
11673    @Override
11674    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11675        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11676        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11677                true /* requireFullPermission */, false /* checkShell */,
11678                "getApplicationHidden for user " + userId);
11679        PackageSetting pkgSetting;
11680        long callingId = Binder.clearCallingIdentity();
11681        try {
11682            // writer
11683            synchronized (mPackages) {
11684                pkgSetting = mSettings.mPackages.get(packageName);
11685                if (pkgSetting == null) {
11686                    return true;
11687                }
11688                return pkgSetting.getHidden(userId);
11689            }
11690        } finally {
11691            Binder.restoreCallingIdentity(callingId);
11692        }
11693    }
11694
11695    /**
11696     * @hide
11697     */
11698    @Override
11699    public int installExistingPackageAsUser(String packageName, int userId) {
11700        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11701                null);
11702        PackageSetting pkgSetting;
11703        final int uid = Binder.getCallingUid();
11704        enforceCrossUserPermission(uid, userId,
11705                true /* requireFullPermission */, true /* checkShell */,
11706                "installExistingPackage for user " + userId);
11707        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11708            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11709        }
11710
11711        long callingId = Binder.clearCallingIdentity();
11712        try {
11713            boolean installed = false;
11714
11715            // writer
11716            synchronized (mPackages) {
11717                pkgSetting = mSettings.mPackages.get(packageName);
11718                if (pkgSetting == null) {
11719                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11720                }
11721                if (!pkgSetting.getInstalled(userId)) {
11722                    pkgSetting.setInstalled(true, userId);
11723                    pkgSetting.setHidden(false, userId);
11724                    mSettings.writePackageRestrictionsLPr(userId);
11725                    installed = true;
11726                }
11727            }
11728
11729            if (installed) {
11730                if (pkgSetting.pkg != null) {
11731                    synchronized (mInstallLock) {
11732                        // We don't need to freeze for a brand new install
11733                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11734                    }
11735                }
11736                sendPackageAddedForUser(packageName, pkgSetting, userId);
11737            }
11738        } finally {
11739            Binder.restoreCallingIdentity(callingId);
11740        }
11741
11742        return PackageManager.INSTALL_SUCCEEDED;
11743    }
11744
11745    boolean isUserRestricted(int userId, String restrictionKey) {
11746        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11747        if (restrictions.getBoolean(restrictionKey, false)) {
11748            Log.w(TAG, "User is restricted: " + restrictionKey);
11749            return true;
11750        }
11751        return false;
11752    }
11753
11754    @Override
11755    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11756            int userId) {
11757        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11758        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11759                true /* requireFullPermission */, true /* checkShell */,
11760                "setPackagesSuspended for user " + userId);
11761
11762        if (ArrayUtils.isEmpty(packageNames)) {
11763            return packageNames;
11764        }
11765
11766        // List of package names for whom the suspended state has changed.
11767        List<String> changedPackages = new ArrayList<>(packageNames.length);
11768        // List of package names for whom the suspended state is not set as requested in this
11769        // method.
11770        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11771        long callingId = Binder.clearCallingIdentity();
11772        try {
11773            for (int i = 0; i < packageNames.length; i++) {
11774                String packageName = packageNames[i];
11775                boolean changed = false;
11776                final int appId;
11777                synchronized (mPackages) {
11778                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11779                    if (pkgSetting == null) {
11780                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11781                                + "\". Skipping suspending/un-suspending.");
11782                        unactionedPackages.add(packageName);
11783                        continue;
11784                    }
11785                    appId = pkgSetting.appId;
11786                    if (pkgSetting.getSuspended(userId) != suspended) {
11787                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11788                            unactionedPackages.add(packageName);
11789                            continue;
11790                        }
11791                        pkgSetting.setSuspended(suspended, userId);
11792                        mSettings.writePackageRestrictionsLPr(userId);
11793                        changed = true;
11794                        changedPackages.add(packageName);
11795                    }
11796                }
11797
11798                if (changed && suspended) {
11799                    killApplication(packageName, UserHandle.getUid(userId, appId),
11800                            "suspending package");
11801                }
11802            }
11803        } finally {
11804            Binder.restoreCallingIdentity(callingId);
11805        }
11806
11807        if (!changedPackages.isEmpty()) {
11808            sendPackagesSuspendedForUser(changedPackages.toArray(
11809                    new String[changedPackages.size()]), userId, suspended);
11810        }
11811
11812        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11813    }
11814
11815    @Override
11816    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11817        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11818                true /* requireFullPermission */, false /* checkShell */,
11819                "isPackageSuspendedForUser for user " + userId);
11820        synchronized (mPackages) {
11821            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11822            if (pkgSetting == null) {
11823                throw new IllegalArgumentException("Unknown target package: " + packageName);
11824            }
11825            return pkgSetting.getSuspended(userId);
11826        }
11827    }
11828
11829    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11830        if (isPackageDeviceAdmin(packageName, userId)) {
11831            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11832                    + "\": has an active device admin");
11833            return false;
11834        }
11835
11836        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11837        if (packageName.equals(activeLauncherPackageName)) {
11838            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11839                    + "\": contains the active launcher");
11840            return false;
11841        }
11842
11843        if (packageName.equals(mRequiredInstallerPackage)) {
11844            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11845                    + "\": required for package installation");
11846            return false;
11847        }
11848
11849        if (packageName.equals(mRequiredUninstallerPackage)) {
11850            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11851                    + "\": required for package uninstallation");
11852            return false;
11853        }
11854
11855        if (packageName.equals(mRequiredVerifierPackage)) {
11856            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11857                    + "\": required for package verification");
11858            return false;
11859        }
11860
11861        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11862            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11863                    + "\": is the default dialer");
11864            return false;
11865        }
11866
11867        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11868            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11869                    + "\": protected package");
11870            return false;
11871        }
11872
11873        return true;
11874    }
11875
11876    private String getActiveLauncherPackageName(int userId) {
11877        Intent intent = new Intent(Intent.ACTION_MAIN);
11878        intent.addCategory(Intent.CATEGORY_HOME);
11879        ResolveInfo resolveInfo = resolveIntent(
11880                intent,
11881                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11882                PackageManager.MATCH_DEFAULT_ONLY,
11883                userId);
11884
11885        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11886    }
11887
11888    private String getDefaultDialerPackageName(int userId) {
11889        synchronized (mPackages) {
11890            return mSettings.getDefaultDialerPackageNameLPw(userId);
11891        }
11892    }
11893
11894    @Override
11895    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11896        mContext.enforceCallingOrSelfPermission(
11897                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11898                "Only package verification agents can verify applications");
11899
11900        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11901        final PackageVerificationResponse response = new PackageVerificationResponse(
11902                verificationCode, Binder.getCallingUid());
11903        msg.arg1 = id;
11904        msg.obj = response;
11905        mHandler.sendMessage(msg);
11906    }
11907
11908    @Override
11909    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11910            long millisecondsToDelay) {
11911        mContext.enforceCallingOrSelfPermission(
11912                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11913                "Only package verification agents can extend verification timeouts");
11914
11915        final PackageVerificationState state = mPendingVerification.get(id);
11916        final PackageVerificationResponse response = new PackageVerificationResponse(
11917                verificationCodeAtTimeout, Binder.getCallingUid());
11918
11919        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11920            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11921        }
11922        if (millisecondsToDelay < 0) {
11923            millisecondsToDelay = 0;
11924        }
11925        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11926                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11927            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11928        }
11929
11930        if ((state != null) && !state.timeoutExtended()) {
11931            state.extendTimeout();
11932
11933            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11934            msg.arg1 = id;
11935            msg.obj = response;
11936            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11937        }
11938    }
11939
11940    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11941            int verificationCode, UserHandle user) {
11942        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11943        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11944        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11945        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11946        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11947
11948        mContext.sendBroadcastAsUser(intent, user,
11949                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11950    }
11951
11952    private ComponentName matchComponentForVerifier(String packageName,
11953            List<ResolveInfo> receivers) {
11954        ActivityInfo targetReceiver = null;
11955
11956        final int NR = receivers.size();
11957        for (int i = 0; i < NR; i++) {
11958            final ResolveInfo info = receivers.get(i);
11959            if (info.activityInfo == null) {
11960                continue;
11961            }
11962
11963            if (packageName.equals(info.activityInfo.packageName)) {
11964                targetReceiver = info.activityInfo;
11965                break;
11966            }
11967        }
11968
11969        if (targetReceiver == null) {
11970            return null;
11971        }
11972
11973        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11974    }
11975
11976    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11977            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11978        if (pkgInfo.verifiers.length == 0) {
11979            return null;
11980        }
11981
11982        final int N = pkgInfo.verifiers.length;
11983        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11984        for (int i = 0; i < N; i++) {
11985            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11986
11987            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11988                    receivers);
11989            if (comp == null) {
11990                continue;
11991            }
11992
11993            final int verifierUid = getUidForVerifier(verifierInfo);
11994            if (verifierUid == -1) {
11995                continue;
11996            }
11997
11998            if (DEBUG_VERIFY) {
11999                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12000                        + " with the correct signature");
12001            }
12002            sufficientVerifiers.add(comp);
12003            verificationState.addSufficientVerifier(verifierUid);
12004        }
12005
12006        return sufficientVerifiers;
12007    }
12008
12009    private int getUidForVerifier(VerifierInfo verifierInfo) {
12010        synchronized (mPackages) {
12011            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12012            if (pkg == null) {
12013                return -1;
12014            } else if (pkg.mSignatures.length != 1) {
12015                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12016                        + " has more than one signature; ignoring");
12017                return -1;
12018            }
12019
12020            /*
12021             * If the public key of the package's signature does not match
12022             * our expected public key, then this is a different package and
12023             * we should skip.
12024             */
12025
12026            final byte[] expectedPublicKey;
12027            try {
12028                final Signature verifierSig = pkg.mSignatures[0];
12029                final PublicKey publicKey = verifierSig.getPublicKey();
12030                expectedPublicKey = publicKey.getEncoded();
12031            } catch (CertificateException e) {
12032                return -1;
12033            }
12034
12035            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12036
12037            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12038                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12039                        + " does not have the expected public key; ignoring");
12040                return -1;
12041            }
12042
12043            return pkg.applicationInfo.uid;
12044        }
12045    }
12046
12047    @Override
12048    public void finishPackageInstall(int token, boolean didLaunch) {
12049        enforceSystemOrRoot("Only the system is allowed to finish installs");
12050
12051        if (DEBUG_INSTALL) {
12052            Slog.v(TAG, "BM finishing package install for " + token);
12053        }
12054        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12055
12056        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12057        mHandler.sendMessage(msg);
12058    }
12059
12060    /**
12061     * Get the verification agent timeout.
12062     *
12063     * @return verification timeout in milliseconds
12064     */
12065    private long getVerificationTimeout() {
12066        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12067                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12068                DEFAULT_VERIFICATION_TIMEOUT);
12069    }
12070
12071    /**
12072     * Get the default verification agent response code.
12073     *
12074     * @return default verification response code
12075     */
12076    private int getDefaultVerificationResponse() {
12077        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12078                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12079                DEFAULT_VERIFICATION_RESPONSE);
12080    }
12081
12082    /**
12083     * Check whether or not package verification has been enabled.
12084     *
12085     * @return true if verification should be performed
12086     */
12087    private boolean isVerificationEnabled(int userId, int installFlags) {
12088        if (!DEFAULT_VERIFY_ENABLE) {
12089            return false;
12090        }
12091        // Ephemeral apps don't get the full verification treatment
12092        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12093            if (DEBUG_EPHEMERAL) {
12094                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12095            }
12096            return false;
12097        }
12098
12099        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12100
12101        // Check if installing from ADB
12102        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12103            // Do not run verification in a test harness environment
12104            if (ActivityManager.isRunningInTestHarness()) {
12105                return false;
12106            }
12107            if (ensureVerifyAppsEnabled) {
12108                return true;
12109            }
12110            // Check if the developer does not want package verification for ADB installs
12111            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12112                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12113                return false;
12114            }
12115        }
12116
12117        if (ensureVerifyAppsEnabled) {
12118            return true;
12119        }
12120
12121        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12122                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12123    }
12124
12125    @Override
12126    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12127            throws RemoteException {
12128        mContext.enforceCallingOrSelfPermission(
12129                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12130                "Only intentfilter verification agents can verify applications");
12131
12132        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12133        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12134                Binder.getCallingUid(), verificationCode, failedDomains);
12135        msg.arg1 = id;
12136        msg.obj = response;
12137        mHandler.sendMessage(msg);
12138    }
12139
12140    @Override
12141    public int getIntentVerificationStatus(String packageName, int userId) {
12142        synchronized (mPackages) {
12143            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12144        }
12145    }
12146
12147    @Override
12148    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12149        mContext.enforceCallingOrSelfPermission(
12150                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12151
12152        boolean result = false;
12153        synchronized (mPackages) {
12154            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12155        }
12156        if (result) {
12157            scheduleWritePackageRestrictionsLocked(userId);
12158        }
12159        return result;
12160    }
12161
12162    @Override
12163    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12164            String packageName) {
12165        synchronized (mPackages) {
12166            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12167        }
12168    }
12169
12170    @Override
12171    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12172        if (TextUtils.isEmpty(packageName)) {
12173            return ParceledListSlice.emptyList();
12174        }
12175        synchronized (mPackages) {
12176            PackageParser.Package pkg = mPackages.get(packageName);
12177            if (pkg == null || pkg.activities == null) {
12178                return ParceledListSlice.emptyList();
12179            }
12180            final int count = pkg.activities.size();
12181            ArrayList<IntentFilter> result = new ArrayList<>();
12182            for (int n=0; n<count; n++) {
12183                PackageParser.Activity activity = pkg.activities.get(n);
12184                if (activity.intents != null && activity.intents.size() > 0) {
12185                    result.addAll(activity.intents);
12186                }
12187            }
12188            return new ParceledListSlice<>(result);
12189        }
12190    }
12191
12192    @Override
12193    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12194        mContext.enforceCallingOrSelfPermission(
12195                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12196
12197        synchronized (mPackages) {
12198            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12199            if (packageName != null) {
12200                result |= updateIntentVerificationStatus(packageName,
12201                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12202                        userId);
12203                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12204                        packageName, userId);
12205            }
12206            return result;
12207        }
12208    }
12209
12210    @Override
12211    public String getDefaultBrowserPackageName(int userId) {
12212        synchronized (mPackages) {
12213            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12214        }
12215    }
12216
12217    /**
12218     * Get the "allow unknown sources" setting.
12219     *
12220     * @return the current "allow unknown sources" setting
12221     */
12222    private int getUnknownSourcesSettings() {
12223        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12224                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12225                -1);
12226    }
12227
12228    @Override
12229    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12230        final int uid = Binder.getCallingUid();
12231        // writer
12232        synchronized (mPackages) {
12233            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12234            if (targetPackageSetting == null) {
12235                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12236            }
12237
12238            PackageSetting installerPackageSetting;
12239            if (installerPackageName != null) {
12240                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12241                if (installerPackageSetting == null) {
12242                    throw new IllegalArgumentException("Unknown installer package: "
12243                            + installerPackageName);
12244                }
12245            } else {
12246                installerPackageSetting = null;
12247            }
12248
12249            Signature[] callerSignature;
12250            Object obj = mSettings.getUserIdLPr(uid);
12251            if (obj != null) {
12252                if (obj instanceof SharedUserSetting) {
12253                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12254                } else if (obj instanceof PackageSetting) {
12255                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12256                } else {
12257                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12258                }
12259            } else {
12260                throw new SecurityException("Unknown calling UID: " + uid);
12261            }
12262
12263            // Verify: can't set installerPackageName to a package that is
12264            // not signed with the same cert as the caller.
12265            if (installerPackageSetting != null) {
12266                if (compareSignatures(callerSignature,
12267                        installerPackageSetting.signatures.mSignatures)
12268                        != PackageManager.SIGNATURE_MATCH) {
12269                    throw new SecurityException(
12270                            "Caller does not have same cert as new installer package "
12271                            + installerPackageName);
12272                }
12273            }
12274
12275            // Verify: if target already has an installer package, it must
12276            // be signed with the same cert as the caller.
12277            if (targetPackageSetting.installerPackageName != null) {
12278                PackageSetting setting = mSettings.mPackages.get(
12279                        targetPackageSetting.installerPackageName);
12280                // If the currently set package isn't valid, then it's always
12281                // okay to change it.
12282                if (setting != null) {
12283                    if (compareSignatures(callerSignature,
12284                            setting.signatures.mSignatures)
12285                            != PackageManager.SIGNATURE_MATCH) {
12286                        throw new SecurityException(
12287                                "Caller does not have same cert as old installer package "
12288                                + targetPackageSetting.installerPackageName);
12289                    }
12290                }
12291            }
12292
12293            // Okay!
12294            targetPackageSetting.installerPackageName = installerPackageName;
12295            if (installerPackageName != null) {
12296                mSettings.mInstallerPackages.add(installerPackageName);
12297            }
12298            scheduleWriteSettingsLocked();
12299        }
12300    }
12301
12302    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12303        // Queue up an async operation since the package installation may take a little while.
12304        mHandler.post(new Runnable() {
12305            public void run() {
12306                mHandler.removeCallbacks(this);
12307                 // Result object to be returned
12308                PackageInstalledInfo res = new PackageInstalledInfo();
12309                res.setReturnCode(currentStatus);
12310                res.uid = -1;
12311                res.pkg = null;
12312                res.removedInfo = null;
12313                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12314                    args.doPreInstall(res.returnCode);
12315                    synchronized (mInstallLock) {
12316                        installPackageTracedLI(args, res);
12317                    }
12318                    args.doPostInstall(res.returnCode, res.uid);
12319                }
12320
12321                // A restore should be performed at this point if (a) the install
12322                // succeeded, (b) the operation is not an update, and (c) the new
12323                // package has not opted out of backup participation.
12324                final boolean update = res.removedInfo != null
12325                        && res.removedInfo.removedPackage != null;
12326                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12327                boolean doRestore = !update
12328                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12329
12330                // Set up the post-install work request bookkeeping.  This will be used
12331                // and cleaned up by the post-install event handling regardless of whether
12332                // there's a restore pass performed.  Token values are >= 1.
12333                int token;
12334                if (mNextInstallToken < 0) mNextInstallToken = 1;
12335                token = mNextInstallToken++;
12336
12337                PostInstallData data = new PostInstallData(args, res);
12338                mRunningInstalls.put(token, data);
12339                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12340
12341                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12342                    // Pass responsibility to the Backup Manager.  It will perform a
12343                    // restore if appropriate, then pass responsibility back to the
12344                    // Package Manager to run the post-install observer callbacks
12345                    // and broadcasts.
12346                    IBackupManager bm = IBackupManager.Stub.asInterface(
12347                            ServiceManager.getService(Context.BACKUP_SERVICE));
12348                    if (bm != null) {
12349                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12350                                + " to BM for possible restore");
12351                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12352                        try {
12353                            // TODO: http://b/22388012
12354                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12355                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12356                            } else {
12357                                doRestore = false;
12358                            }
12359                        } catch (RemoteException e) {
12360                            // can't happen; the backup manager is local
12361                        } catch (Exception e) {
12362                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12363                            doRestore = false;
12364                        }
12365                    } else {
12366                        Slog.e(TAG, "Backup Manager not found!");
12367                        doRestore = false;
12368                    }
12369                }
12370
12371                if (!doRestore) {
12372                    // No restore possible, or the Backup Manager was mysteriously not
12373                    // available -- just fire the post-install work request directly.
12374                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12375
12376                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12377
12378                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12379                    mHandler.sendMessage(msg);
12380                }
12381            }
12382        });
12383    }
12384
12385    /**
12386     * Callback from PackageSettings whenever an app is first transitioned out of the
12387     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12388     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12389     * here whether the app is the target of an ongoing install, and only send the
12390     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12391     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12392     * handling.
12393     */
12394    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12395        // Serialize this with the rest of the install-process message chain.  In the
12396        // restore-at-install case, this Runnable will necessarily run before the
12397        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12398        // are coherent.  In the non-restore case, the app has already completed install
12399        // and been launched through some other means, so it is not in a problematic
12400        // state for observers to see the FIRST_LAUNCH signal.
12401        mHandler.post(new Runnable() {
12402            @Override
12403            public void run() {
12404                for (int i = 0; i < mRunningInstalls.size(); i++) {
12405                    final PostInstallData data = mRunningInstalls.valueAt(i);
12406                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12407                        continue;
12408                    }
12409                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12410                        // right package; but is it for the right user?
12411                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12412                            if (userId == data.res.newUsers[uIndex]) {
12413                                if (DEBUG_BACKUP) {
12414                                    Slog.i(TAG, "Package " + pkgName
12415                                            + " being restored so deferring FIRST_LAUNCH");
12416                                }
12417                                return;
12418                            }
12419                        }
12420                    }
12421                }
12422                // didn't find it, so not being restored
12423                if (DEBUG_BACKUP) {
12424                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12425                }
12426                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12427            }
12428        });
12429    }
12430
12431    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12432        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12433                installerPkg, null, userIds);
12434    }
12435
12436    private abstract class HandlerParams {
12437        private static final int MAX_RETRIES = 4;
12438
12439        /**
12440         * Number of times startCopy() has been attempted and had a non-fatal
12441         * error.
12442         */
12443        private int mRetries = 0;
12444
12445        /** User handle for the user requesting the information or installation. */
12446        private final UserHandle mUser;
12447        String traceMethod;
12448        int traceCookie;
12449
12450        HandlerParams(UserHandle user) {
12451            mUser = user;
12452        }
12453
12454        UserHandle getUser() {
12455            return mUser;
12456        }
12457
12458        HandlerParams setTraceMethod(String traceMethod) {
12459            this.traceMethod = traceMethod;
12460            return this;
12461        }
12462
12463        HandlerParams setTraceCookie(int traceCookie) {
12464            this.traceCookie = traceCookie;
12465            return this;
12466        }
12467
12468        final boolean startCopy() {
12469            boolean res;
12470            try {
12471                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12472
12473                if (++mRetries > MAX_RETRIES) {
12474                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12475                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12476                    handleServiceError();
12477                    return false;
12478                } else {
12479                    handleStartCopy();
12480                    res = true;
12481                }
12482            } catch (RemoteException e) {
12483                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12484                mHandler.sendEmptyMessage(MCS_RECONNECT);
12485                res = false;
12486            }
12487            handleReturnCode();
12488            return res;
12489        }
12490
12491        final void serviceError() {
12492            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12493            handleServiceError();
12494            handleReturnCode();
12495        }
12496
12497        abstract void handleStartCopy() throws RemoteException;
12498        abstract void handleServiceError();
12499        abstract void handleReturnCode();
12500    }
12501
12502    class MeasureParams extends HandlerParams {
12503        private final PackageStats mStats;
12504        private boolean mSuccess;
12505
12506        private final IPackageStatsObserver mObserver;
12507
12508        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12509            super(new UserHandle(stats.userHandle));
12510            mObserver = observer;
12511            mStats = stats;
12512        }
12513
12514        @Override
12515        public String toString() {
12516            return "MeasureParams{"
12517                + Integer.toHexString(System.identityHashCode(this))
12518                + " " + mStats.packageName + "}";
12519        }
12520
12521        @Override
12522        void handleStartCopy() throws RemoteException {
12523            synchronized (mInstallLock) {
12524                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12525            }
12526
12527            if (mSuccess) {
12528                boolean mounted = false;
12529                try {
12530                    final String status = Environment.getExternalStorageState();
12531                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12532                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12533                } catch (Exception e) {
12534                }
12535
12536                if (mounted) {
12537                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12538
12539                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12540                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12541
12542                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12543                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12544
12545                    // Always subtract cache size, since it's a subdirectory
12546                    mStats.externalDataSize -= mStats.externalCacheSize;
12547
12548                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12549                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12550
12551                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12552                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12553                }
12554            }
12555        }
12556
12557        @Override
12558        void handleReturnCode() {
12559            if (mObserver != null) {
12560                try {
12561                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12562                } catch (RemoteException e) {
12563                    Slog.i(TAG, "Observer no longer exists.");
12564                }
12565            }
12566        }
12567
12568        @Override
12569        void handleServiceError() {
12570            Slog.e(TAG, "Could not measure application " + mStats.packageName
12571                            + " external storage");
12572        }
12573    }
12574
12575    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12576            throws RemoteException {
12577        long result = 0;
12578        for (File path : paths) {
12579            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12580        }
12581        return result;
12582    }
12583
12584    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12585        for (File path : paths) {
12586            try {
12587                mcs.clearDirectory(path.getAbsolutePath());
12588            } catch (RemoteException e) {
12589            }
12590        }
12591    }
12592
12593    static class OriginInfo {
12594        /**
12595         * Location where install is coming from, before it has been
12596         * copied/renamed into place. This could be a single monolithic APK
12597         * file, or a cluster directory. This location may be untrusted.
12598         */
12599        final File file;
12600        final String cid;
12601
12602        /**
12603         * Flag indicating that {@link #file} or {@link #cid} has already been
12604         * staged, meaning downstream users don't need to defensively copy the
12605         * contents.
12606         */
12607        final boolean staged;
12608
12609        /**
12610         * Flag indicating that {@link #file} or {@link #cid} is an already
12611         * installed app that is being moved.
12612         */
12613        final boolean existing;
12614
12615        final String resolvedPath;
12616        final File resolvedFile;
12617
12618        static OriginInfo fromNothing() {
12619            return new OriginInfo(null, null, false, false);
12620        }
12621
12622        static OriginInfo fromUntrustedFile(File file) {
12623            return new OriginInfo(file, null, false, false);
12624        }
12625
12626        static OriginInfo fromExistingFile(File file) {
12627            return new OriginInfo(file, null, false, true);
12628        }
12629
12630        static OriginInfo fromStagedFile(File file) {
12631            return new OriginInfo(file, null, true, false);
12632        }
12633
12634        static OriginInfo fromStagedContainer(String cid) {
12635            return new OriginInfo(null, cid, true, false);
12636        }
12637
12638        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12639            this.file = file;
12640            this.cid = cid;
12641            this.staged = staged;
12642            this.existing = existing;
12643
12644            if (cid != null) {
12645                resolvedPath = PackageHelper.getSdDir(cid);
12646                resolvedFile = new File(resolvedPath);
12647            } else if (file != null) {
12648                resolvedPath = file.getAbsolutePath();
12649                resolvedFile = file;
12650            } else {
12651                resolvedPath = null;
12652                resolvedFile = null;
12653            }
12654        }
12655    }
12656
12657    static class MoveInfo {
12658        final int moveId;
12659        final String fromUuid;
12660        final String toUuid;
12661        final String packageName;
12662        final String dataAppName;
12663        final int appId;
12664        final String seinfo;
12665        final int targetSdkVersion;
12666
12667        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12668                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12669            this.moveId = moveId;
12670            this.fromUuid = fromUuid;
12671            this.toUuid = toUuid;
12672            this.packageName = packageName;
12673            this.dataAppName = dataAppName;
12674            this.appId = appId;
12675            this.seinfo = seinfo;
12676            this.targetSdkVersion = targetSdkVersion;
12677        }
12678    }
12679
12680    static class VerificationInfo {
12681        /** A constant used to indicate that a uid value is not present. */
12682        public static final int NO_UID = -1;
12683
12684        /** URI referencing where the package was downloaded from. */
12685        final Uri originatingUri;
12686
12687        /** HTTP referrer URI associated with the originatingURI. */
12688        final Uri referrer;
12689
12690        /** UID of the application that the install request originated from. */
12691        final int originatingUid;
12692
12693        /** UID of application requesting the install */
12694        final int installerUid;
12695
12696        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12697            this.originatingUri = originatingUri;
12698            this.referrer = referrer;
12699            this.originatingUid = originatingUid;
12700            this.installerUid = installerUid;
12701        }
12702    }
12703
12704    class InstallParams extends HandlerParams {
12705        final OriginInfo origin;
12706        final MoveInfo move;
12707        final IPackageInstallObserver2 observer;
12708        int installFlags;
12709        final String installerPackageName;
12710        final String volumeUuid;
12711        private InstallArgs mArgs;
12712        private int mRet;
12713        final String packageAbiOverride;
12714        final String[] grantedRuntimePermissions;
12715        final VerificationInfo verificationInfo;
12716        final Certificate[][] certificates;
12717
12718        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12719                int installFlags, String installerPackageName, String volumeUuid,
12720                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12721                String[] grantedPermissions, Certificate[][] certificates) {
12722            super(user);
12723            this.origin = origin;
12724            this.move = move;
12725            this.observer = observer;
12726            this.installFlags = installFlags;
12727            this.installerPackageName = installerPackageName;
12728            this.volumeUuid = volumeUuid;
12729            this.verificationInfo = verificationInfo;
12730            this.packageAbiOverride = packageAbiOverride;
12731            this.grantedRuntimePermissions = grantedPermissions;
12732            this.certificates = certificates;
12733        }
12734
12735        @Override
12736        public String toString() {
12737            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12738                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12739        }
12740
12741        private int installLocationPolicy(PackageInfoLite pkgLite) {
12742            String packageName = pkgLite.packageName;
12743            int installLocation = pkgLite.installLocation;
12744            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12745            // reader
12746            synchronized (mPackages) {
12747                // Currently installed package which the new package is attempting to replace or
12748                // null if no such package is installed.
12749                PackageParser.Package installedPkg = mPackages.get(packageName);
12750                // Package which currently owns the data which the new package will own if installed.
12751                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12752                // will be null whereas dataOwnerPkg will contain information about the package
12753                // which was uninstalled while keeping its data.
12754                PackageParser.Package dataOwnerPkg = installedPkg;
12755                if (dataOwnerPkg  == null) {
12756                    PackageSetting ps = mSettings.mPackages.get(packageName);
12757                    if (ps != null) {
12758                        dataOwnerPkg = ps.pkg;
12759                    }
12760                }
12761
12762                if (dataOwnerPkg != null) {
12763                    // If installed, the package will get access to data left on the device by its
12764                    // predecessor. As a security measure, this is permited only if this is not a
12765                    // version downgrade or if the predecessor package is marked as debuggable and
12766                    // a downgrade is explicitly requested.
12767                    //
12768                    // On debuggable platform builds, downgrades are permitted even for
12769                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12770                    // not offer security guarantees and thus it's OK to disable some security
12771                    // mechanisms to make debugging/testing easier on those builds. However, even on
12772                    // debuggable builds downgrades of packages are permitted only if requested via
12773                    // installFlags. This is because we aim to keep the behavior of debuggable
12774                    // platform builds as close as possible to the behavior of non-debuggable
12775                    // platform builds.
12776                    final boolean downgradeRequested =
12777                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12778                    final boolean packageDebuggable =
12779                                (dataOwnerPkg.applicationInfo.flags
12780                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12781                    final boolean downgradePermitted =
12782                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12783                    if (!downgradePermitted) {
12784                        try {
12785                            checkDowngrade(dataOwnerPkg, pkgLite);
12786                        } catch (PackageManagerException e) {
12787                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12788                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12789                        }
12790                    }
12791                }
12792
12793                if (installedPkg != null) {
12794                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12795                        // Check for updated system application.
12796                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12797                            if (onSd) {
12798                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12799                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12800                            }
12801                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12802                        } else {
12803                            if (onSd) {
12804                                // Install flag overrides everything.
12805                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12806                            }
12807                            // If current upgrade specifies particular preference
12808                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12809                                // Application explicitly specified internal.
12810                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12811                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12812                                // App explictly prefers external. Let policy decide
12813                            } else {
12814                                // Prefer previous location
12815                                if (isExternal(installedPkg)) {
12816                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12817                                }
12818                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12819                            }
12820                        }
12821                    } else {
12822                        // Invalid install. Return error code
12823                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12824                    }
12825                }
12826            }
12827            // All the special cases have been taken care of.
12828            // Return result based on recommended install location.
12829            if (onSd) {
12830                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12831            }
12832            return pkgLite.recommendedInstallLocation;
12833        }
12834
12835        /*
12836         * Invoke remote method to get package information and install
12837         * location values. Override install location based on default
12838         * policy if needed and then create install arguments based
12839         * on the install location.
12840         */
12841        public void handleStartCopy() throws RemoteException {
12842            int ret = PackageManager.INSTALL_SUCCEEDED;
12843
12844            // If we're already staged, we've firmly committed to an install location
12845            if (origin.staged) {
12846                if (origin.file != null) {
12847                    installFlags |= PackageManager.INSTALL_INTERNAL;
12848                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12849                } else if (origin.cid != null) {
12850                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12851                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12852                } else {
12853                    throw new IllegalStateException("Invalid stage location");
12854                }
12855            }
12856
12857            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12858            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12859            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12860            PackageInfoLite pkgLite = null;
12861
12862            if (onInt && onSd) {
12863                // Check if both bits are set.
12864                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12865                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12866            } else if (onSd && ephemeral) {
12867                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12868                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12869            } else {
12870                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12871                        packageAbiOverride);
12872
12873                if (DEBUG_EPHEMERAL && ephemeral) {
12874                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12875                }
12876
12877                /*
12878                 * If we have too little free space, try to free cache
12879                 * before giving up.
12880                 */
12881                if (!origin.staged && pkgLite.recommendedInstallLocation
12882                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12883                    // TODO: focus freeing disk space on the target device
12884                    final StorageManager storage = StorageManager.from(mContext);
12885                    final long lowThreshold = storage.getStorageLowBytes(
12886                            Environment.getDataDirectory());
12887
12888                    final long sizeBytes = mContainerService.calculateInstalledSize(
12889                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12890
12891                    try {
12892                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12893                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12894                                installFlags, packageAbiOverride);
12895                    } catch (InstallerException e) {
12896                        Slog.w(TAG, "Failed to free cache", e);
12897                    }
12898
12899                    /*
12900                     * The cache free must have deleted the file we
12901                     * downloaded to install.
12902                     *
12903                     * TODO: fix the "freeCache" call to not delete
12904                     *       the file we care about.
12905                     */
12906                    if (pkgLite.recommendedInstallLocation
12907                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12908                        pkgLite.recommendedInstallLocation
12909                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12910                    }
12911                }
12912            }
12913
12914            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12915                int loc = pkgLite.recommendedInstallLocation;
12916                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12917                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12918                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12919                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12920                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12921                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12922                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12923                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12924                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12925                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12926                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12927                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12928                } else {
12929                    // Override with defaults if needed.
12930                    loc = installLocationPolicy(pkgLite);
12931                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12932                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12933                    } else if (!onSd && !onInt) {
12934                        // Override install location with flags
12935                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12936                            // Set the flag to install on external media.
12937                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12938                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12939                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12940                            if (DEBUG_EPHEMERAL) {
12941                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12942                            }
12943                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12944                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12945                                    |PackageManager.INSTALL_INTERNAL);
12946                        } else {
12947                            // Make sure the flag for installing on external
12948                            // media is unset
12949                            installFlags |= PackageManager.INSTALL_INTERNAL;
12950                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12951                        }
12952                    }
12953                }
12954            }
12955
12956            final InstallArgs args = createInstallArgs(this);
12957            mArgs = args;
12958
12959            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12960                // TODO: http://b/22976637
12961                // Apps installed for "all" users use the device owner to verify the app
12962                UserHandle verifierUser = getUser();
12963                if (verifierUser == UserHandle.ALL) {
12964                    verifierUser = UserHandle.SYSTEM;
12965                }
12966
12967                /*
12968                 * Determine if we have any installed package verifiers. If we
12969                 * do, then we'll defer to them to verify the packages.
12970                 */
12971                final int requiredUid = mRequiredVerifierPackage == null ? -1
12972                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12973                                verifierUser.getIdentifier());
12974                if (!origin.existing && requiredUid != -1
12975                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12976                    final Intent verification = new Intent(
12977                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12978                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12979                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12980                            PACKAGE_MIME_TYPE);
12981                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12982
12983                    // Query all live verifiers based on current user state
12984                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12985                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12986
12987                    if (DEBUG_VERIFY) {
12988                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12989                                + verification.toString() + " with " + pkgLite.verifiers.length
12990                                + " optional verifiers");
12991                    }
12992
12993                    final int verificationId = mPendingVerificationToken++;
12994
12995                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12996
12997                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12998                            installerPackageName);
12999
13000                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13001                            installFlags);
13002
13003                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13004                            pkgLite.packageName);
13005
13006                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13007                            pkgLite.versionCode);
13008
13009                    if (verificationInfo != null) {
13010                        if (verificationInfo.originatingUri != null) {
13011                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13012                                    verificationInfo.originatingUri);
13013                        }
13014                        if (verificationInfo.referrer != null) {
13015                            verification.putExtra(Intent.EXTRA_REFERRER,
13016                                    verificationInfo.referrer);
13017                        }
13018                        if (verificationInfo.originatingUid >= 0) {
13019                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13020                                    verificationInfo.originatingUid);
13021                        }
13022                        if (verificationInfo.installerUid >= 0) {
13023                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13024                                    verificationInfo.installerUid);
13025                        }
13026                    }
13027
13028                    final PackageVerificationState verificationState = new PackageVerificationState(
13029                            requiredUid, args);
13030
13031                    mPendingVerification.append(verificationId, verificationState);
13032
13033                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13034                            receivers, verificationState);
13035
13036                    /*
13037                     * If any sufficient verifiers were listed in the package
13038                     * manifest, attempt to ask them.
13039                     */
13040                    if (sufficientVerifiers != null) {
13041                        final int N = sufficientVerifiers.size();
13042                        if (N == 0) {
13043                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13044                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13045                        } else {
13046                            for (int i = 0; i < N; i++) {
13047                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13048
13049                                final Intent sufficientIntent = new Intent(verification);
13050                                sufficientIntent.setComponent(verifierComponent);
13051                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13052                            }
13053                        }
13054                    }
13055
13056                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13057                            mRequiredVerifierPackage, receivers);
13058                    if (ret == PackageManager.INSTALL_SUCCEEDED
13059                            && mRequiredVerifierPackage != null) {
13060                        Trace.asyncTraceBegin(
13061                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13062                        /*
13063                         * Send the intent to the required verification agent,
13064                         * but only start the verification timeout after the
13065                         * target BroadcastReceivers have run.
13066                         */
13067                        verification.setComponent(requiredVerifierComponent);
13068                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13069                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13070                                new BroadcastReceiver() {
13071                                    @Override
13072                                    public void onReceive(Context context, Intent intent) {
13073                                        final Message msg = mHandler
13074                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13075                                        msg.arg1 = verificationId;
13076                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13077                                    }
13078                                }, null, 0, null, null);
13079
13080                        /*
13081                         * We don't want the copy to proceed until verification
13082                         * succeeds, so null out this field.
13083                         */
13084                        mArgs = null;
13085                    }
13086                } else {
13087                    /*
13088                     * No package verification is enabled, so immediately start
13089                     * the remote call to initiate copy using temporary file.
13090                     */
13091                    ret = args.copyApk(mContainerService, true);
13092                }
13093            }
13094
13095            mRet = ret;
13096        }
13097
13098        @Override
13099        void handleReturnCode() {
13100            // If mArgs is null, then MCS couldn't be reached. When it
13101            // reconnects, it will try again to install. At that point, this
13102            // will succeed.
13103            if (mArgs != null) {
13104                processPendingInstall(mArgs, mRet);
13105            }
13106        }
13107
13108        @Override
13109        void handleServiceError() {
13110            mArgs = createInstallArgs(this);
13111            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13112        }
13113
13114        public boolean isForwardLocked() {
13115            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13116        }
13117    }
13118
13119    /**
13120     * Used during creation of InstallArgs
13121     *
13122     * @param installFlags package installation flags
13123     * @return true if should be installed on external storage
13124     */
13125    private static boolean installOnExternalAsec(int installFlags) {
13126        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13127            return false;
13128        }
13129        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13130            return true;
13131        }
13132        return false;
13133    }
13134
13135    /**
13136     * Used during creation of InstallArgs
13137     *
13138     * @param installFlags package installation flags
13139     * @return true if should be installed as forward locked
13140     */
13141    private static boolean installForwardLocked(int installFlags) {
13142        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13143    }
13144
13145    private InstallArgs createInstallArgs(InstallParams params) {
13146        if (params.move != null) {
13147            return new MoveInstallArgs(params);
13148        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13149            return new AsecInstallArgs(params);
13150        } else {
13151            return new FileInstallArgs(params);
13152        }
13153    }
13154
13155    /**
13156     * Create args that describe an existing installed package. Typically used
13157     * when cleaning up old installs, or used as a move source.
13158     */
13159    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13160            String resourcePath, String[] instructionSets) {
13161        final boolean isInAsec;
13162        if (installOnExternalAsec(installFlags)) {
13163            /* Apps on SD card are always in ASEC containers. */
13164            isInAsec = true;
13165        } else if (installForwardLocked(installFlags)
13166                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13167            /*
13168             * Forward-locked apps are only in ASEC containers if they're the
13169             * new style
13170             */
13171            isInAsec = true;
13172        } else {
13173            isInAsec = false;
13174        }
13175
13176        if (isInAsec) {
13177            return new AsecInstallArgs(codePath, instructionSets,
13178                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13179        } else {
13180            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13181        }
13182    }
13183
13184    static abstract class InstallArgs {
13185        /** @see InstallParams#origin */
13186        final OriginInfo origin;
13187        /** @see InstallParams#move */
13188        final MoveInfo move;
13189
13190        final IPackageInstallObserver2 observer;
13191        // Always refers to PackageManager flags only
13192        final int installFlags;
13193        final String installerPackageName;
13194        final String volumeUuid;
13195        final UserHandle user;
13196        final String abiOverride;
13197        final String[] installGrantPermissions;
13198        /** If non-null, drop an async trace when the install completes */
13199        final String traceMethod;
13200        final int traceCookie;
13201        final Certificate[][] certificates;
13202
13203        // The list of instruction sets supported by this app. This is currently
13204        // only used during the rmdex() phase to clean up resources. We can get rid of this
13205        // if we move dex files under the common app path.
13206        /* nullable */ String[] instructionSets;
13207
13208        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13209                int installFlags, String installerPackageName, String volumeUuid,
13210                UserHandle user, String[] instructionSets,
13211                String abiOverride, String[] installGrantPermissions,
13212                String traceMethod, int traceCookie, Certificate[][] certificates) {
13213            this.origin = origin;
13214            this.move = move;
13215            this.installFlags = installFlags;
13216            this.observer = observer;
13217            this.installerPackageName = installerPackageName;
13218            this.volumeUuid = volumeUuid;
13219            this.user = user;
13220            this.instructionSets = instructionSets;
13221            this.abiOverride = abiOverride;
13222            this.installGrantPermissions = installGrantPermissions;
13223            this.traceMethod = traceMethod;
13224            this.traceCookie = traceCookie;
13225            this.certificates = certificates;
13226        }
13227
13228        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13229        abstract int doPreInstall(int status);
13230
13231        /**
13232         * Rename package into final resting place. All paths on the given
13233         * scanned package should be updated to reflect the rename.
13234         */
13235        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13236        abstract int doPostInstall(int status, int uid);
13237
13238        /** @see PackageSettingBase#codePathString */
13239        abstract String getCodePath();
13240        /** @see PackageSettingBase#resourcePathString */
13241        abstract String getResourcePath();
13242
13243        // Need installer lock especially for dex file removal.
13244        abstract void cleanUpResourcesLI();
13245        abstract boolean doPostDeleteLI(boolean delete);
13246
13247        /**
13248         * Called before the source arguments are copied. This is used mostly
13249         * for MoveParams when it needs to read the source file to put it in the
13250         * destination.
13251         */
13252        int doPreCopy() {
13253            return PackageManager.INSTALL_SUCCEEDED;
13254        }
13255
13256        /**
13257         * Called after the source arguments are copied. This is used mostly for
13258         * MoveParams when it needs to read the source file to put it in the
13259         * destination.
13260         */
13261        int doPostCopy(int uid) {
13262            return PackageManager.INSTALL_SUCCEEDED;
13263        }
13264
13265        protected boolean isFwdLocked() {
13266            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13267        }
13268
13269        protected boolean isExternalAsec() {
13270            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13271        }
13272
13273        protected boolean isEphemeral() {
13274            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13275        }
13276
13277        UserHandle getUser() {
13278            return user;
13279        }
13280    }
13281
13282    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13283        if (!allCodePaths.isEmpty()) {
13284            if (instructionSets == null) {
13285                throw new IllegalStateException("instructionSet == null");
13286            }
13287            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13288            for (String codePath : allCodePaths) {
13289                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13290                    try {
13291                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13292                    } catch (InstallerException ignored) {
13293                    }
13294                }
13295            }
13296        }
13297    }
13298
13299    /**
13300     * Logic to handle installation of non-ASEC applications, including copying
13301     * and renaming logic.
13302     */
13303    class FileInstallArgs extends InstallArgs {
13304        private File codeFile;
13305        private File resourceFile;
13306
13307        // Example topology:
13308        // /data/app/com.example/base.apk
13309        // /data/app/com.example/split_foo.apk
13310        // /data/app/com.example/lib/arm/libfoo.so
13311        // /data/app/com.example/lib/arm64/libfoo.so
13312        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13313
13314        /** New install */
13315        FileInstallArgs(InstallParams params) {
13316            super(params.origin, params.move, params.observer, params.installFlags,
13317                    params.installerPackageName, params.volumeUuid,
13318                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13319                    params.grantedRuntimePermissions,
13320                    params.traceMethod, params.traceCookie, params.certificates);
13321            if (isFwdLocked()) {
13322                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13323            }
13324        }
13325
13326        /** Existing install */
13327        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13328            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13329                    null, null, null, 0, null /*certificates*/);
13330            this.codeFile = (codePath != null) ? new File(codePath) : null;
13331            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13332        }
13333
13334        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13335            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13336            try {
13337                return doCopyApk(imcs, temp);
13338            } finally {
13339                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13340            }
13341        }
13342
13343        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13344            if (origin.staged) {
13345                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13346                codeFile = origin.file;
13347                resourceFile = origin.file;
13348                return PackageManager.INSTALL_SUCCEEDED;
13349            }
13350
13351            try {
13352                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13353                final File tempDir =
13354                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13355                codeFile = tempDir;
13356                resourceFile = tempDir;
13357            } catch (IOException e) {
13358                Slog.w(TAG, "Failed to create copy file: " + e);
13359                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13360            }
13361
13362            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13363                @Override
13364                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13365                    if (!FileUtils.isValidExtFilename(name)) {
13366                        throw new IllegalArgumentException("Invalid filename: " + name);
13367                    }
13368                    try {
13369                        final File file = new File(codeFile, name);
13370                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13371                                O_RDWR | O_CREAT, 0644);
13372                        Os.chmod(file.getAbsolutePath(), 0644);
13373                        return new ParcelFileDescriptor(fd);
13374                    } catch (ErrnoException e) {
13375                        throw new RemoteException("Failed to open: " + e.getMessage());
13376                    }
13377                }
13378            };
13379
13380            int ret = PackageManager.INSTALL_SUCCEEDED;
13381            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13382            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13383                Slog.e(TAG, "Failed to copy package");
13384                return ret;
13385            }
13386
13387            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13388            NativeLibraryHelper.Handle handle = null;
13389            try {
13390                handle = NativeLibraryHelper.Handle.create(codeFile);
13391                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13392                        abiOverride);
13393            } catch (IOException e) {
13394                Slog.e(TAG, "Copying native libraries failed", e);
13395                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13396            } finally {
13397                IoUtils.closeQuietly(handle);
13398            }
13399
13400            return ret;
13401        }
13402
13403        int doPreInstall(int status) {
13404            if (status != PackageManager.INSTALL_SUCCEEDED) {
13405                cleanUp();
13406            }
13407            return status;
13408        }
13409
13410        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13411            if (status != PackageManager.INSTALL_SUCCEEDED) {
13412                cleanUp();
13413                return false;
13414            }
13415
13416            final File targetDir = codeFile.getParentFile();
13417            final File beforeCodeFile = codeFile;
13418            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13419
13420            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13421            try {
13422                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13423            } catch (ErrnoException e) {
13424                Slog.w(TAG, "Failed to rename", e);
13425                return false;
13426            }
13427
13428            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13429                Slog.w(TAG, "Failed to restorecon");
13430                return false;
13431            }
13432
13433            // Reflect the rename internally
13434            codeFile = afterCodeFile;
13435            resourceFile = afterCodeFile;
13436
13437            // Reflect the rename in scanned details
13438            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13439            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13440                    afterCodeFile, pkg.baseCodePath));
13441            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13442                    afterCodeFile, pkg.splitCodePaths));
13443
13444            // Reflect the rename in app info
13445            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13446            pkg.setApplicationInfoCodePath(pkg.codePath);
13447            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13448            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13449            pkg.setApplicationInfoResourcePath(pkg.codePath);
13450            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13451            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13452
13453            return true;
13454        }
13455
13456        int doPostInstall(int status, int uid) {
13457            if (status != PackageManager.INSTALL_SUCCEEDED) {
13458                cleanUp();
13459            }
13460            return status;
13461        }
13462
13463        @Override
13464        String getCodePath() {
13465            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13466        }
13467
13468        @Override
13469        String getResourcePath() {
13470            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13471        }
13472
13473        private boolean cleanUp() {
13474            if (codeFile == null || !codeFile.exists()) {
13475                return false;
13476            }
13477
13478            removeCodePathLI(codeFile);
13479
13480            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13481                resourceFile.delete();
13482            }
13483
13484            return true;
13485        }
13486
13487        void cleanUpResourcesLI() {
13488            // Try enumerating all code paths before deleting
13489            List<String> allCodePaths = Collections.EMPTY_LIST;
13490            if (codeFile != null && codeFile.exists()) {
13491                try {
13492                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13493                    allCodePaths = pkg.getAllCodePaths();
13494                } catch (PackageParserException e) {
13495                    // Ignored; we tried our best
13496                }
13497            }
13498
13499            cleanUp();
13500            removeDexFiles(allCodePaths, instructionSets);
13501        }
13502
13503        boolean doPostDeleteLI(boolean delete) {
13504            // XXX err, shouldn't we respect the delete flag?
13505            cleanUpResourcesLI();
13506            return true;
13507        }
13508    }
13509
13510    private boolean isAsecExternal(String cid) {
13511        final String asecPath = PackageHelper.getSdFilesystem(cid);
13512        return !asecPath.startsWith(mAsecInternalPath);
13513    }
13514
13515    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13516            PackageManagerException {
13517        if (copyRet < 0) {
13518            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13519                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13520                throw new PackageManagerException(copyRet, message);
13521            }
13522        }
13523    }
13524
13525    /**
13526     * Extract the MountService "container ID" from the full code path of an
13527     * .apk.
13528     */
13529    static String cidFromCodePath(String fullCodePath) {
13530        int eidx = fullCodePath.lastIndexOf("/");
13531        String subStr1 = fullCodePath.substring(0, eidx);
13532        int sidx = subStr1.lastIndexOf("/");
13533        return subStr1.substring(sidx+1, eidx);
13534    }
13535
13536    /**
13537     * Logic to handle installation of ASEC applications, including copying and
13538     * renaming logic.
13539     */
13540    class AsecInstallArgs extends InstallArgs {
13541        static final String RES_FILE_NAME = "pkg.apk";
13542        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13543
13544        String cid;
13545        String packagePath;
13546        String resourcePath;
13547
13548        /** New install */
13549        AsecInstallArgs(InstallParams params) {
13550            super(params.origin, params.move, params.observer, params.installFlags,
13551                    params.installerPackageName, params.volumeUuid,
13552                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13553                    params.grantedRuntimePermissions,
13554                    params.traceMethod, params.traceCookie, params.certificates);
13555        }
13556
13557        /** Existing install */
13558        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13559                        boolean isExternal, boolean isForwardLocked) {
13560            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13561              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13562                    instructionSets, null, null, null, 0, null /*certificates*/);
13563            // Hackily pretend we're still looking at a full code path
13564            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13565                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13566            }
13567
13568            // Extract cid from fullCodePath
13569            int eidx = fullCodePath.lastIndexOf("/");
13570            String subStr1 = fullCodePath.substring(0, eidx);
13571            int sidx = subStr1.lastIndexOf("/");
13572            cid = subStr1.substring(sidx+1, eidx);
13573            setMountPath(subStr1);
13574        }
13575
13576        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13577            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13578              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13579                    instructionSets, null, null, null, 0, null /*certificates*/);
13580            this.cid = cid;
13581            setMountPath(PackageHelper.getSdDir(cid));
13582        }
13583
13584        void createCopyFile() {
13585            cid = mInstallerService.allocateExternalStageCidLegacy();
13586        }
13587
13588        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13589            if (origin.staged && origin.cid != null) {
13590                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13591                cid = origin.cid;
13592                setMountPath(PackageHelper.getSdDir(cid));
13593                return PackageManager.INSTALL_SUCCEEDED;
13594            }
13595
13596            if (temp) {
13597                createCopyFile();
13598            } else {
13599                /*
13600                 * Pre-emptively destroy the container since it's destroyed if
13601                 * copying fails due to it existing anyway.
13602                 */
13603                PackageHelper.destroySdDir(cid);
13604            }
13605
13606            final String newMountPath = imcs.copyPackageToContainer(
13607                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13608                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13609
13610            if (newMountPath != null) {
13611                setMountPath(newMountPath);
13612                return PackageManager.INSTALL_SUCCEEDED;
13613            } else {
13614                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13615            }
13616        }
13617
13618        @Override
13619        String getCodePath() {
13620            return packagePath;
13621        }
13622
13623        @Override
13624        String getResourcePath() {
13625            return resourcePath;
13626        }
13627
13628        int doPreInstall(int status) {
13629            if (status != PackageManager.INSTALL_SUCCEEDED) {
13630                // Destroy container
13631                PackageHelper.destroySdDir(cid);
13632            } else {
13633                boolean mounted = PackageHelper.isContainerMounted(cid);
13634                if (!mounted) {
13635                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13636                            Process.SYSTEM_UID);
13637                    if (newMountPath != null) {
13638                        setMountPath(newMountPath);
13639                    } else {
13640                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13641                    }
13642                }
13643            }
13644            return status;
13645        }
13646
13647        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13648            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13649            String newMountPath = null;
13650            if (PackageHelper.isContainerMounted(cid)) {
13651                // Unmount the container
13652                if (!PackageHelper.unMountSdDir(cid)) {
13653                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13654                    return false;
13655                }
13656            }
13657            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13658                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13659                        " which might be stale. Will try to clean up.");
13660                // Clean up the stale container and proceed to recreate.
13661                if (!PackageHelper.destroySdDir(newCacheId)) {
13662                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13663                    return false;
13664                }
13665                // Successfully cleaned up stale container. Try to rename again.
13666                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13667                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13668                            + " inspite of cleaning it up.");
13669                    return false;
13670                }
13671            }
13672            if (!PackageHelper.isContainerMounted(newCacheId)) {
13673                Slog.w(TAG, "Mounting container " + newCacheId);
13674                newMountPath = PackageHelper.mountSdDir(newCacheId,
13675                        getEncryptKey(), Process.SYSTEM_UID);
13676            } else {
13677                newMountPath = PackageHelper.getSdDir(newCacheId);
13678            }
13679            if (newMountPath == null) {
13680                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13681                return false;
13682            }
13683            Log.i(TAG, "Succesfully renamed " + cid +
13684                    " to " + newCacheId +
13685                    " at new path: " + newMountPath);
13686            cid = newCacheId;
13687
13688            final File beforeCodeFile = new File(packagePath);
13689            setMountPath(newMountPath);
13690            final File afterCodeFile = new File(packagePath);
13691
13692            // Reflect the rename in scanned details
13693            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13694            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13695                    afterCodeFile, pkg.baseCodePath));
13696            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13697                    afterCodeFile, pkg.splitCodePaths));
13698
13699            // Reflect the rename in app info
13700            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13701            pkg.setApplicationInfoCodePath(pkg.codePath);
13702            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13703            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13704            pkg.setApplicationInfoResourcePath(pkg.codePath);
13705            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13706            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13707
13708            return true;
13709        }
13710
13711        private void setMountPath(String mountPath) {
13712            final File mountFile = new File(mountPath);
13713
13714            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13715            if (monolithicFile.exists()) {
13716                packagePath = monolithicFile.getAbsolutePath();
13717                if (isFwdLocked()) {
13718                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13719                } else {
13720                    resourcePath = packagePath;
13721                }
13722            } else {
13723                packagePath = mountFile.getAbsolutePath();
13724                resourcePath = packagePath;
13725            }
13726        }
13727
13728        int doPostInstall(int status, int uid) {
13729            if (status != PackageManager.INSTALL_SUCCEEDED) {
13730                cleanUp();
13731            } else {
13732                final int groupOwner;
13733                final String protectedFile;
13734                if (isFwdLocked()) {
13735                    groupOwner = UserHandle.getSharedAppGid(uid);
13736                    protectedFile = RES_FILE_NAME;
13737                } else {
13738                    groupOwner = -1;
13739                    protectedFile = null;
13740                }
13741
13742                if (uid < Process.FIRST_APPLICATION_UID
13743                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13744                    Slog.e(TAG, "Failed to finalize " + cid);
13745                    PackageHelper.destroySdDir(cid);
13746                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13747                }
13748
13749                boolean mounted = PackageHelper.isContainerMounted(cid);
13750                if (!mounted) {
13751                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13752                }
13753            }
13754            return status;
13755        }
13756
13757        private void cleanUp() {
13758            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13759
13760            // Destroy secure container
13761            PackageHelper.destroySdDir(cid);
13762        }
13763
13764        private List<String> getAllCodePaths() {
13765            final File codeFile = new File(getCodePath());
13766            if (codeFile != null && codeFile.exists()) {
13767                try {
13768                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13769                    return pkg.getAllCodePaths();
13770                } catch (PackageParserException e) {
13771                    // Ignored; we tried our best
13772                }
13773            }
13774            return Collections.EMPTY_LIST;
13775        }
13776
13777        void cleanUpResourcesLI() {
13778            // Enumerate all code paths before deleting
13779            cleanUpResourcesLI(getAllCodePaths());
13780        }
13781
13782        private void cleanUpResourcesLI(List<String> allCodePaths) {
13783            cleanUp();
13784            removeDexFiles(allCodePaths, instructionSets);
13785        }
13786
13787        String getPackageName() {
13788            return getAsecPackageName(cid);
13789        }
13790
13791        boolean doPostDeleteLI(boolean delete) {
13792            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13793            final List<String> allCodePaths = getAllCodePaths();
13794            boolean mounted = PackageHelper.isContainerMounted(cid);
13795            if (mounted) {
13796                // Unmount first
13797                if (PackageHelper.unMountSdDir(cid)) {
13798                    mounted = false;
13799                }
13800            }
13801            if (!mounted && delete) {
13802                cleanUpResourcesLI(allCodePaths);
13803            }
13804            return !mounted;
13805        }
13806
13807        @Override
13808        int doPreCopy() {
13809            if (isFwdLocked()) {
13810                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13811                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13812                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13813                }
13814            }
13815
13816            return PackageManager.INSTALL_SUCCEEDED;
13817        }
13818
13819        @Override
13820        int doPostCopy(int uid) {
13821            if (isFwdLocked()) {
13822                if (uid < Process.FIRST_APPLICATION_UID
13823                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13824                                RES_FILE_NAME)) {
13825                    Slog.e(TAG, "Failed to finalize " + cid);
13826                    PackageHelper.destroySdDir(cid);
13827                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13828                }
13829            }
13830
13831            return PackageManager.INSTALL_SUCCEEDED;
13832        }
13833    }
13834
13835    /**
13836     * Logic to handle movement of existing installed applications.
13837     */
13838    class MoveInstallArgs extends InstallArgs {
13839        private File codeFile;
13840        private File resourceFile;
13841
13842        /** New install */
13843        MoveInstallArgs(InstallParams params) {
13844            super(params.origin, params.move, params.observer, params.installFlags,
13845                    params.installerPackageName, params.volumeUuid,
13846                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13847                    params.grantedRuntimePermissions,
13848                    params.traceMethod, params.traceCookie, params.certificates);
13849        }
13850
13851        int copyApk(IMediaContainerService imcs, boolean temp) {
13852            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13853                    + move.fromUuid + " to " + move.toUuid);
13854            synchronized (mInstaller) {
13855                try {
13856                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13857                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13858                } catch (InstallerException e) {
13859                    Slog.w(TAG, "Failed to move app", e);
13860                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13861                }
13862            }
13863
13864            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13865            resourceFile = codeFile;
13866            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13867
13868            return PackageManager.INSTALL_SUCCEEDED;
13869        }
13870
13871        int doPreInstall(int status) {
13872            if (status != PackageManager.INSTALL_SUCCEEDED) {
13873                cleanUp(move.toUuid);
13874            }
13875            return status;
13876        }
13877
13878        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13879            if (status != PackageManager.INSTALL_SUCCEEDED) {
13880                cleanUp(move.toUuid);
13881                return false;
13882            }
13883
13884            // Reflect the move in app info
13885            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13886            pkg.setApplicationInfoCodePath(pkg.codePath);
13887            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13888            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13889            pkg.setApplicationInfoResourcePath(pkg.codePath);
13890            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13891            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13892
13893            return true;
13894        }
13895
13896        int doPostInstall(int status, int uid) {
13897            if (status == PackageManager.INSTALL_SUCCEEDED) {
13898                cleanUp(move.fromUuid);
13899            } else {
13900                cleanUp(move.toUuid);
13901            }
13902            return status;
13903        }
13904
13905        @Override
13906        String getCodePath() {
13907            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13908        }
13909
13910        @Override
13911        String getResourcePath() {
13912            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13913        }
13914
13915        private boolean cleanUp(String volumeUuid) {
13916            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13917                    move.dataAppName);
13918            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13919            final int[] userIds = sUserManager.getUserIds();
13920            synchronized (mInstallLock) {
13921                // Clean up both app data and code
13922                // All package moves are frozen until finished
13923                for (int userId : userIds) {
13924                    try {
13925                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13926                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13927                    } catch (InstallerException e) {
13928                        Slog.w(TAG, String.valueOf(e));
13929                    }
13930                }
13931                removeCodePathLI(codeFile);
13932            }
13933            return true;
13934        }
13935
13936        void cleanUpResourcesLI() {
13937            throw new UnsupportedOperationException();
13938        }
13939
13940        boolean doPostDeleteLI(boolean delete) {
13941            throw new UnsupportedOperationException();
13942        }
13943    }
13944
13945    static String getAsecPackageName(String packageCid) {
13946        int idx = packageCid.lastIndexOf("-");
13947        if (idx == -1) {
13948            return packageCid;
13949        }
13950        return packageCid.substring(0, idx);
13951    }
13952
13953    // Utility method used to create code paths based on package name and available index.
13954    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13955        String idxStr = "";
13956        int idx = 1;
13957        // Fall back to default value of idx=1 if prefix is not
13958        // part of oldCodePath
13959        if (oldCodePath != null) {
13960            String subStr = oldCodePath;
13961            // Drop the suffix right away
13962            if (suffix != null && subStr.endsWith(suffix)) {
13963                subStr = subStr.substring(0, subStr.length() - suffix.length());
13964            }
13965            // If oldCodePath already contains prefix find out the
13966            // ending index to either increment or decrement.
13967            int sidx = subStr.lastIndexOf(prefix);
13968            if (sidx != -1) {
13969                subStr = subStr.substring(sidx + prefix.length());
13970                if (subStr != null) {
13971                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13972                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13973                    }
13974                    try {
13975                        idx = Integer.parseInt(subStr);
13976                        if (idx <= 1) {
13977                            idx++;
13978                        } else {
13979                            idx--;
13980                        }
13981                    } catch(NumberFormatException e) {
13982                    }
13983                }
13984            }
13985        }
13986        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13987        return prefix + idxStr;
13988    }
13989
13990    private File getNextCodePath(File targetDir, String packageName) {
13991        int suffix = 1;
13992        File result;
13993        do {
13994            result = new File(targetDir, packageName + "-" + suffix);
13995            suffix++;
13996        } while (result.exists());
13997        return result;
13998    }
13999
14000    // Utility method that returns the relative package path with respect
14001    // to the installation directory. Like say for /data/data/com.test-1.apk
14002    // string com.test-1 is returned.
14003    static String deriveCodePathName(String codePath) {
14004        if (codePath == null) {
14005            return null;
14006        }
14007        final File codeFile = new File(codePath);
14008        final String name = codeFile.getName();
14009        if (codeFile.isDirectory()) {
14010            return name;
14011        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14012            final int lastDot = name.lastIndexOf('.');
14013            return name.substring(0, lastDot);
14014        } else {
14015            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14016            return null;
14017        }
14018    }
14019
14020    static class PackageInstalledInfo {
14021        String name;
14022        int uid;
14023        // The set of users that originally had this package installed.
14024        int[] origUsers;
14025        // The set of users that now have this package installed.
14026        int[] newUsers;
14027        PackageParser.Package pkg;
14028        int returnCode;
14029        String returnMsg;
14030        PackageRemovedInfo removedInfo;
14031        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14032
14033        public void setError(int code, String msg) {
14034            setReturnCode(code);
14035            setReturnMessage(msg);
14036            Slog.w(TAG, msg);
14037        }
14038
14039        public void setError(String msg, PackageParserException e) {
14040            setReturnCode(e.error);
14041            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14042            Slog.w(TAG, msg, e);
14043        }
14044
14045        public void setError(String msg, PackageManagerException e) {
14046            returnCode = e.error;
14047            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14048            Slog.w(TAG, msg, e);
14049        }
14050
14051        public void setReturnCode(int returnCode) {
14052            this.returnCode = returnCode;
14053            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14054            for (int i = 0; i < childCount; i++) {
14055                addedChildPackages.valueAt(i).returnCode = returnCode;
14056            }
14057        }
14058
14059        private void setReturnMessage(String returnMsg) {
14060            this.returnMsg = returnMsg;
14061            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14062            for (int i = 0; i < childCount; i++) {
14063                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14064            }
14065        }
14066
14067        // In some error cases we want to convey more info back to the observer
14068        String origPackage;
14069        String origPermission;
14070    }
14071
14072    /*
14073     * Install a non-existing package.
14074     */
14075    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14076            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14077            PackageInstalledInfo res) {
14078        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14079
14080        // Remember this for later, in case we need to rollback this install
14081        String pkgName = pkg.packageName;
14082
14083        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14084
14085        synchronized(mPackages) {
14086            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14087                // A package with the same name is already installed, though
14088                // it has been renamed to an older name.  The package we
14089                // are trying to install should be installed as an update to
14090                // the existing one, but that has not been requested, so bail.
14091                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14092                        + " without first uninstalling package running as "
14093                        + mSettings.mRenamedPackages.get(pkgName));
14094                return;
14095            }
14096            if (mPackages.containsKey(pkgName)) {
14097                // Don't allow installation over an existing package with the same name.
14098                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14099                        + " without first uninstalling.");
14100                return;
14101            }
14102        }
14103
14104        try {
14105            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14106                    System.currentTimeMillis(), user);
14107
14108            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14109
14110            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14111                prepareAppDataAfterInstallLIF(newPackage);
14112
14113            } else {
14114                // Remove package from internal structures, but keep around any
14115                // data that might have already existed
14116                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14117                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14118            }
14119        } catch (PackageManagerException e) {
14120            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14121        }
14122
14123        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14124    }
14125
14126    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14127        // Can't rotate keys during boot or if sharedUser.
14128        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14129                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14130            return false;
14131        }
14132        // app is using upgradeKeySets; make sure all are valid
14133        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14134        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14135        for (int i = 0; i < upgradeKeySets.length; i++) {
14136            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14137                Slog.wtf(TAG, "Package "
14138                         + (oldPs.name != null ? oldPs.name : "<null>")
14139                         + " contains upgrade-key-set reference to unknown key-set: "
14140                         + upgradeKeySets[i]
14141                         + " reverting to signatures check.");
14142                return false;
14143            }
14144        }
14145        return true;
14146    }
14147
14148    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14149        // Upgrade keysets are being used.  Determine if new package has a superset of the
14150        // required keys.
14151        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14152        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14153        for (int i = 0; i < upgradeKeySets.length; i++) {
14154            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14155            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14156                return true;
14157            }
14158        }
14159        return false;
14160    }
14161
14162    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14163        try (DigestInputStream digestStream =
14164                new DigestInputStream(new FileInputStream(file), digest)) {
14165            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14166        }
14167    }
14168
14169    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14170            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14171        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14172
14173        final PackageParser.Package oldPackage;
14174        final String pkgName = pkg.packageName;
14175        final int[] allUsers;
14176        final int[] installedUsers;
14177
14178        synchronized(mPackages) {
14179            oldPackage = mPackages.get(pkgName);
14180            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14181
14182            // don't allow upgrade to target a release SDK from a pre-release SDK
14183            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14184                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14185            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14186                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14187            if (oldTargetsPreRelease
14188                    && !newTargetsPreRelease
14189                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14190                Slog.w(TAG, "Can't install package targeting released sdk");
14191                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14192                return;
14193            }
14194
14195            // don't allow an upgrade from full to ephemeral
14196            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14197            if (isEphemeral && !oldIsEphemeral) {
14198                // can't downgrade from full to ephemeral
14199                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14200                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14201                return;
14202            }
14203
14204            // verify signatures are valid
14205            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14206            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14207                if (!checkUpgradeKeySetLP(ps, pkg)) {
14208                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14209                            "New package not signed by keys specified by upgrade-keysets: "
14210                                    + pkgName);
14211                    return;
14212                }
14213            } else {
14214                // default to original signature matching
14215                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14216                        != PackageManager.SIGNATURE_MATCH) {
14217                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14218                            "New package has a different signature: " + pkgName);
14219                    return;
14220                }
14221            }
14222
14223            // don't allow a system upgrade unless the upgrade hash matches
14224            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14225                byte[] digestBytes = null;
14226                try {
14227                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14228                    updateDigest(digest, new File(pkg.baseCodePath));
14229                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14230                        for (String path : pkg.splitCodePaths) {
14231                            updateDigest(digest, new File(path));
14232                        }
14233                    }
14234                    digestBytes = digest.digest();
14235                } catch (NoSuchAlgorithmException | IOException e) {
14236                    res.setError(INSTALL_FAILED_INVALID_APK,
14237                            "Could not compute hash: " + pkgName);
14238                    return;
14239                }
14240                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14241                    res.setError(INSTALL_FAILED_INVALID_APK,
14242                            "New package fails restrict-update check: " + pkgName);
14243                    return;
14244                }
14245                // retain upgrade restriction
14246                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14247            }
14248
14249            // Check for shared user id changes
14250            String invalidPackageName =
14251                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14252            if (invalidPackageName != null) {
14253                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14254                        "Package " + invalidPackageName + " tried to change user "
14255                                + oldPackage.mSharedUserId);
14256                return;
14257            }
14258
14259            // In case of rollback, remember per-user/profile install state
14260            allUsers = sUserManager.getUserIds();
14261            installedUsers = ps.queryInstalledUsers(allUsers, true);
14262        }
14263
14264        // Update what is removed
14265        res.removedInfo = new PackageRemovedInfo();
14266        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14267        res.removedInfo.removedPackage = oldPackage.packageName;
14268        res.removedInfo.isUpdate = true;
14269        res.removedInfo.origUsers = installedUsers;
14270        final int childCount = (oldPackage.childPackages != null)
14271                ? oldPackage.childPackages.size() : 0;
14272        for (int i = 0; i < childCount; i++) {
14273            boolean childPackageUpdated = false;
14274            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14275            if (res.addedChildPackages != null) {
14276                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14277                if (childRes != null) {
14278                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14279                    childRes.removedInfo.removedPackage = childPkg.packageName;
14280                    childRes.removedInfo.isUpdate = true;
14281                    childPackageUpdated = true;
14282                }
14283            }
14284            if (!childPackageUpdated) {
14285                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14286                childRemovedRes.removedPackage = childPkg.packageName;
14287                childRemovedRes.isUpdate = false;
14288                childRemovedRes.dataRemoved = true;
14289                synchronized (mPackages) {
14290                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14291                    if (childPs != null) {
14292                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14293                    }
14294                }
14295                if (res.removedInfo.removedChildPackages == null) {
14296                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14297                }
14298                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14299            }
14300        }
14301
14302        boolean sysPkg = (isSystemApp(oldPackage));
14303        if (sysPkg) {
14304            // Set the system/privileged flags as needed
14305            final boolean privileged =
14306                    (oldPackage.applicationInfo.privateFlags
14307                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14308            final int systemPolicyFlags = policyFlags
14309                    | PackageParser.PARSE_IS_SYSTEM
14310                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14311
14312            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14313                    user, allUsers, installerPackageName, res);
14314        } else {
14315            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14316                    user, allUsers, installerPackageName, res);
14317        }
14318    }
14319
14320    public List<String> getPreviousCodePaths(String packageName) {
14321        final PackageSetting ps = mSettings.mPackages.get(packageName);
14322        final List<String> result = new ArrayList<String>();
14323        if (ps != null && ps.oldCodePaths != null) {
14324            result.addAll(ps.oldCodePaths);
14325        }
14326        return result;
14327    }
14328
14329    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14330            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14331            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14332        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14333                + deletedPackage);
14334
14335        String pkgName = deletedPackage.packageName;
14336        boolean deletedPkg = true;
14337        boolean addedPkg = false;
14338        boolean updatedSettings = false;
14339        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14340        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14341                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14342
14343        final long origUpdateTime = (pkg.mExtras != null)
14344                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14345
14346        // First delete the existing package while retaining the data directory
14347        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14348                res.removedInfo, true, pkg)) {
14349            // If the existing package wasn't successfully deleted
14350            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14351            deletedPkg = false;
14352        } else {
14353            // Successfully deleted the old package; proceed with replace.
14354
14355            // If deleted package lived in a container, give users a chance to
14356            // relinquish resources before killing.
14357            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14358                if (DEBUG_INSTALL) {
14359                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14360                }
14361                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14362                final ArrayList<String> pkgList = new ArrayList<String>(1);
14363                pkgList.add(deletedPackage.applicationInfo.packageName);
14364                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14365            }
14366
14367            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14368                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14369            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14370
14371            try {
14372                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14373                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14374                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14375
14376                // Update the in-memory copy of the previous code paths.
14377                PackageSetting ps = mSettings.mPackages.get(pkgName);
14378                if (!killApp) {
14379                    if (ps.oldCodePaths == null) {
14380                        ps.oldCodePaths = new ArraySet<>();
14381                    }
14382                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14383                    if (deletedPackage.splitCodePaths != null) {
14384                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14385                    }
14386                } else {
14387                    ps.oldCodePaths = null;
14388                }
14389                if (ps.childPackageNames != null) {
14390                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14391                        final String childPkgName = ps.childPackageNames.get(i);
14392                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14393                        childPs.oldCodePaths = ps.oldCodePaths;
14394                    }
14395                }
14396                prepareAppDataAfterInstallLIF(newPackage);
14397                addedPkg = true;
14398            } catch (PackageManagerException e) {
14399                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14400            }
14401        }
14402
14403        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14404            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14405
14406            // Revert all internal state mutations and added folders for the failed install
14407            if (addedPkg) {
14408                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14409                        res.removedInfo, true, null);
14410            }
14411
14412            // Restore the old package
14413            if (deletedPkg) {
14414                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14415                File restoreFile = new File(deletedPackage.codePath);
14416                // Parse old package
14417                boolean oldExternal = isExternal(deletedPackage);
14418                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14419                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14420                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14421                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14422                try {
14423                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14424                            null);
14425                } catch (PackageManagerException e) {
14426                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14427                            + e.getMessage());
14428                    return;
14429                }
14430
14431                synchronized (mPackages) {
14432                    // Ensure the installer package name up to date
14433                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14434
14435                    // Update permissions for restored package
14436                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14437
14438                    mSettings.writeLPr();
14439                }
14440
14441                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14442            }
14443        } else {
14444            synchronized (mPackages) {
14445                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14446                if (ps != null) {
14447                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14448                    if (res.removedInfo.removedChildPackages != null) {
14449                        final int childCount = res.removedInfo.removedChildPackages.size();
14450                        // Iterate in reverse as we may modify the collection
14451                        for (int i = childCount - 1; i >= 0; i--) {
14452                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14453                            if (res.addedChildPackages.containsKey(childPackageName)) {
14454                                res.removedInfo.removedChildPackages.removeAt(i);
14455                            } else {
14456                                PackageRemovedInfo childInfo = res.removedInfo
14457                                        .removedChildPackages.valueAt(i);
14458                                childInfo.removedForAllUsers = mPackages.get(
14459                                        childInfo.removedPackage) == null;
14460                            }
14461                        }
14462                    }
14463                }
14464            }
14465        }
14466    }
14467
14468    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14469            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14470            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14471        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14472                + ", old=" + deletedPackage);
14473
14474        final boolean disabledSystem;
14475
14476        // Remove existing system package
14477        removePackageLI(deletedPackage, true);
14478
14479        synchronized (mPackages) {
14480            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14481        }
14482        if (!disabledSystem) {
14483            // We didn't need to disable the .apk as a current system package,
14484            // which means we are replacing another update that is already
14485            // installed.  We need to make sure to delete the older one's .apk.
14486            res.removedInfo.args = createInstallArgsForExisting(0,
14487                    deletedPackage.applicationInfo.getCodePath(),
14488                    deletedPackage.applicationInfo.getResourcePath(),
14489                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14490        } else {
14491            res.removedInfo.args = null;
14492        }
14493
14494        // Successfully disabled the old package. Now proceed with re-installation
14495        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14496                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14497        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14498
14499        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14500        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14501                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14502
14503        PackageParser.Package newPackage = null;
14504        try {
14505            // Add the package to the internal data structures
14506            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14507
14508            // Set the update and install times
14509            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14510            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14511                    System.currentTimeMillis());
14512
14513            // Update the package dynamic state if succeeded
14514            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14515                // Now that the install succeeded make sure we remove data
14516                // directories for any child package the update removed.
14517                final int deletedChildCount = (deletedPackage.childPackages != null)
14518                        ? deletedPackage.childPackages.size() : 0;
14519                final int newChildCount = (newPackage.childPackages != null)
14520                        ? newPackage.childPackages.size() : 0;
14521                for (int i = 0; i < deletedChildCount; i++) {
14522                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14523                    boolean childPackageDeleted = true;
14524                    for (int j = 0; j < newChildCount; j++) {
14525                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14526                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14527                            childPackageDeleted = false;
14528                            break;
14529                        }
14530                    }
14531                    if (childPackageDeleted) {
14532                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14533                                deletedChildPkg.packageName);
14534                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14535                            PackageRemovedInfo removedChildRes = res.removedInfo
14536                                    .removedChildPackages.get(deletedChildPkg.packageName);
14537                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14538                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14539                        }
14540                    }
14541                }
14542
14543                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14544                prepareAppDataAfterInstallLIF(newPackage);
14545            }
14546        } catch (PackageManagerException e) {
14547            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14548            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14549        }
14550
14551        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14552            // Re installation failed. Restore old information
14553            // Remove new pkg information
14554            if (newPackage != null) {
14555                removeInstalledPackageLI(newPackage, true);
14556            }
14557            // Add back the old system package
14558            try {
14559                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14560            } catch (PackageManagerException e) {
14561                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14562            }
14563
14564            synchronized (mPackages) {
14565                if (disabledSystem) {
14566                    enableSystemPackageLPw(deletedPackage);
14567                }
14568
14569                // Ensure the installer package name up to date
14570                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14571
14572                // Update permissions for restored package
14573                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14574
14575                mSettings.writeLPr();
14576            }
14577
14578            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14579                    + " after failed upgrade");
14580        }
14581    }
14582
14583    /**
14584     * Checks whether the parent or any of the child packages have a change shared
14585     * user. For a package to be a valid update the shred users of the parent and
14586     * the children should match. We may later support changing child shared users.
14587     * @param oldPkg The updated package.
14588     * @param newPkg The update package.
14589     * @return The shared user that change between the versions.
14590     */
14591    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14592            PackageParser.Package newPkg) {
14593        // Check parent shared user
14594        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14595            return newPkg.packageName;
14596        }
14597        // Check child shared users
14598        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14599        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14600        for (int i = 0; i < newChildCount; i++) {
14601            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14602            // If this child was present, did it have the same shared user?
14603            for (int j = 0; j < oldChildCount; j++) {
14604                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14605                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14606                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14607                    return newChildPkg.packageName;
14608                }
14609            }
14610        }
14611        return null;
14612    }
14613
14614    private void removeNativeBinariesLI(PackageSetting ps) {
14615        // Remove the lib path for the parent package
14616        if (ps != null) {
14617            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14618            // Remove the lib path for the child packages
14619            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14620            for (int i = 0; i < childCount; i++) {
14621                PackageSetting childPs = null;
14622                synchronized (mPackages) {
14623                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14624                }
14625                if (childPs != null) {
14626                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14627                            .legacyNativeLibraryPathString);
14628                }
14629            }
14630        }
14631    }
14632
14633    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14634        // Enable the parent package
14635        mSettings.enableSystemPackageLPw(pkg.packageName);
14636        // Enable the child packages
14637        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14638        for (int i = 0; i < childCount; i++) {
14639            PackageParser.Package childPkg = pkg.childPackages.get(i);
14640            mSettings.enableSystemPackageLPw(childPkg.packageName);
14641        }
14642    }
14643
14644    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14645            PackageParser.Package newPkg) {
14646        // Disable the parent package (parent always replaced)
14647        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14648        // Disable the child packages
14649        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14650        for (int i = 0; i < childCount; i++) {
14651            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14652            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14653            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14654        }
14655        return disabled;
14656    }
14657
14658    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14659            String installerPackageName) {
14660        // Enable the parent package
14661        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14662        // Enable the child packages
14663        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14664        for (int i = 0; i < childCount; i++) {
14665            PackageParser.Package childPkg = pkg.childPackages.get(i);
14666            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14667        }
14668    }
14669
14670    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14671        // Collect all used permissions in the UID
14672        ArraySet<String> usedPermissions = new ArraySet<>();
14673        final int packageCount = su.packages.size();
14674        for (int i = 0; i < packageCount; i++) {
14675            PackageSetting ps = su.packages.valueAt(i);
14676            if (ps.pkg == null) {
14677                continue;
14678            }
14679            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14680            for (int j = 0; j < requestedPermCount; j++) {
14681                String permission = ps.pkg.requestedPermissions.get(j);
14682                BasePermission bp = mSettings.mPermissions.get(permission);
14683                if (bp != null) {
14684                    usedPermissions.add(permission);
14685                }
14686            }
14687        }
14688
14689        PermissionsState permissionsState = su.getPermissionsState();
14690        // Prune install permissions
14691        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14692        final int installPermCount = installPermStates.size();
14693        for (int i = installPermCount - 1; i >= 0;  i--) {
14694            PermissionState permissionState = installPermStates.get(i);
14695            if (!usedPermissions.contains(permissionState.getName())) {
14696                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14697                if (bp != null) {
14698                    permissionsState.revokeInstallPermission(bp);
14699                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14700                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14701                }
14702            }
14703        }
14704
14705        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14706
14707        // Prune runtime permissions
14708        for (int userId : allUserIds) {
14709            List<PermissionState> runtimePermStates = permissionsState
14710                    .getRuntimePermissionStates(userId);
14711            final int runtimePermCount = runtimePermStates.size();
14712            for (int i = runtimePermCount - 1; i >= 0; i--) {
14713                PermissionState permissionState = runtimePermStates.get(i);
14714                if (!usedPermissions.contains(permissionState.getName())) {
14715                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14716                    if (bp != null) {
14717                        permissionsState.revokeRuntimePermission(bp, userId);
14718                        permissionsState.updatePermissionFlags(bp, userId,
14719                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14720                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14721                                runtimePermissionChangedUserIds, userId);
14722                    }
14723                }
14724            }
14725        }
14726
14727        return runtimePermissionChangedUserIds;
14728    }
14729
14730    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14731            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14732        // Update the parent package setting
14733        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14734                res, user);
14735        // Update the child packages setting
14736        final int childCount = (newPackage.childPackages != null)
14737                ? newPackage.childPackages.size() : 0;
14738        for (int i = 0; i < childCount; i++) {
14739            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14740            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14741            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14742                    childRes.origUsers, childRes, user);
14743        }
14744    }
14745
14746    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14747            String installerPackageName, int[] allUsers, int[] installedForUsers,
14748            PackageInstalledInfo res, UserHandle user) {
14749        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14750
14751        String pkgName = newPackage.packageName;
14752        synchronized (mPackages) {
14753            //write settings. the installStatus will be incomplete at this stage.
14754            //note that the new package setting would have already been
14755            //added to mPackages. It hasn't been persisted yet.
14756            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14757            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14758            mSettings.writeLPr();
14759            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14760        }
14761
14762        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14763        synchronized (mPackages) {
14764            updatePermissionsLPw(newPackage.packageName, newPackage,
14765                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14766                            ? UPDATE_PERMISSIONS_ALL : 0));
14767            // For system-bundled packages, we assume that installing an upgraded version
14768            // of the package implies that the user actually wants to run that new code,
14769            // so we enable the package.
14770            PackageSetting ps = mSettings.mPackages.get(pkgName);
14771            final int userId = user.getIdentifier();
14772            if (ps != null) {
14773                if (isSystemApp(newPackage)) {
14774                    if (DEBUG_INSTALL) {
14775                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14776                    }
14777                    // Enable system package for requested users
14778                    if (res.origUsers != null) {
14779                        for (int origUserId : res.origUsers) {
14780                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14781                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14782                                        origUserId, installerPackageName);
14783                            }
14784                        }
14785                    }
14786                    // Also convey the prior install/uninstall state
14787                    if (allUsers != null && installedForUsers != null) {
14788                        for (int currentUserId : allUsers) {
14789                            final boolean installed = ArrayUtils.contains(
14790                                    installedForUsers, currentUserId);
14791                            if (DEBUG_INSTALL) {
14792                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14793                            }
14794                            ps.setInstalled(installed, currentUserId);
14795                        }
14796                        // these install state changes will be persisted in the
14797                        // upcoming call to mSettings.writeLPr().
14798                    }
14799                }
14800                // It's implied that when a user requests installation, they want the app to be
14801                // installed and enabled.
14802                if (userId != UserHandle.USER_ALL) {
14803                    ps.setInstalled(true, userId);
14804                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14805                }
14806            }
14807            res.name = pkgName;
14808            res.uid = newPackage.applicationInfo.uid;
14809            res.pkg = newPackage;
14810            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14811            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14812            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14813            //to update install status
14814            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14815            mSettings.writeLPr();
14816            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14817        }
14818
14819        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14820    }
14821
14822    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14823        try {
14824            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14825            installPackageLI(args, res);
14826        } finally {
14827            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14828        }
14829    }
14830
14831    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14832        final int installFlags = args.installFlags;
14833        final String installerPackageName = args.installerPackageName;
14834        final String volumeUuid = args.volumeUuid;
14835        final File tmpPackageFile = new File(args.getCodePath());
14836        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14837        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14838                || (args.volumeUuid != null));
14839        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14840        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14841        boolean replace = false;
14842        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14843        if (args.move != null) {
14844            // moving a complete application; perform an initial scan on the new install location
14845            scanFlags |= SCAN_INITIAL;
14846        }
14847        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14848            scanFlags |= SCAN_DONT_KILL_APP;
14849        }
14850
14851        // Result object to be returned
14852        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14853
14854        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14855
14856        // Sanity check
14857        if (ephemeral && (forwardLocked || onExternal)) {
14858            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14859                    + " external=" + onExternal);
14860            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14861            return;
14862        }
14863
14864        // Retrieve PackageSettings and parse package
14865        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14866                | PackageParser.PARSE_ENFORCE_CODE
14867                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14868                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14869                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14870                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14871        PackageParser pp = new PackageParser();
14872        pp.setSeparateProcesses(mSeparateProcesses);
14873        pp.setDisplayMetrics(mMetrics);
14874
14875        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14876        final PackageParser.Package pkg;
14877        try {
14878            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14879        } catch (PackageParserException e) {
14880            res.setError("Failed parse during installPackageLI", e);
14881            return;
14882        } finally {
14883            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14884        }
14885
14886        // If we are installing a clustered package add results for the children
14887        if (pkg.childPackages != null) {
14888            synchronized (mPackages) {
14889                final int childCount = pkg.childPackages.size();
14890                for (int i = 0; i < childCount; i++) {
14891                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14892                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14893                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14894                    childRes.pkg = childPkg;
14895                    childRes.name = childPkg.packageName;
14896                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14897                    if (childPs != null) {
14898                        childRes.origUsers = childPs.queryInstalledUsers(
14899                                sUserManager.getUserIds(), true);
14900                    }
14901                    if ((mPackages.containsKey(childPkg.packageName))) {
14902                        childRes.removedInfo = new PackageRemovedInfo();
14903                        childRes.removedInfo.removedPackage = childPkg.packageName;
14904                    }
14905                    if (res.addedChildPackages == null) {
14906                        res.addedChildPackages = new ArrayMap<>();
14907                    }
14908                    res.addedChildPackages.put(childPkg.packageName, childRes);
14909                }
14910            }
14911        }
14912
14913        // If package doesn't declare API override, mark that we have an install
14914        // time CPU ABI override.
14915        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14916            pkg.cpuAbiOverride = args.abiOverride;
14917        }
14918
14919        String pkgName = res.name = pkg.packageName;
14920        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14921            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14922                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14923                return;
14924            }
14925        }
14926
14927        try {
14928            // either use what we've been given or parse directly from the APK
14929            if (args.certificates != null) {
14930                try {
14931                    PackageParser.populateCertificates(pkg, args.certificates);
14932                } catch (PackageParserException e) {
14933                    // there was something wrong with the certificates we were given;
14934                    // try to pull them from the APK
14935                    PackageParser.collectCertificates(pkg, parseFlags);
14936                }
14937            } else {
14938                PackageParser.collectCertificates(pkg, parseFlags);
14939            }
14940        } catch (PackageParserException e) {
14941            res.setError("Failed collect during installPackageLI", e);
14942            return;
14943        }
14944
14945        // Get rid of all references to package scan path via parser.
14946        pp = null;
14947        String oldCodePath = null;
14948        boolean systemApp = false;
14949        synchronized (mPackages) {
14950            // Check if installing already existing package
14951            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14952                String oldName = mSettings.mRenamedPackages.get(pkgName);
14953                if (pkg.mOriginalPackages != null
14954                        && pkg.mOriginalPackages.contains(oldName)
14955                        && mPackages.containsKey(oldName)) {
14956                    // This package is derived from an original package,
14957                    // and this device has been updating from that original
14958                    // name.  We must continue using the original name, so
14959                    // rename the new package here.
14960                    pkg.setPackageName(oldName);
14961                    pkgName = pkg.packageName;
14962                    replace = true;
14963                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14964                            + oldName + " pkgName=" + pkgName);
14965                } else if (mPackages.containsKey(pkgName)) {
14966                    // This package, under its official name, already exists
14967                    // on the device; we should replace it.
14968                    replace = true;
14969                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14970                }
14971
14972                // Child packages are installed through the parent package
14973                if (pkg.parentPackage != null) {
14974                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14975                            "Package " + pkg.packageName + " is child of package "
14976                                    + pkg.parentPackage.parentPackage + ". Child packages "
14977                                    + "can be updated only through the parent package.");
14978                    return;
14979                }
14980
14981                if (replace) {
14982                    // Prevent apps opting out from runtime permissions
14983                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14984                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14985                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14986                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14987                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14988                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14989                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14990                                        + " doesn't support runtime permissions but the old"
14991                                        + " target SDK " + oldTargetSdk + " does.");
14992                        return;
14993                    }
14994
14995                    // Prevent installing of child packages
14996                    if (oldPackage.parentPackage != null) {
14997                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14998                                "Package " + pkg.packageName + " is child of package "
14999                                        + oldPackage.parentPackage + ". Child packages "
15000                                        + "can be updated only through the parent package.");
15001                        return;
15002                    }
15003                }
15004            }
15005
15006            PackageSetting ps = mSettings.mPackages.get(pkgName);
15007            if (ps != null) {
15008                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15009
15010                // Quick sanity check that we're signed correctly if updating;
15011                // we'll check this again later when scanning, but we want to
15012                // bail early here before tripping over redefined permissions.
15013                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15014                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15015                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15016                                + pkg.packageName + " upgrade keys do not match the "
15017                                + "previously installed version");
15018                        return;
15019                    }
15020                } else {
15021                    try {
15022                        verifySignaturesLP(ps, pkg);
15023                    } catch (PackageManagerException e) {
15024                        res.setError(e.error, e.getMessage());
15025                        return;
15026                    }
15027                }
15028
15029                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15030                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15031                    systemApp = (ps.pkg.applicationInfo.flags &
15032                            ApplicationInfo.FLAG_SYSTEM) != 0;
15033                }
15034                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15035            }
15036
15037            // Check whether the newly-scanned package wants to define an already-defined perm
15038            int N = pkg.permissions.size();
15039            for (int i = N-1; i >= 0; i--) {
15040                PackageParser.Permission perm = pkg.permissions.get(i);
15041                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15042                if (bp != null) {
15043                    // If the defining package is signed with our cert, it's okay.  This
15044                    // also includes the "updating the same package" case, of course.
15045                    // "updating same package" could also involve key-rotation.
15046                    final boolean sigsOk;
15047                    if (bp.sourcePackage.equals(pkg.packageName)
15048                            && (bp.packageSetting instanceof PackageSetting)
15049                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15050                                    scanFlags))) {
15051                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15052                    } else {
15053                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15054                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15055                    }
15056                    if (!sigsOk) {
15057                        // If the owning package is the system itself, we log but allow
15058                        // install to proceed; we fail the install on all other permission
15059                        // redefinitions.
15060                        if (!bp.sourcePackage.equals("android")) {
15061                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15062                                    + pkg.packageName + " attempting to redeclare permission "
15063                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15064                            res.origPermission = perm.info.name;
15065                            res.origPackage = bp.sourcePackage;
15066                            return;
15067                        } else {
15068                            Slog.w(TAG, "Package " + pkg.packageName
15069                                    + " attempting to redeclare system permission "
15070                                    + perm.info.name + "; ignoring new declaration");
15071                            pkg.permissions.remove(i);
15072                        }
15073                    }
15074                }
15075            }
15076        }
15077
15078        if (systemApp) {
15079            if (onExternal) {
15080                // Abort update; system app can't be replaced with app on sdcard
15081                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15082                        "Cannot install updates to system apps on sdcard");
15083                return;
15084            } else if (ephemeral) {
15085                // Abort update; system app can't be replaced with an ephemeral app
15086                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15087                        "Cannot update a system app with an ephemeral app");
15088                return;
15089            }
15090        }
15091
15092        if (args.move != null) {
15093            // We did an in-place move, so dex is ready to roll
15094            scanFlags |= SCAN_NO_DEX;
15095            scanFlags |= SCAN_MOVE;
15096
15097            synchronized (mPackages) {
15098                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15099                if (ps == null) {
15100                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15101                            "Missing settings for moved package " + pkgName);
15102                }
15103
15104                // We moved the entire application as-is, so bring over the
15105                // previously derived ABI information.
15106                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15107                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15108            }
15109
15110        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15111            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15112            scanFlags |= SCAN_NO_DEX;
15113
15114            try {
15115                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15116                    args.abiOverride : pkg.cpuAbiOverride);
15117                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15118                        true /* extract libs */);
15119            } catch (PackageManagerException pme) {
15120                Slog.e(TAG, "Error deriving application ABI", pme);
15121                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15122                return;
15123            }
15124
15125            // Shared libraries for the package need to be updated.
15126            synchronized (mPackages) {
15127                try {
15128                    updateSharedLibrariesLPw(pkg, null);
15129                } catch (PackageManagerException e) {
15130                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15131                }
15132            }
15133            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15134            // Do not run PackageDexOptimizer through the local performDexOpt
15135            // method because `pkg` may not be in `mPackages` yet.
15136            //
15137            // Also, don't fail application installs if the dexopt step fails.
15138            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15139                    null /* instructionSets */, false /* checkProfiles */,
15140                    getCompilerFilterForReason(REASON_INSTALL),
15141                    getOrCreateCompilerPackageStats(pkg));
15142            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15143
15144            // Notify BackgroundDexOptService that the package has been changed.
15145            // If this is an update of a package which used to fail to compile,
15146            // BDOS will remove it from its blacklist.
15147            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15148        }
15149
15150        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15151            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15152            return;
15153        }
15154
15155        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15156
15157        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15158                "installPackageLI")) {
15159            if (replace) {
15160                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15161                        installerPackageName, res);
15162            } else {
15163                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15164                        args.user, installerPackageName, volumeUuid, res);
15165            }
15166        }
15167        synchronized (mPackages) {
15168            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15169            if (ps != null) {
15170                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15171            }
15172
15173            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15174            for (int i = 0; i < childCount; i++) {
15175                PackageParser.Package childPkg = pkg.childPackages.get(i);
15176                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15177                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15178                if (childPs != null) {
15179                    childRes.newUsers = childPs.queryInstalledUsers(
15180                            sUserManager.getUserIds(), true);
15181                }
15182            }
15183        }
15184    }
15185
15186    private void startIntentFilterVerifications(int userId, boolean replacing,
15187            PackageParser.Package pkg) {
15188        if (mIntentFilterVerifierComponent == null) {
15189            Slog.w(TAG, "No IntentFilter verification will not be done as "
15190                    + "there is no IntentFilterVerifier available!");
15191            return;
15192        }
15193
15194        final int verifierUid = getPackageUid(
15195                mIntentFilterVerifierComponent.getPackageName(),
15196                MATCH_DEBUG_TRIAGED_MISSING,
15197                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15198
15199        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15200        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15201        mHandler.sendMessage(msg);
15202
15203        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15204        for (int i = 0; i < childCount; i++) {
15205            PackageParser.Package childPkg = pkg.childPackages.get(i);
15206            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15207            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15208            mHandler.sendMessage(msg);
15209        }
15210    }
15211
15212    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15213            PackageParser.Package pkg) {
15214        int size = pkg.activities.size();
15215        if (size == 0) {
15216            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15217                    "No activity, so no need to verify any IntentFilter!");
15218            return;
15219        }
15220
15221        final boolean hasDomainURLs = hasDomainURLs(pkg);
15222        if (!hasDomainURLs) {
15223            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15224                    "No domain URLs, so no need to verify any IntentFilter!");
15225            return;
15226        }
15227
15228        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15229                + " if any IntentFilter from the " + size
15230                + " Activities needs verification ...");
15231
15232        int count = 0;
15233        final String packageName = pkg.packageName;
15234
15235        synchronized (mPackages) {
15236            // If this is a new install and we see that we've already run verification for this
15237            // package, we have nothing to do: it means the state was restored from backup.
15238            if (!replacing) {
15239                IntentFilterVerificationInfo ivi =
15240                        mSettings.getIntentFilterVerificationLPr(packageName);
15241                if (ivi != null) {
15242                    if (DEBUG_DOMAIN_VERIFICATION) {
15243                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15244                                + ivi.getStatusString());
15245                    }
15246                    return;
15247                }
15248            }
15249
15250            // If any filters need to be verified, then all need to be.
15251            boolean needToVerify = false;
15252            for (PackageParser.Activity a : pkg.activities) {
15253                for (ActivityIntentInfo filter : a.intents) {
15254                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15255                        if (DEBUG_DOMAIN_VERIFICATION) {
15256                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15257                        }
15258                        needToVerify = true;
15259                        break;
15260                    }
15261                }
15262            }
15263
15264            if (needToVerify) {
15265                final int verificationId = mIntentFilterVerificationToken++;
15266                for (PackageParser.Activity a : pkg.activities) {
15267                    for (ActivityIntentInfo filter : a.intents) {
15268                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15269                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15270                                    "Verification needed for IntentFilter:" + filter.toString());
15271                            mIntentFilterVerifier.addOneIntentFilterVerification(
15272                                    verifierUid, userId, verificationId, filter, packageName);
15273                            count++;
15274                        }
15275                    }
15276                }
15277            }
15278        }
15279
15280        if (count > 0) {
15281            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15282                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15283                    +  " for userId:" + userId);
15284            mIntentFilterVerifier.startVerifications(userId);
15285        } else {
15286            if (DEBUG_DOMAIN_VERIFICATION) {
15287                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15288            }
15289        }
15290    }
15291
15292    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15293        final ComponentName cn  = filter.activity.getComponentName();
15294        final String packageName = cn.getPackageName();
15295
15296        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15297                packageName);
15298        if (ivi == null) {
15299            return true;
15300        }
15301        int status = ivi.getStatus();
15302        switch (status) {
15303            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15304            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15305                return true;
15306
15307            default:
15308                // Nothing to do
15309                return false;
15310        }
15311    }
15312
15313    private static boolean isMultiArch(ApplicationInfo info) {
15314        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15315    }
15316
15317    private static boolean isExternal(PackageParser.Package pkg) {
15318        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15319    }
15320
15321    private static boolean isExternal(PackageSetting ps) {
15322        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15323    }
15324
15325    private static boolean isEphemeral(PackageParser.Package pkg) {
15326        return pkg.applicationInfo.isEphemeralApp();
15327    }
15328
15329    private static boolean isEphemeral(PackageSetting ps) {
15330        return ps.pkg != null && isEphemeral(ps.pkg);
15331    }
15332
15333    private static boolean isSystemApp(PackageParser.Package pkg) {
15334        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15335    }
15336
15337    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15338        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15339    }
15340
15341    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15342        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15343    }
15344
15345    private static boolean isSystemApp(PackageSetting ps) {
15346        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15347    }
15348
15349    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15350        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15351    }
15352
15353    private int packageFlagsToInstallFlags(PackageSetting ps) {
15354        int installFlags = 0;
15355        if (isEphemeral(ps)) {
15356            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15357        }
15358        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15359            // This existing package was an external ASEC install when we have
15360            // the external flag without a UUID
15361            installFlags |= PackageManager.INSTALL_EXTERNAL;
15362        }
15363        if (ps.isForwardLocked()) {
15364            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15365        }
15366        return installFlags;
15367    }
15368
15369    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15370        if (isExternal(pkg)) {
15371            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15372                return StorageManager.UUID_PRIMARY_PHYSICAL;
15373            } else {
15374                return pkg.volumeUuid;
15375            }
15376        } else {
15377            return StorageManager.UUID_PRIVATE_INTERNAL;
15378        }
15379    }
15380
15381    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15382        if (isExternal(pkg)) {
15383            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15384                return mSettings.getExternalVersion();
15385            } else {
15386                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15387            }
15388        } else {
15389            return mSettings.getInternalVersion();
15390        }
15391    }
15392
15393    private void deleteTempPackageFiles() {
15394        final FilenameFilter filter = new FilenameFilter() {
15395            public boolean accept(File dir, String name) {
15396                return name.startsWith("vmdl") && name.endsWith(".tmp");
15397            }
15398        };
15399        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15400            file.delete();
15401        }
15402    }
15403
15404    @Override
15405    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15406            int flags) {
15407        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15408                flags);
15409    }
15410
15411    @Override
15412    public void deletePackage(final String packageName,
15413            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15414        mContext.enforceCallingOrSelfPermission(
15415                android.Manifest.permission.DELETE_PACKAGES, null);
15416        Preconditions.checkNotNull(packageName);
15417        Preconditions.checkNotNull(observer);
15418        final int uid = Binder.getCallingUid();
15419        if (!isOrphaned(packageName)
15420                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15421            try {
15422                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15423                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15424                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15425                observer.onUserActionRequired(intent);
15426            } catch (RemoteException re) {
15427            }
15428            return;
15429        }
15430        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15431        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15432        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15433            mContext.enforceCallingOrSelfPermission(
15434                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15435                    "deletePackage for user " + userId);
15436        }
15437
15438        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15439            try {
15440                observer.onPackageDeleted(packageName,
15441                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15442            } catch (RemoteException re) {
15443            }
15444            return;
15445        }
15446
15447        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15448            try {
15449                observer.onPackageDeleted(packageName,
15450                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15451            } catch (RemoteException re) {
15452            }
15453            return;
15454        }
15455
15456        if (DEBUG_REMOVE) {
15457            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15458                    + " deleteAllUsers: " + deleteAllUsers );
15459        }
15460        // Queue up an async operation since the package deletion may take a little while.
15461        mHandler.post(new Runnable() {
15462            public void run() {
15463                mHandler.removeCallbacks(this);
15464                int returnCode;
15465                if (!deleteAllUsers) {
15466                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15467                } else {
15468                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15469                    // If nobody is blocking uninstall, proceed with delete for all users
15470                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15471                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15472                    } else {
15473                        // Otherwise uninstall individually for users with blockUninstalls=false
15474                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15475                        for (int userId : users) {
15476                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15477                                returnCode = deletePackageX(packageName, userId, userFlags);
15478                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15479                                    Slog.w(TAG, "Package delete failed for user " + userId
15480                                            + ", returnCode " + returnCode);
15481                                }
15482                            }
15483                        }
15484                        // The app has only been marked uninstalled for certain users.
15485                        // We still need to report that delete was blocked
15486                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15487                    }
15488                }
15489                try {
15490                    observer.onPackageDeleted(packageName, returnCode, null);
15491                } catch (RemoteException e) {
15492                    Log.i(TAG, "Observer no longer exists.");
15493                } //end catch
15494            } //end run
15495        });
15496    }
15497
15498    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15499        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15500              || callingUid == Process.SYSTEM_UID) {
15501            return true;
15502        }
15503        final int callingUserId = UserHandle.getUserId(callingUid);
15504        // If the caller installed the pkgName, then allow it to silently uninstall.
15505        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15506            return true;
15507        }
15508
15509        // Allow package verifier to silently uninstall.
15510        if (mRequiredVerifierPackage != null &&
15511                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15512            return true;
15513        }
15514
15515        // Allow package uninstaller to silently uninstall.
15516        if (mRequiredUninstallerPackage != null &&
15517                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15518            return true;
15519        }
15520
15521        // Allow storage manager to silently uninstall.
15522        if (mStorageManagerPackage != null &&
15523                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15524            return true;
15525        }
15526        return false;
15527    }
15528
15529    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15530        int[] result = EMPTY_INT_ARRAY;
15531        for (int userId : userIds) {
15532            if (getBlockUninstallForUser(packageName, userId)) {
15533                result = ArrayUtils.appendInt(result, userId);
15534            }
15535        }
15536        return result;
15537    }
15538
15539    @Override
15540    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15541        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15542    }
15543
15544    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15545        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15546                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15547        try {
15548            if (dpm != null) {
15549                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15550                        /* callingUserOnly =*/ false);
15551                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15552                        : deviceOwnerComponentName.getPackageName();
15553                // Does the package contains the device owner?
15554                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15555                // this check is probably not needed, since DO should be registered as a device
15556                // admin on some user too. (Original bug for this: b/17657954)
15557                if (packageName.equals(deviceOwnerPackageName)) {
15558                    return true;
15559                }
15560                // Does it contain a device admin for any user?
15561                int[] users;
15562                if (userId == UserHandle.USER_ALL) {
15563                    users = sUserManager.getUserIds();
15564                } else {
15565                    users = new int[]{userId};
15566                }
15567                for (int i = 0; i < users.length; ++i) {
15568                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15569                        return true;
15570                    }
15571                }
15572            }
15573        } catch (RemoteException e) {
15574        }
15575        return false;
15576    }
15577
15578    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15579        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15580    }
15581
15582    /**
15583     *  This method is an internal method that could be get invoked either
15584     *  to delete an installed package or to clean up a failed installation.
15585     *  After deleting an installed package, a broadcast is sent to notify any
15586     *  listeners that the package has been removed. For cleaning up a failed
15587     *  installation, the broadcast is not necessary since the package's
15588     *  installation wouldn't have sent the initial broadcast either
15589     *  The key steps in deleting a package are
15590     *  deleting the package information in internal structures like mPackages,
15591     *  deleting the packages base directories through installd
15592     *  updating mSettings to reflect current status
15593     *  persisting settings for later use
15594     *  sending a broadcast if necessary
15595     */
15596    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15597        final PackageRemovedInfo info = new PackageRemovedInfo();
15598        final boolean res;
15599
15600        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15601                ? UserHandle.USER_ALL : userId;
15602
15603        if (isPackageDeviceAdmin(packageName, removeUser)) {
15604            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15605            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15606        }
15607
15608        PackageSetting uninstalledPs = null;
15609
15610        // for the uninstall-updates case and restricted profiles, remember the per-
15611        // user handle installed state
15612        int[] allUsers;
15613        synchronized (mPackages) {
15614            uninstalledPs = mSettings.mPackages.get(packageName);
15615            if (uninstalledPs == null) {
15616                Slog.w(TAG, "Not removing non-existent package " + packageName);
15617                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15618            }
15619            allUsers = sUserManager.getUserIds();
15620            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15621        }
15622
15623        final int freezeUser;
15624        if (isUpdatedSystemApp(uninstalledPs)
15625                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15626            // We're downgrading a system app, which will apply to all users, so
15627            // freeze them all during the downgrade
15628            freezeUser = UserHandle.USER_ALL;
15629        } else {
15630            freezeUser = removeUser;
15631        }
15632
15633        synchronized (mInstallLock) {
15634            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15635            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15636                    deleteFlags, "deletePackageX")) {
15637                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15638                        deleteFlags | REMOVE_CHATTY, info, true, null);
15639            }
15640            synchronized (mPackages) {
15641                if (res) {
15642                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15643                }
15644            }
15645        }
15646
15647        if (res) {
15648            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15649            info.sendPackageRemovedBroadcasts(killApp);
15650            info.sendSystemPackageUpdatedBroadcasts();
15651            info.sendSystemPackageAppearedBroadcasts();
15652        }
15653        // Force a gc here.
15654        Runtime.getRuntime().gc();
15655        // Delete the resources here after sending the broadcast to let
15656        // other processes clean up before deleting resources.
15657        if (info.args != null) {
15658            synchronized (mInstallLock) {
15659                info.args.doPostDeleteLI(true);
15660            }
15661        }
15662
15663        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15664    }
15665
15666    class PackageRemovedInfo {
15667        String removedPackage;
15668        int uid = -1;
15669        int removedAppId = -1;
15670        int[] origUsers;
15671        int[] removedUsers = null;
15672        boolean isRemovedPackageSystemUpdate = false;
15673        boolean isUpdate;
15674        boolean dataRemoved;
15675        boolean removedForAllUsers;
15676        // Clean up resources deleted packages.
15677        InstallArgs args = null;
15678        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15679        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15680
15681        void sendPackageRemovedBroadcasts(boolean killApp) {
15682            sendPackageRemovedBroadcastInternal(killApp);
15683            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15684            for (int i = 0; i < childCount; i++) {
15685                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15686                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15687            }
15688        }
15689
15690        void sendSystemPackageUpdatedBroadcasts() {
15691            if (isRemovedPackageSystemUpdate) {
15692                sendSystemPackageUpdatedBroadcastsInternal();
15693                final int childCount = (removedChildPackages != null)
15694                        ? removedChildPackages.size() : 0;
15695                for (int i = 0; i < childCount; i++) {
15696                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15697                    if (childInfo.isRemovedPackageSystemUpdate) {
15698                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15699                    }
15700                }
15701            }
15702        }
15703
15704        void sendSystemPackageAppearedBroadcasts() {
15705            final int packageCount = (appearedChildPackages != null)
15706                    ? appearedChildPackages.size() : 0;
15707            for (int i = 0; i < packageCount; i++) {
15708                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15709                for (int userId : installedInfo.newUsers) {
15710                    sendPackageAddedForUser(installedInfo.name, true,
15711                            UserHandle.getAppId(installedInfo.uid), userId);
15712                }
15713            }
15714        }
15715
15716        private void sendSystemPackageUpdatedBroadcastsInternal() {
15717            Bundle extras = new Bundle(2);
15718            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15719            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15720            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15721                    extras, 0, null, null, null);
15722            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15723                    extras, 0, null, null, null);
15724            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15725                    null, 0, removedPackage, null, null);
15726        }
15727
15728        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15729            Bundle extras = new Bundle(2);
15730            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15731            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15732            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15733            if (isUpdate || isRemovedPackageSystemUpdate) {
15734                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15735            }
15736            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15737            if (removedPackage != null) {
15738                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15739                        extras, 0, null, null, removedUsers);
15740                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15741                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15742                            removedPackage, extras, 0, null, null, removedUsers);
15743                }
15744            }
15745            if (removedAppId >= 0) {
15746                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15747                        removedUsers);
15748            }
15749        }
15750    }
15751
15752    /*
15753     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15754     * flag is not set, the data directory is removed as well.
15755     * make sure this flag is set for partially installed apps. If not its meaningless to
15756     * delete a partially installed application.
15757     */
15758    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15759            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15760        String packageName = ps.name;
15761        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15762        // Retrieve object to delete permissions for shared user later on
15763        final PackageParser.Package deletedPkg;
15764        final PackageSetting deletedPs;
15765        // reader
15766        synchronized (mPackages) {
15767            deletedPkg = mPackages.get(packageName);
15768            deletedPs = mSettings.mPackages.get(packageName);
15769            if (outInfo != null) {
15770                outInfo.removedPackage = packageName;
15771                outInfo.removedUsers = deletedPs != null
15772                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15773                        : null;
15774            }
15775        }
15776
15777        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15778
15779        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15780            final PackageParser.Package resolvedPkg;
15781            if (deletedPkg != null) {
15782                resolvedPkg = deletedPkg;
15783            } else {
15784                // We don't have a parsed package when it lives on an ejected
15785                // adopted storage device, so fake something together
15786                resolvedPkg = new PackageParser.Package(ps.name);
15787                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15788            }
15789            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15790                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15791            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15792            if (outInfo != null) {
15793                outInfo.dataRemoved = true;
15794            }
15795            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15796        }
15797
15798        // writer
15799        synchronized (mPackages) {
15800            if (deletedPs != null) {
15801                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15802                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15803                    clearDefaultBrowserIfNeeded(packageName);
15804                    if (outInfo != null) {
15805                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15806                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15807                    }
15808                    updatePermissionsLPw(deletedPs.name, null, 0);
15809                    if (deletedPs.sharedUser != null) {
15810                        // Remove permissions associated with package. Since runtime
15811                        // permissions are per user we have to kill the removed package
15812                        // or packages running under the shared user of the removed
15813                        // package if revoking the permissions requested only by the removed
15814                        // package is successful and this causes a change in gids.
15815                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15816                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15817                                    userId);
15818                            if (userIdToKill == UserHandle.USER_ALL
15819                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15820                                // If gids changed for this user, kill all affected packages.
15821                                mHandler.post(new Runnable() {
15822                                    @Override
15823                                    public void run() {
15824                                        // This has to happen with no lock held.
15825                                        killApplication(deletedPs.name, deletedPs.appId,
15826                                                KILL_APP_REASON_GIDS_CHANGED);
15827                                    }
15828                                });
15829                                break;
15830                            }
15831                        }
15832                    }
15833                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15834                }
15835                // make sure to preserve per-user disabled state if this removal was just
15836                // a downgrade of a system app to the factory package
15837                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15838                    if (DEBUG_REMOVE) {
15839                        Slog.d(TAG, "Propagating install state across downgrade");
15840                    }
15841                    for (int userId : allUserHandles) {
15842                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15843                        if (DEBUG_REMOVE) {
15844                            Slog.d(TAG, "    user " + userId + " => " + installed);
15845                        }
15846                        ps.setInstalled(installed, userId);
15847                    }
15848                }
15849            }
15850            // can downgrade to reader
15851            if (writeSettings) {
15852                // Save settings now
15853                mSettings.writeLPr();
15854            }
15855        }
15856        if (outInfo != null) {
15857            // A user ID was deleted here. Go through all users and remove it
15858            // from KeyStore.
15859            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15860        }
15861    }
15862
15863    static boolean locationIsPrivileged(File path) {
15864        try {
15865            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15866                    .getCanonicalPath();
15867            return path.getCanonicalPath().startsWith(privilegedAppDir);
15868        } catch (IOException e) {
15869            Slog.e(TAG, "Unable to access code path " + path);
15870        }
15871        return false;
15872    }
15873
15874    /*
15875     * Tries to delete system package.
15876     */
15877    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15878            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15879            boolean writeSettings) {
15880        if (deletedPs.parentPackageName != null) {
15881            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15882            return false;
15883        }
15884
15885        final boolean applyUserRestrictions
15886                = (allUserHandles != null) && (outInfo.origUsers != null);
15887        final PackageSetting disabledPs;
15888        // Confirm if the system package has been updated
15889        // An updated system app can be deleted. This will also have to restore
15890        // the system pkg from system partition
15891        // reader
15892        synchronized (mPackages) {
15893            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15894        }
15895
15896        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15897                + " disabledPs=" + disabledPs);
15898
15899        if (disabledPs == null) {
15900            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15901            return false;
15902        } else if (DEBUG_REMOVE) {
15903            Slog.d(TAG, "Deleting system pkg from data partition");
15904        }
15905
15906        if (DEBUG_REMOVE) {
15907            if (applyUserRestrictions) {
15908                Slog.d(TAG, "Remembering install states:");
15909                for (int userId : allUserHandles) {
15910                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15911                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15912                }
15913            }
15914        }
15915
15916        // Delete the updated package
15917        outInfo.isRemovedPackageSystemUpdate = true;
15918        if (outInfo.removedChildPackages != null) {
15919            final int childCount = (deletedPs.childPackageNames != null)
15920                    ? deletedPs.childPackageNames.size() : 0;
15921            for (int i = 0; i < childCount; i++) {
15922                String childPackageName = deletedPs.childPackageNames.get(i);
15923                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15924                        .contains(childPackageName)) {
15925                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15926                            childPackageName);
15927                    if (childInfo != null) {
15928                        childInfo.isRemovedPackageSystemUpdate = true;
15929                    }
15930                }
15931            }
15932        }
15933
15934        if (disabledPs.versionCode < deletedPs.versionCode) {
15935            // Delete data for downgrades
15936            flags &= ~PackageManager.DELETE_KEEP_DATA;
15937        } else {
15938            // Preserve data by setting flag
15939            flags |= PackageManager.DELETE_KEEP_DATA;
15940        }
15941
15942        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15943                outInfo, writeSettings, disabledPs.pkg);
15944        if (!ret) {
15945            return false;
15946        }
15947
15948        // writer
15949        synchronized (mPackages) {
15950            // Reinstate the old system package
15951            enableSystemPackageLPw(disabledPs.pkg);
15952            // Remove any native libraries from the upgraded package.
15953            removeNativeBinariesLI(deletedPs);
15954        }
15955
15956        // Install the system package
15957        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15958        int parseFlags = mDefParseFlags
15959                | PackageParser.PARSE_MUST_BE_APK
15960                | PackageParser.PARSE_IS_SYSTEM
15961                | PackageParser.PARSE_IS_SYSTEM_DIR;
15962        if (locationIsPrivileged(disabledPs.codePath)) {
15963            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15964        }
15965
15966        final PackageParser.Package newPkg;
15967        try {
15968            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15969        } catch (PackageManagerException e) {
15970            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15971                    + e.getMessage());
15972            return false;
15973        }
15974        try {
15975            // update shared libraries for the newly re-installed system package
15976            updateSharedLibrariesLPw(newPkg, null);
15977        } catch (PackageManagerException e) {
15978            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
15979        }
15980
15981        prepareAppDataAfterInstallLIF(newPkg);
15982
15983        // writer
15984        synchronized (mPackages) {
15985            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15986
15987            // Propagate the permissions state as we do not want to drop on the floor
15988            // runtime permissions. The update permissions method below will take
15989            // care of removing obsolete permissions and grant install permissions.
15990            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15991            updatePermissionsLPw(newPkg.packageName, newPkg,
15992                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15993
15994            if (applyUserRestrictions) {
15995                if (DEBUG_REMOVE) {
15996                    Slog.d(TAG, "Propagating install state across reinstall");
15997                }
15998                for (int userId : allUserHandles) {
15999                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16000                    if (DEBUG_REMOVE) {
16001                        Slog.d(TAG, "    user " + userId + " => " + installed);
16002                    }
16003                    ps.setInstalled(installed, userId);
16004
16005                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16006                }
16007                // Regardless of writeSettings we need to ensure that this restriction
16008                // state propagation is persisted
16009                mSettings.writeAllUsersPackageRestrictionsLPr();
16010            }
16011            // can downgrade to reader here
16012            if (writeSettings) {
16013                mSettings.writeLPr();
16014            }
16015        }
16016        return true;
16017    }
16018
16019    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16020            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16021            PackageRemovedInfo outInfo, boolean writeSettings,
16022            PackageParser.Package replacingPackage) {
16023        synchronized (mPackages) {
16024            if (outInfo != null) {
16025                outInfo.uid = ps.appId;
16026            }
16027
16028            if (outInfo != null && outInfo.removedChildPackages != null) {
16029                final int childCount = (ps.childPackageNames != null)
16030                        ? ps.childPackageNames.size() : 0;
16031                for (int i = 0; i < childCount; i++) {
16032                    String childPackageName = ps.childPackageNames.get(i);
16033                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16034                    if (childPs == null) {
16035                        return false;
16036                    }
16037                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16038                            childPackageName);
16039                    if (childInfo != null) {
16040                        childInfo.uid = childPs.appId;
16041                    }
16042                }
16043            }
16044        }
16045
16046        // Delete package data from internal structures and also remove data if flag is set
16047        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16048
16049        // Delete the child packages data
16050        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16051        for (int i = 0; i < childCount; i++) {
16052            PackageSetting childPs;
16053            synchronized (mPackages) {
16054                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16055            }
16056            if (childPs != null) {
16057                PackageRemovedInfo childOutInfo = (outInfo != null
16058                        && outInfo.removedChildPackages != null)
16059                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16060                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16061                        && (replacingPackage != null
16062                        && !replacingPackage.hasChildPackage(childPs.name))
16063                        ? flags & ~DELETE_KEEP_DATA : flags;
16064                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16065                        deleteFlags, writeSettings);
16066            }
16067        }
16068
16069        // Delete application code and resources only for parent packages
16070        if (ps.parentPackageName == null) {
16071            if (deleteCodeAndResources && (outInfo != null)) {
16072                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16073                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16074                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16075            }
16076        }
16077
16078        return true;
16079    }
16080
16081    @Override
16082    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16083            int userId) {
16084        mContext.enforceCallingOrSelfPermission(
16085                android.Manifest.permission.DELETE_PACKAGES, null);
16086        synchronized (mPackages) {
16087            PackageSetting ps = mSettings.mPackages.get(packageName);
16088            if (ps == null) {
16089                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16090                return false;
16091            }
16092            if (!ps.getInstalled(userId)) {
16093                // Can't block uninstall for an app that is not installed or enabled.
16094                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16095                return false;
16096            }
16097            ps.setBlockUninstall(blockUninstall, userId);
16098            mSettings.writePackageRestrictionsLPr(userId);
16099        }
16100        return true;
16101    }
16102
16103    @Override
16104    public boolean getBlockUninstallForUser(String packageName, int userId) {
16105        synchronized (mPackages) {
16106            PackageSetting ps = mSettings.mPackages.get(packageName);
16107            if (ps == null) {
16108                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16109                return false;
16110            }
16111            return ps.getBlockUninstall(userId);
16112        }
16113    }
16114
16115    @Override
16116    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16117        int callingUid = Binder.getCallingUid();
16118        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16119            throw new SecurityException(
16120                    "setRequiredForSystemUser can only be run by the system or root");
16121        }
16122        synchronized (mPackages) {
16123            PackageSetting ps = mSettings.mPackages.get(packageName);
16124            if (ps == null) {
16125                Log.w(TAG, "Package doesn't exist: " + packageName);
16126                return false;
16127            }
16128            if (systemUserApp) {
16129                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16130            } else {
16131                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16132            }
16133            mSettings.writeLPr();
16134        }
16135        return true;
16136    }
16137
16138    /*
16139     * This method handles package deletion in general
16140     */
16141    private boolean deletePackageLIF(String packageName, UserHandle user,
16142            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16143            PackageRemovedInfo outInfo, boolean writeSettings,
16144            PackageParser.Package replacingPackage) {
16145        if (packageName == null) {
16146            Slog.w(TAG, "Attempt to delete null packageName.");
16147            return false;
16148        }
16149
16150        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16151
16152        PackageSetting ps;
16153
16154        synchronized (mPackages) {
16155            ps = mSettings.mPackages.get(packageName);
16156            if (ps == null) {
16157                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16158                return false;
16159            }
16160
16161            if (ps.parentPackageName != null && (!isSystemApp(ps)
16162                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16163                if (DEBUG_REMOVE) {
16164                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16165                            + ((user == null) ? UserHandle.USER_ALL : user));
16166                }
16167                final int removedUserId = (user != null) ? user.getIdentifier()
16168                        : UserHandle.USER_ALL;
16169                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16170                    return false;
16171                }
16172                markPackageUninstalledForUserLPw(ps, user);
16173                scheduleWritePackageRestrictionsLocked(user);
16174                return true;
16175            }
16176        }
16177
16178        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16179                && user.getIdentifier() != UserHandle.USER_ALL)) {
16180            // The caller is asking that the package only be deleted for a single
16181            // user.  To do this, we just mark its uninstalled state and delete
16182            // its data. If this is a system app, we only allow this to happen if
16183            // they have set the special DELETE_SYSTEM_APP which requests different
16184            // semantics than normal for uninstalling system apps.
16185            markPackageUninstalledForUserLPw(ps, user);
16186
16187            if (!isSystemApp(ps)) {
16188                // Do not uninstall the APK if an app should be cached
16189                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16190                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16191                    // Other user still have this package installed, so all
16192                    // we need to do is clear this user's data and save that
16193                    // it is uninstalled.
16194                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16195                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16196                        return false;
16197                    }
16198                    scheduleWritePackageRestrictionsLocked(user);
16199                    return true;
16200                } else {
16201                    // We need to set it back to 'installed' so the uninstall
16202                    // broadcasts will be sent correctly.
16203                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16204                    ps.setInstalled(true, user.getIdentifier());
16205                }
16206            } else {
16207                // This is a system app, so we assume that the
16208                // other users still have this package installed, so all
16209                // we need to do is clear this user's data and save that
16210                // it is uninstalled.
16211                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16212                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16213                    return false;
16214                }
16215                scheduleWritePackageRestrictionsLocked(user);
16216                return true;
16217            }
16218        }
16219
16220        // If we are deleting a composite package for all users, keep track
16221        // of result for each child.
16222        if (ps.childPackageNames != null && outInfo != null) {
16223            synchronized (mPackages) {
16224                final int childCount = ps.childPackageNames.size();
16225                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16226                for (int i = 0; i < childCount; i++) {
16227                    String childPackageName = ps.childPackageNames.get(i);
16228                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16229                    childInfo.removedPackage = childPackageName;
16230                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16231                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16232                    if (childPs != null) {
16233                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16234                    }
16235                }
16236            }
16237        }
16238
16239        boolean ret = false;
16240        if (isSystemApp(ps)) {
16241            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16242            // When an updated system application is deleted we delete the existing resources
16243            // as well and fall back to existing code in system partition
16244            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16245        } else {
16246            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16247            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16248                    outInfo, writeSettings, replacingPackage);
16249        }
16250
16251        // Take a note whether we deleted the package for all users
16252        if (outInfo != null) {
16253            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16254            if (outInfo.removedChildPackages != null) {
16255                synchronized (mPackages) {
16256                    final int childCount = outInfo.removedChildPackages.size();
16257                    for (int i = 0; i < childCount; i++) {
16258                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16259                        if (childInfo != null) {
16260                            childInfo.removedForAllUsers = mPackages.get(
16261                                    childInfo.removedPackage) == null;
16262                        }
16263                    }
16264                }
16265            }
16266            // If we uninstalled an update to a system app there may be some
16267            // child packages that appeared as they are declared in the system
16268            // app but were not declared in the update.
16269            if (isSystemApp(ps)) {
16270                synchronized (mPackages) {
16271                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16272                    final int childCount = (updatedPs.childPackageNames != null)
16273                            ? updatedPs.childPackageNames.size() : 0;
16274                    for (int i = 0; i < childCount; i++) {
16275                        String childPackageName = updatedPs.childPackageNames.get(i);
16276                        if (outInfo.removedChildPackages == null
16277                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16278                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16279                            if (childPs == null) {
16280                                continue;
16281                            }
16282                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16283                            installRes.name = childPackageName;
16284                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16285                            installRes.pkg = mPackages.get(childPackageName);
16286                            installRes.uid = childPs.pkg.applicationInfo.uid;
16287                            if (outInfo.appearedChildPackages == null) {
16288                                outInfo.appearedChildPackages = new ArrayMap<>();
16289                            }
16290                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16291                        }
16292                    }
16293                }
16294            }
16295        }
16296
16297        return ret;
16298    }
16299
16300    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16301        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16302                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16303        for (int nextUserId : userIds) {
16304            if (DEBUG_REMOVE) {
16305                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16306            }
16307            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16308                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16309                    false /*hidden*/, false /*suspended*/, null, null, null,
16310                    false /*blockUninstall*/,
16311                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16312        }
16313    }
16314
16315    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16316            PackageRemovedInfo outInfo) {
16317        final PackageParser.Package pkg;
16318        synchronized (mPackages) {
16319            pkg = mPackages.get(ps.name);
16320        }
16321
16322        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16323                : new int[] {userId};
16324        for (int nextUserId : userIds) {
16325            if (DEBUG_REMOVE) {
16326                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16327                        + nextUserId);
16328            }
16329
16330            destroyAppDataLIF(pkg, userId,
16331                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16332            destroyAppProfilesLIF(pkg, userId);
16333            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16334            schedulePackageCleaning(ps.name, nextUserId, false);
16335            synchronized (mPackages) {
16336                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16337                    scheduleWritePackageRestrictionsLocked(nextUserId);
16338                }
16339                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16340            }
16341        }
16342
16343        if (outInfo != null) {
16344            outInfo.removedPackage = ps.name;
16345            outInfo.removedAppId = ps.appId;
16346            outInfo.removedUsers = userIds;
16347        }
16348
16349        return true;
16350    }
16351
16352    private final class ClearStorageConnection implements ServiceConnection {
16353        IMediaContainerService mContainerService;
16354
16355        @Override
16356        public void onServiceConnected(ComponentName name, IBinder service) {
16357            synchronized (this) {
16358                mContainerService = IMediaContainerService.Stub.asInterface(service);
16359                notifyAll();
16360            }
16361        }
16362
16363        @Override
16364        public void onServiceDisconnected(ComponentName name) {
16365        }
16366    }
16367
16368    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16369        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16370
16371        final boolean mounted;
16372        if (Environment.isExternalStorageEmulated()) {
16373            mounted = true;
16374        } else {
16375            final String status = Environment.getExternalStorageState();
16376
16377            mounted = status.equals(Environment.MEDIA_MOUNTED)
16378                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16379        }
16380
16381        if (!mounted) {
16382            return;
16383        }
16384
16385        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16386        int[] users;
16387        if (userId == UserHandle.USER_ALL) {
16388            users = sUserManager.getUserIds();
16389        } else {
16390            users = new int[] { userId };
16391        }
16392        final ClearStorageConnection conn = new ClearStorageConnection();
16393        if (mContext.bindServiceAsUser(
16394                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16395            try {
16396                for (int curUser : users) {
16397                    long timeout = SystemClock.uptimeMillis() + 5000;
16398                    synchronized (conn) {
16399                        long now;
16400                        while (conn.mContainerService == null &&
16401                                (now = SystemClock.uptimeMillis()) < timeout) {
16402                            try {
16403                                conn.wait(timeout - now);
16404                            } catch (InterruptedException e) {
16405                            }
16406                        }
16407                    }
16408                    if (conn.mContainerService == null) {
16409                        return;
16410                    }
16411
16412                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16413                    clearDirectory(conn.mContainerService,
16414                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16415                    if (allData) {
16416                        clearDirectory(conn.mContainerService,
16417                                userEnv.buildExternalStorageAppDataDirs(packageName));
16418                        clearDirectory(conn.mContainerService,
16419                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16420                    }
16421                }
16422            } finally {
16423                mContext.unbindService(conn);
16424            }
16425        }
16426    }
16427
16428    @Override
16429    public void clearApplicationProfileData(String packageName) {
16430        enforceSystemOrRoot("Only the system can clear all profile data");
16431
16432        final PackageParser.Package pkg;
16433        synchronized (mPackages) {
16434            pkg = mPackages.get(packageName);
16435        }
16436
16437        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16438            synchronized (mInstallLock) {
16439                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16440                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16441                        true /* removeBaseMarker */);
16442            }
16443        }
16444    }
16445
16446    @Override
16447    public void clearApplicationUserData(final String packageName,
16448            final IPackageDataObserver observer, final int userId) {
16449        mContext.enforceCallingOrSelfPermission(
16450                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16451
16452        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16453                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16454
16455        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16456            throw new SecurityException("Cannot clear data for a protected package: "
16457                    + packageName);
16458        }
16459        // Queue up an async operation since the package deletion may take a little while.
16460        mHandler.post(new Runnable() {
16461            public void run() {
16462                mHandler.removeCallbacks(this);
16463                final boolean succeeded;
16464                try (PackageFreezer freezer = freezePackage(packageName,
16465                        "clearApplicationUserData")) {
16466                    synchronized (mInstallLock) {
16467                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16468                    }
16469                    clearExternalStorageDataSync(packageName, userId, true);
16470                }
16471                if (succeeded) {
16472                    // invoke DeviceStorageMonitor's update method to clear any notifications
16473                    DeviceStorageMonitorInternal dsm = LocalServices
16474                            .getService(DeviceStorageMonitorInternal.class);
16475                    if (dsm != null) {
16476                        dsm.checkMemory();
16477                    }
16478                }
16479                if(observer != null) {
16480                    try {
16481                        observer.onRemoveCompleted(packageName, succeeded);
16482                    } catch (RemoteException e) {
16483                        Log.i(TAG, "Observer no longer exists.");
16484                    }
16485                } //end if observer
16486            } //end run
16487        });
16488    }
16489
16490    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16491        if (packageName == null) {
16492            Slog.w(TAG, "Attempt to delete null packageName.");
16493            return false;
16494        }
16495
16496        // Try finding details about the requested package
16497        PackageParser.Package pkg;
16498        synchronized (mPackages) {
16499            pkg = mPackages.get(packageName);
16500            if (pkg == null) {
16501                final PackageSetting ps = mSettings.mPackages.get(packageName);
16502                if (ps != null) {
16503                    pkg = ps.pkg;
16504                }
16505            }
16506
16507            if (pkg == null) {
16508                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16509                return false;
16510            }
16511
16512            PackageSetting ps = (PackageSetting) pkg.mExtras;
16513            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16514        }
16515
16516        clearAppDataLIF(pkg, userId,
16517                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16518
16519        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16520        removeKeystoreDataIfNeeded(userId, appId);
16521
16522        UserManagerInternal umInternal = getUserManagerInternal();
16523        final int flags;
16524        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16525            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16526        } else if (umInternal.isUserRunning(userId)) {
16527            flags = StorageManager.FLAG_STORAGE_DE;
16528        } else {
16529            flags = 0;
16530        }
16531        prepareAppDataContentsLIF(pkg, userId, flags);
16532
16533        return true;
16534    }
16535
16536    /**
16537     * Reverts user permission state changes (permissions and flags) in
16538     * all packages for a given user.
16539     *
16540     * @param userId The device user for which to do a reset.
16541     */
16542    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16543        final int packageCount = mPackages.size();
16544        for (int i = 0; i < packageCount; i++) {
16545            PackageParser.Package pkg = mPackages.valueAt(i);
16546            PackageSetting ps = (PackageSetting) pkg.mExtras;
16547            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16548        }
16549    }
16550
16551    private void resetNetworkPolicies(int userId) {
16552        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16553    }
16554
16555    /**
16556     * Reverts user permission state changes (permissions and flags).
16557     *
16558     * @param ps The package for which to reset.
16559     * @param userId The device user for which to do a reset.
16560     */
16561    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16562            final PackageSetting ps, final int userId) {
16563        if (ps.pkg == null) {
16564            return;
16565        }
16566
16567        // These are flags that can change base on user actions.
16568        final int userSettableMask = FLAG_PERMISSION_USER_SET
16569                | FLAG_PERMISSION_USER_FIXED
16570                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16571                | FLAG_PERMISSION_REVIEW_REQUIRED;
16572
16573        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16574                | FLAG_PERMISSION_POLICY_FIXED;
16575
16576        boolean writeInstallPermissions = false;
16577        boolean writeRuntimePermissions = false;
16578
16579        final int permissionCount = ps.pkg.requestedPermissions.size();
16580        for (int i = 0; i < permissionCount; i++) {
16581            String permission = ps.pkg.requestedPermissions.get(i);
16582
16583            BasePermission bp = mSettings.mPermissions.get(permission);
16584            if (bp == null) {
16585                continue;
16586            }
16587
16588            // If shared user we just reset the state to which only this app contributed.
16589            if (ps.sharedUser != null) {
16590                boolean used = false;
16591                final int packageCount = ps.sharedUser.packages.size();
16592                for (int j = 0; j < packageCount; j++) {
16593                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16594                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16595                            && pkg.pkg.requestedPermissions.contains(permission)) {
16596                        used = true;
16597                        break;
16598                    }
16599                }
16600                if (used) {
16601                    continue;
16602                }
16603            }
16604
16605            PermissionsState permissionsState = ps.getPermissionsState();
16606
16607            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16608
16609            // Always clear the user settable flags.
16610            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16611                    bp.name) != null;
16612            // If permission review is enabled and this is a legacy app, mark the
16613            // permission as requiring a review as this is the initial state.
16614            int flags = 0;
16615            if (Build.PERMISSIONS_REVIEW_REQUIRED
16616                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16617                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16618            }
16619            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16620                if (hasInstallState) {
16621                    writeInstallPermissions = true;
16622                } else {
16623                    writeRuntimePermissions = true;
16624                }
16625            }
16626
16627            // Below is only runtime permission handling.
16628            if (!bp.isRuntime()) {
16629                continue;
16630            }
16631
16632            // Never clobber system or policy.
16633            if ((oldFlags & policyOrSystemFlags) != 0) {
16634                continue;
16635            }
16636
16637            // If this permission was granted by default, make sure it is.
16638            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16639                if (permissionsState.grantRuntimePermission(bp, userId)
16640                        != PERMISSION_OPERATION_FAILURE) {
16641                    writeRuntimePermissions = true;
16642                }
16643            // If permission review is enabled the permissions for a legacy apps
16644            // are represented as constantly granted runtime ones, so don't revoke.
16645            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16646                // Otherwise, reset the permission.
16647                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16648                switch (revokeResult) {
16649                    case PERMISSION_OPERATION_SUCCESS:
16650                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16651                        writeRuntimePermissions = true;
16652                        final int appId = ps.appId;
16653                        mHandler.post(new Runnable() {
16654                            @Override
16655                            public void run() {
16656                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16657                            }
16658                        });
16659                    } break;
16660                }
16661            }
16662        }
16663
16664        // Synchronously write as we are taking permissions away.
16665        if (writeRuntimePermissions) {
16666            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16667        }
16668
16669        // Synchronously write as we are taking permissions away.
16670        if (writeInstallPermissions) {
16671            mSettings.writeLPr();
16672        }
16673    }
16674
16675    /**
16676     * Remove entries from the keystore daemon. Will only remove it if the
16677     * {@code appId} is valid.
16678     */
16679    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16680        if (appId < 0) {
16681            return;
16682        }
16683
16684        final KeyStore keyStore = KeyStore.getInstance();
16685        if (keyStore != null) {
16686            if (userId == UserHandle.USER_ALL) {
16687                for (final int individual : sUserManager.getUserIds()) {
16688                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16689                }
16690            } else {
16691                keyStore.clearUid(UserHandle.getUid(userId, appId));
16692            }
16693        } else {
16694            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16695        }
16696    }
16697
16698    @Override
16699    public void deleteApplicationCacheFiles(final String packageName,
16700            final IPackageDataObserver observer) {
16701        final int userId = UserHandle.getCallingUserId();
16702        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16703    }
16704
16705    @Override
16706    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16707            final IPackageDataObserver observer) {
16708        mContext.enforceCallingOrSelfPermission(
16709                android.Manifest.permission.DELETE_CACHE_FILES, null);
16710        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16711                /* requireFullPermission= */ true, /* checkShell= */ false,
16712                "delete application cache files");
16713
16714        final PackageParser.Package pkg;
16715        synchronized (mPackages) {
16716            pkg = mPackages.get(packageName);
16717        }
16718
16719        // Queue up an async operation since the package deletion may take a little while.
16720        mHandler.post(new Runnable() {
16721            public void run() {
16722                synchronized (mInstallLock) {
16723                    final int flags = StorageManager.FLAG_STORAGE_DE
16724                            | StorageManager.FLAG_STORAGE_CE;
16725                    // We're only clearing cache files, so we don't care if the
16726                    // app is unfrozen and still able to run
16727                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16728                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16729                }
16730                clearExternalStorageDataSync(packageName, userId, false);
16731                if (observer != null) {
16732                    try {
16733                        observer.onRemoveCompleted(packageName, true);
16734                    } catch (RemoteException e) {
16735                        Log.i(TAG, "Observer no longer exists.");
16736                    }
16737                }
16738            }
16739        });
16740    }
16741
16742    @Override
16743    public void getPackageSizeInfo(final String packageName, int userHandle,
16744            final IPackageStatsObserver observer) {
16745        mContext.enforceCallingOrSelfPermission(
16746                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16747        if (packageName == null) {
16748            throw new IllegalArgumentException("Attempt to get size of null packageName");
16749        }
16750
16751        PackageStats stats = new PackageStats(packageName, userHandle);
16752
16753        /*
16754         * Queue up an async operation since the package measurement may take a
16755         * little while.
16756         */
16757        Message msg = mHandler.obtainMessage(INIT_COPY);
16758        msg.obj = new MeasureParams(stats, observer);
16759        mHandler.sendMessage(msg);
16760    }
16761
16762    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16763        final PackageSetting ps;
16764        synchronized (mPackages) {
16765            ps = mSettings.mPackages.get(packageName);
16766            if (ps == null) {
16767                Slog.w(TAG, "Failed to find settings for " + packageName);
16768                return false;
16769            }
16770        }
16771        try {
16772            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16773                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16774                    ps.getCeDataInode(userId), ps.codePathString, stats);
16775        } catch (InstallerException e) {
16776            Slog.w(TAG, String.valueOf(e));
16777            return false;
16778        }
16779
16780        // For now, ignore code size of packages on system partition
16781        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16782            stats.codeSize = 0;
16783        }
16784
16785        return true;
16786    }
16787
16788    private int getUidTargetSdkVersionLockedLPr(int uid) {
16789        Object obj = mSettings.getUserIdLPr(uid);
16790        if (obj instanceof SharedUserSetting) {
16791            final SharedUserSetting sus = (SharedUserSetting) obj;
16792            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16793            final Iterator<PackageSetting> it = sus.packages.iterator();
16794            while (it.hasNext()) {
16795                final PackageSetting ps = it.next();
16796                if (ps.pkg != null) {
16797                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16798                    if (v < vers) vers = v;
16799                }
16800            }
16801            return vers;
16802        } else if (obj instanceof PackageSetting) {
16803            final PackageSetting ps = (PackageSetting) obj;
16804            if (ps.pkg != null) {
16805                return ps.pkg.applicationInfo.targetSdkVersion;
16806            }
16807        }
16808        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16809    }
16810
16811    @Override
16812    public void addPreferredActivity(IntentFilter filter, int match,
16813            ComponentName[] set, ComponentName activity, int userId) {
16814        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16815                "Adding preferred");
16816    }
16817
16818    private void addPreferredActivityInternal(IntentFilter filter, int match,
16819            ComponentName[] set, ComponentName activity, boolean always, int userId,
16820            String opname) {
16821        // writer
16822        int callingUid = Binder.getCallingUid();
16823        enforceCrossUserPermission(callingUid, userId,
16824                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16825        if (filter.countActions() == 0) {
16826            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16827            return;
16828        }
16829        synchronized (mPackages) {
16830            if (mContext.checkCallingOrSelfPermission(
16831                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16832                    != PackageManager.PERMISSION_GRANTED) {
16833                if (getUidTargetSdkVersionLockedLPr(callingUid)
16834                        < Build.VERSION_CODES.FROYO) {
16835                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16836                            + callingUid);
16837                    return;
16838                }
16839                mContext.enforceCallingOrSelfPermission(
16840                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16841            }
16842
16843            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16844            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16845                    + userId + ":");
16846            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16847            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16848            scheduleWritePackageRestrictionsLocked(userId);
16849            postPreferredActivityChangedBroadcast(userId);
16850        }
16851    }
16852
16853    private void postPreferredActivityChangedBroadcast(int userId) {
16854        mHandler.post(() -> {
16855            final IActivityManager am = ActivityManagerNative.getDefault();
16856            if (am == null) {
16857                return;
16858            }
16859
16860            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16861            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16862            try {
16863                am.broadcastIntent(null, intent, null, null,
16864                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
16865                        null, false, false, userId);
16866            } catch (RemoteException e) {
16867            }
16868        });
16869    }
16870
16871    @Override
16872    public void replacePreferredActivity(IntentFilter filter, int match,
16873            ComponentName[] set, ComponentName activity, int userId) {
16874        if (filter.countActions() != 1) {
16875            throw new IllegalArgumentException(
16876                    "replacePreferredActivity expects filter to have only 1 action.");
16877        }
16878        if (filter.countDataAuthorities() != 0
16879                || filter.countDataPaths() != 0
16880                || filter.countDataSchemes() > 1
16881                || filter.countDataTypes() != 0) {
16882            throw new IllegalArgumentException(
16883                    "replacePreferredActivity expects filter to have no data authorities, " +
16884                    "paths, or types; and at most one scheme.");
16885        }
16886
16887        final int callingUid = Binder.getCallingUid();
16888        enforceCrossUserPermission(callingUid, userId,
16889                true /* requireFullPermission */, false /* checkShell */,
16890                "replace preferred activity");
16891        synchronized (mPackages) {
16892            if (mContext.checkCallingOrSelfPermission(
16893                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16894                    != PackageManager.PERMISSION_GRANTED) {
16895                if (getUidTargetSdkVersionLockedLPr(callingUid)
16896                        < Build.VERSION_CODES.FROYO) {
16897                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16898                            + Binder.getCallingUid());
16899                    return;
16900                }
16901                mContext.enforceCallingOrSelfPermission(
16902                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16903            }
16904
16905            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16906            if (pir != null) {
16907                // Get all of the existing entries that exactly match this filter.
16908                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16909                if (existing != null && existing.size() == 1) {
16910                    PreferredActivity cur = existing.get(0);
16911                    if (DEBUG_PREFERRED) {
16912                        Slog.i(TAG, "Checking replace of preferred:");
16913                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16914                        if (!cur.mPref.mAlways) {
16915                            Slog.i(TAG, "  -- CUR; not mAlways!");
16916                        } else {
16917                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16918                            Slog.i(TAG, "  -- CUR: mSet="
16919                                    + Arrays.toString(cur.mPref.mSetComponents));
16920                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16921                            Slog.i(TAG, "  -- NEW: mMatch="
16922                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16923                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16924                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16925                        }
16926                    }
16927                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16928                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16929                            && cur.mPref.sameSet(set)) {
16930                        // Setting the preferred activity to what it happens to be already
16931                        if (DEBUG_PREFERRED) {
16932                            Slog.i(TAG, "Replacing with same preferred activity "
16933                                    + cur.mPref.mShortComponent + " for user "
16934                                    + userId + ":");
16935                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16936                        }
16937                        return;
16938                    }
16939                }
16940
16941                if (existing != null) {
16942                    if (DEBUG_PREFERRED) {
16943                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16944                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16945                    }
16946                    for (int i = 0; i < existing.size(); i++) {
16947                        PreferredActivity pa = existing.get(i);
16948                        if (DEBUG_PREFERRED) {
16949                            Slog.i(TAG, "Removing existing preferred activity "
16950                                    + pa.mPref.mComponent + ":");
16951                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16952                        }
16953                        pir.removeFilter(pa);
16954                    }
16955                }
16956            }
16957            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16958                    "Replacing preferred");
16959        }
16960    }
16961
16962    @Override
16963    public void clearPackagePreferredActivities(String packageName) {
16964        final int uid = Binder.getCallingUid();
16965        // writer
16966        synchronized (mPackages) {
16967            PackageParser.Package pkg = mPackages.get(packageName);
16968            if (pkg == null || pkg.applicationInfo.uid != uid) {
16969                if (mContext.checkCallingOrSelfPermission(
16970                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16971                        != PackageManager.PERMISSION_GRANTED) {
16972                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16973                            < Build.VERSION_CODES.FROYO) {
16974                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16975                                + Binder.getCallingUid());
16976                        return;
16977                    }
16978                    mContext.enforceCallingOrSelfPermission(
16979                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16980                }
16981            }
16982
16983            int user = UserHandle.getCallingUserId();
16984            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16985                scheduleWritePackageRestrictionsLocked(user);
16986            }
16987        }
16988    }
16989
16990    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16991    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16992        ArrayList<PreferredActivity> removed = null;
16993        boolean changed = false;
16994        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16995            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16996            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16997            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16998                continue;
16999            }
17000            Iterator<PreferredActivity> it = pir.filterIterator();
17001            while (it.hasNext()) {
17002                PreferredActivity pa = it.next();
17003                // Mark entry for removal only if it matches the package name
17004                // and the entry is of type "always".
17005                if (packageName == null ||
17006                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17007                                && pa.mPref.mAlways)) {
17008                    if (removed == null) {
17009                        removed = new ArrayList<PreferredActivity>();
17010                    }
17011                    removed.add(pa);
17012                }
17013            }
17014            if (removed != null) {
17015                for (int j=0; j<removed.size(); j++) {
17016                    PreferredActivity pa = removed.get(j);
17017                    pir.removeFilter(pa);
17018                }
17019                changed = true;
17020            }
17021        }
17022        if (changed) {
17023            postPreferredActivityChangedBroadcast(userId);
17024        }
17025        return changed;
17026    }
17027
17028    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17029    private void clearIntentFilterVerificationsLPw(int userId) {
17030        final int packageCount = mPackages.size();
17031        for (int i = 0; i < packageCount; i++) {
17032            PackageParser.Package pkg = mPackages.valueAt(i);
17033            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17034        }
17035    }
17036
17037    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17038    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17039        if (userId == UserHandle.USER_ALL) {
17040            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17041                    sUserManager.getUserIds())) {
17042                for (int oneUserId : sUserManager.getUserIds()) {
17043                    scheduleWritePackageRestrictionsLocked(oneUserId);
17044                }
17045            }
17046        } else {
17047            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17048                scheduleWritePackageRestrictionsLocked(userId);
17049            }
17050        }
17051    }
17052
17053    void clearDefaultBrowserIfNeeded(String packageName) {
17054        for (int oneUserId : sUserManager.getUserIds()) {
17055            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17056            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17057            if (packageName.equals(defaultBrowserPackageName)) {
17058                setDefaultBrowserPackageName(null, oneUserId);
17059            }
17060        }
17061    }
17062
17063    @Override
17064    public void resetApplicationPreferences(int userId) {
17065        mContext.enforceCallingOrSelfPermission(
17066                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17067        final long identity = Binder.clearCallingIdentity();
17068        // writer
17069        try {
17070            synchronized (mPackages) {
17071                clearPackagePreferredActivitiesLPw(null, userId);
17072                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17073                // TODO: We have to reset the default SMS and Phone. This requires
17074                // significant refactoring to keep all default apps in the package
17075                // manager (cleaner but more work) or have the services provide
17076                // callbacks to the package manager to request a default app reset.
17077                applyFactoryDefaultBrowserLPw(userId);
17078                clearIntentFilterVerificationsLPw(userId);
17079                primeDomainVerificationsLPw(userId);
17080                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17081                scheduleWritePackageRestrictionsLocked(userId);
17082            }
17083            resetNetworkPolicies(userId);
17084        } finally {
17085            Binder.restoreCallingIdentity(identity);
17086        }
17087    }
17088
17089    @Override
17090    public int getPreferredActivities(List<IntentFilter> outFilters,
17091            List<ComponentName> outActivities, String packageName) {
17092
17093        int num = 0;
17094        final int userId = UserHandle.getCallingUserId();
17095        // reader
17096        synchronized (mPackages) {
17097            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17098            if (pir != null) {
17099                final Iterator<PreferredActivity> it = pir.filterIterator();
17100                while (it.hasNext()) {
17101                    final PreferredActivity pa = it.next();
17102                    if (packageName == null
17103                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17104                                    && pa.mPref.mAlways)) {
17105                        if (outFilters != null) {
17106                            outFilters.add(new IntentFilter(pa));
17107                        }
17108                        if (outActivities != null) {
17109                            outActivities.add(pa.mPref.mComponent);
17110                        }
17111                    }
17112                }
17113            }
17114        }
17115
17116        return num;
17117    }
17118
17119    @Override
17120    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17121            int userId) {
17122        int callingUid = Binder.getCallingUid();
17123        if (callingUid != Process.SYSTEM_UID) {
17124            throw new SecurityException(
17125                    "addPersistentPreferredActivity can only be run by the system");
17126        }
17127        if (filter.countActions() == 0) {
17128            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17129            return;
17130        }
17131        synchronized (mPackages) {
17132            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17133                    ":");
17134            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17135            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17136                    new PersistentPreferredActivity(filter, activity));
17137            scheduleWritePackageRestrictionsLocked(userId);
17138            postPreferredActivityChangedBroadcast(userId);
17139        }
17140    }
17141
17142    @Override
17143    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17144        int callingUid = Binder.getCallingUid();
17145        if (callingUid != Process.SYSTEM_UID) {
17146            throw new SecurityException(
17147                    "clearPackagePersistentPreferredActivities can only be run by the system");
17148        }
17149        ArrayList<PersistentPreferredActivity> removed = null;
17150        boolean changed = false;
17151        synchronized (mPackages) {
17152            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17153                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17154                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17155                        .valueAt(i);
17156                if (userId != thisUserId) {
17157                    continue;
17158                }
17159                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17160                while (it.hasNext()) {
17161                    PersistentPreferredActivity ppa = it.next();
17162                    // Mark entry for removal only if it matches the package name.
17163                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17164                        if (removed == null) {
17165                            removed = new ArrayList<PersistentPreferredActivity>();
17166                        }
17167                        removed.add(ppa);
17168                    }
17169                }
17170                if (removed != null) {
17171                    for (int j=0; j<removed.size(); j++) {
17172                        PersistentPreferredActivity ppa = removed.get(j);
17173                        ppir.removeFilter(ppa);
17174                    }
17175                    changed = true;
17176                }
17177            }
17178
17179            if (changed) {
17180                scheduleWritePackageRestrictionsLocked(userId);
17181                postPreferredActivityChangedBroadcast(userId);
17182            }
17183        }
17184    }
17185
17186    /**
17187     * Common machinery for picking apart a restored XML blob and passing
17188     * it to a caller-supplied functor to be applied to the running system.
17189     */
17190    private void restoreFromXml(XmlPullParser parser, int userId,
17191            String expectedStartTag, BlobXmlRestorer functor)
17192            throws IOException, XmlPullParserException {
17193        int type;
17194        while ((type = parser.next()) != XmlPullParser.START_TAG
17195                && type != XmlPullParser.END_DOCUMENT) {
17196        }
17197        if (type != XmlPullParser.START_TAG) {
17198            // oops didn't find a start tag?!
17199            if (DEBUG_BACKUP) {
17200                Slog.e(TAG, "Didn't find start tag during restore");
17201            }
17202            return;
17203        }
17204Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17205        // this is supposed to be TAG_PREFERRED_BACKUP
17206        if (!expectedStartTag.equals(parser.getName())) {
17207            if (DEBUG_BACKUP) {
17208                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17209            }
17210            return;
17211        }
17212
17213        // skip interfering stuff, then we're aligned with the backing implementation
17214        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17215Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17216        functor.apply(parser, userId);
17217    }
17218
17219    private interface BlobXmlRestorer {
17220        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17221    }
17222
17223    /**
17224     * Non-Binder method, support for the backup/restore mechanism: write the
17225     * full set of preferred activities in its canonical XML format.  Returns the
17226     * XML output as a byte array, or null if there is none.
17227     */
17228    @Override
17229    public byte[] getPreferredActivityBackup(int userId) {
17230        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17231            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17232        }
17233
17234        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17235        try {
17236            final XmlSerializer serializer = new FastXmlSerializer();
17237            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17238            serializer.startDocument(null, true);
17239            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17240
17241            synchronized (mPackages) {
17242                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17243            }
17244
17245            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17246            serializer.endDocument();
17247            serializer.flush();
17248        } catch (Exception e) {
17249            if (DEBUG_BACKUP) {
17250                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17251            }
17252            return null;
17253        }
17254
17255        return dataStream.toByteArray();
17256    }
17257
17258    @Override
17259    public void restorePreferredActivities(byte[] backup, int userId) {
17260        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17261            throw new SecurityException("Only the system may call restorePreferredActivities()");
17262        }
17263
17264        try {
17265            final XmlPullParser parser = Xml.newPullParser();
17266            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17267            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17268                    new BlobXmlRestorer() {
17269                        @Override
17270                        public void apply(XmlPullParser parser, int userId)
17271                                throws XmlPullParserException, IOException {
17272                            synchronized (mPackages) {
17273                                mSettings.readPreferredActivitiesLPw(parser, userId);
17274                            }
17275                        }
17276                    } );
17277        } catch (Exception e) {
17278            if (DEBUG_BACKUP) {
17279                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17280            }
17281        }
17282    }
17283
17284    /**
17285     * Non-Binder method, support for the backup/restore mechanism: write the
17286     * default browser (etc) settings in its canonical XML format.  Returns the default
17287     * browser XML representation as a byte array, or null if there is none.
17288     */
17289    @Override
17290    public byte[] getDefaultAppsBackup(int userId) {
17291        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17292            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17293        }
17294
17295        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17296        try {
17297            final XmlSerializer serializer = new FastXmlSerializer();
17298            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17299            serializer.startDocument(null, true);
17300            serializer.startTag(null, TAG_DEFAULT_APPS);
17301
17302            synchronized (mPackages) {
17303                mSettings.writeDefaultAppsLPr(serializer, userId);
17304            }
17305
17306            serializer.endTag(null, TAG_DEFAULT_APPS);
17307            serializer.endDocument();
17308            serializer.flush();
17309        } catch (Exception e) {
17310            if (DEBUG_BACKUP) {
17311                Slog.e(TAG, "Unable to write default apps for backup", e);
17312            }
17313            return null;
17314        }
17315
17316        return dataStream.toByteArray();
17317    }
17318
17319    @Override
17320    public void restoreDefaultApps(byte[] backup, int userId) {
17321        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17322            throw new SecurityException("Only the system may call restoreDefaultApps()");
17323        }
17324
17325        try {
17326            final XmlPullParser parser = Xml.newPullParser();
17327            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17328            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17329                    new BlobXmlRestorer() {
17330                        @Override
17331                        public void apply(XmlPullParser parser, int userId)
17332                                throws XmlPullParserException, IOException {
17333                            synchronized (mPackages) {
17334                                mSettings.readDefaultAppsLPw(parser, userId);
17335                            }
17336                        }
17337                    } );
17338        } catch (Exception e) {
17339            if (DEBUG_BACKUP) {
17340                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17341            }
17342        }
17343    }
17344
17345    @Override
17346    public byte[] getIntentFilterVerificationBackup(int userId) {
17347        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17348            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17349        }
17350
17351        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17352        try {
17353            final XmlSerializer serializer = new FastXmlSerializer();
17354            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17355            serializer.startDocument(null, true);
17356            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17357
17358            synchronized (mPackages) {
17359                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17360            }
17361
17362            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17363            serializer.endDocument();
17364            serializer.flush();
17365        } catch (Exception e) {
17366            if (DEBUG_BACKUP) {
17367                Slog.e(TAG, "Unable to write default apps for backup", e);
17368            }
17369            return null;
17370        }
17371
17372        return dataStream.toByteArray();
17373    }
17374
17375    @Override
17376    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17377        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17378            throw new SecurityException("Only the system may call restorePreferredActivities()");
17379        }
17380
17381        try {
17382            final XmlPullParser parser = Xml.newPullParser();
17383            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17384            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17385                    new BlobXmlRestorer() {
17386                        @Override
17387                        public void apply(XmlPullParser parser, int userId)
17388                                throws XmlPullParserException, IOException {
17389                            synchronized (mPackages) {
17390                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17391                                mSettings.writeLPr();
17392                            }
17393                        }
17394                    } );
17395        } catch (Exception e) {
17396            if (DEBUG_BACKUP) {
17397                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17398            }
17399        }
17400    }
17401
17402    @Override
17403    public byte[] getPermissionGrantBackup(int userId) {
17404        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17405            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17406        }
17407
17408        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17409        try {
17410            final XmlSerializer serializer = new FastXmlSerializer();
17411            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17412            serializer.startDocument(null, true);
17413            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17414
17415            synchronized (mPackages) {
17416                serializeRuntimePermissionGrantsLPr(serializer, userId);
17417            }
17418
17419            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17420            serializer.endDocument();
17421            serializer.flush();
17422        } catch (Exception e) {
17423            if (DEBUG_BACKUP) {
17424                Slog.e(TAG, "Unable to write default apps for backup", e);
17425            }
17426            return null;
17427        }
17428
17429        return dataStream.toByteArray();
17430    }
17431
17432    @Override
17433    public void restorePermissionGrants(byte[] backup, int userId) {
17434        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17435            throw new SecurityException("Only the system may call restorePermissionGrants()");
17436        }
17437
17438        try {
17439            final XmlPullParser parser = Xml.newPullParser();
17440            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17441            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17442                    new BlobXmlRestorer() {
17443                        @Override
17444                        public void apply(XmlPullParser parser, int userId)
17445                                throws XmlPullParserException, IOException {
17446                            synchronized (mPackages) {
17447                                processRestoredPermissionGrantsLPr(parser, userId);
17448                            }
17449                        }
17450                    } );
17451        } catch (Exception e) {
17452            if (DEBUG_BACKUP) {
17453                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17454            }
17455        }
17456    }
17457
17458    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17459            throws IOException {
17460        serializer.startTag(null, TAG_ALL_GRANTS);
17461
17462        final int N = mSettings.mPackages.size();
17463        for (int i = 0; i < N; i++) {
17464            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17465            boolean pkgGrantsKnown = false;
17466
17467            PermissionsState packagePerms = ps.getPermissionsState();
17468
17469            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17470                final int grantFlags = state.getFlags();
17471                // only look at grants that are not system/policy fixed
17472                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17473                    final boolean isGranted = state.isGranted();
17474                    // And only back up the user-twiddled state bits
17475                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17476                        final String packageName = mSettings.mPackages.keyAt(i);
17477                        if (!pkgGrantsKnown) {
17478                            serializer.startTag(null, TAG_GRANT);
17479                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17480                            pkgGrantsKnown = true;
17481                        }
17482
17483                        final boolean userSet =
17484                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17485                        final boolean userFixed =
17486                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17487                        final boolean revoke =
17488                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17489
17490                        serializer.startTag(null, TAG_PERMISSION);
17491                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17492                        if (isGranted) {
17493                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17494                        }
17495                        if (userSet) {
17496                            serializer.attribute(null, ATTR_USER_SET, "true");
17497                        }
17498                        if (userFixed) {
17499                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17500                        }
17501                        if (revoke) {
17502                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17503                        }
17504                        serializer.endTag(null, TAG_PERMISSION);
17505                    }
17506                }
17507            }
17508
17509            if (pkgGrantsKnown) {
17510                serializer.endTag(null, TAG_GRANT);
17511            }
17512        }
17513
17514        serializer.endTag(null, TAG_ALL_GRANTS);
17515    }
17516
17517    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17518            throws XmlPullParserException, IOException {
17519        String pkgName = null;
17520        int outerDepth = parser.getDepth();
17521        int type;
17522        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17523                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17524            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17525                continue;
17526            }
17527
17528            final String tagName = parser.getName();
17529            if (tagName.equals(TAG_GRANT)) {
17530                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17531                if (DEBUG_BACKUP) {
17532                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17533                }
17534            } else if (tagName.equals(TAG_PERMISSION)) {
17535
17536                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17537                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17538
17539                int newFlagSet = 0;
17540                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17541                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17542                }
17543                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17544                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17545                }
17546                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17547                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17548                }
17549                if (DEBUG_BACKUP) {
17550                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17551                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17552                }
17553                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17554                if (ps != null) {
17555                    // Already installed so we apply the grant immediately
17556                    if (DEBUG_BACKUP) {
17557                        Slog.v(TAG, "        + already installed; applying");
17558                    }
17559                    PermissionsState perms = ps.getPermissionsState();
17560                    BasePermission bp = mSettings.mPermissions.get(permName);
17561                    if (bp != null) {
17562                        if (isGranted) {
17563                            perms.grantRuntimePermission(bp, userId);
17564                        }
17565                        if (newFlagSet != 0) {
17566                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17567                        }
17568                    }
17569                } else {
17570                    // Need to wait for post-restore install to apply the grant
17571                    if (DEBUG_BACKUP) {
17572                        Slog.v(TAG, "        - not yet installed; saving for later");
17573                    }
17574                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17575                            isGranted, newFlagSet, userId);
17576                }
17577            } else {
17578                PackageManagerService.reportSettingsProblem(Log.WARN,
17579                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17580                XmlUtils.skipCurrentTag(parser);
17581            }
17582        }
17583
17584        scheduleWriteSettingsLocked();
17585        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17586    }
17587
17588    @Override
17589    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17590            int sourceUserId, int targetUserId, int flags) {
17591        mContext.enforceCallingOrSelfPermission(
17592                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17593        int callingUid = Binder.getCallingUid();
17594        enforceOwnerRights(ownerPackage, callingUid);
17595        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17596        if (intentFilter.countActions() == 0) {
17597            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17598            return;
17599        }
17600        synchronized (mPackages) {
17601            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17602                    ownerPackage, targetUserId, flags);
17603            CrossProfileIntentResolver resolver =
17604                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17605            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17606            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17607            if (existing != null) {
17608                int size = existing.size();
17609                for (int i = 0; i < size; i++) {
17610                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17611                        return;
17612                    }
17613                }
17614            }
17615            resolver.addFilter(newFilter);
17616            scheduleWritePackageRestrictionsLocked(sourceUserId);
17617        }
17618    }
17619
17620    @Override
17621    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17622        mContext.enforceCallingOrSelfPermission(
17623                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17624        int callingUid = Binder.getCallingUid();
17625        enforceOwnerRights(ownerPackage, callingUid);
17626        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17627        synchronized (mPackages) {
17628            CrossProfileIntentResolver resolver =
17629                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17630            ArraySet<CrossProfileIntentFilter> set =
17631                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17632            for (CrossProfileIntentFilter filter : set) {
17633                if (filter.getOwnerPackage().equals(ownerPackage)) {
17634                    resolver.removeFilter(filter);
17635                }
17636            }
17637            scheduleWritePackageRestrictionsLocked(sourceUserId);
17638        }
17639    }
17640
17641    // Enforcing that callingUid is owning pkg on userId
17642    private void enforceOwnerRights(String pkg, int callingUid) {
17643        // The system owns everything.
17644        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17645            return;
17646        }
17647        int callingUserId = UserHandle.getUserId(callingUid);
17648        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17649        if (pi == null) {
17650            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17651                    + callingUserId);
17652        }
17653        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17654            throw new SecurityException("Calling uid " + callingUid
17655                    + " does not own package " + pkg);
17656        }
17657    }
17658
17659    @Override
17660    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17661        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17662    }
17663
17664    private Intent getHomeIntent() {
17665        Intent intent = new Intent(Intent.ACTION_MAIN);
17666        intent.addCategory(Intent.CATEGORY_HOME);
17667        intent.addCategory(Intent.CATEGORY_DEFAULT);
17668        return intent;
17669    }
17670
17671    private IntentFilter getHomeFilter() {
17672        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17673        filter.addCategory(Intent.CATEGORY_HOME);
17674        filter.addCategory(Intent.CATEGORY_DEFAULT);
17675        return filter;
17676    }
17677
17678    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17679            int userId) {
17680        Intent intent  = getHomeIntent();
17681        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17682                PackageManager.GET_META_DATA, userId);
17683        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17684                true, false, false, userId);
17685
17686        allHomeCandidates.clear();
17687        if (list != null) {
17688            for (ResolveInfo ri : list) {
17689                allHomeCandidates.add(ri);
17690            }
17691        }
17692        return (preferred == null || preferred.activityInfo == null)
17693                ? null
17694                : new ComponentName(preferred.activityInfo.packageName,
17695                        preferred.activityInfo.name);
17696    }
17697
17698    @Override
17699    public void setHomeActivity(ComponentName comp, int userId) {
17700        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17701        getHomeActivitiesAsUser(homeActivities, userId);
17702
17703        boolean found = false;
17704
17705        final int size = homeActivities.size();
17706        final ComponentName[] set = new ComponentName[size];
17707        for (int i = 0; i < size; i++) {
17708            final ResolveInfo candidate = homeActivities.get(i);
17709            final ActivityInfo info = candidate.activityInfo;
17710            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17711            set[i] = activityName;
17712            if (!found && activityName.equals(comp)) {
17713                found = true;
17714            }
17715        }
17716        if (!found) {
17717            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17718                    + userId);
17719        }
17720        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17721                set, comp, userId);
17722    }
17723
17724    private @Nullable String getSetupWizardPackageName() {
17725        final Intent intent = new Intent(Intent.ACTION_MAIN);
17726        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17727
17728        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17729                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17730                        | MATCH_DISABLED_COMPONENTS,
17731                UserHandle.myUserId());
17732        if (matches.size() == 1) {
17733            return matches.get(0).getComponentInfo().packageName;
17734        } else {
17735            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17736                    + ": matches=" + matches);
17737            return null;
17738        }
17739    }
17740
17741    private @Nullable String getStorageManagerPackageName() {
17742        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17743
17744        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17745                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17746                        | MATCH_DISABLED_COMPONENTS,
17747                UserHandle.myUserId());
17748        if (matches.size() == 1) {
17749            return matches.get(0).getComponentInfo().packageName;
17750        } else {
17751            Slog.e(TAG, "There should probably be exactly one storage manager; found "
17752                    + matches.size() + ": matches=" + matches);
17753            return null;
17754        }
17755    }
17756
17757    @Override
17758    public void setApplicationEnabledSetting(String appPackageName,
17759            int newState, int flags, int userId, String callingPackage) {
17760        if (!sUserManager.exists(userId)) return;
17761        if (callingPackage == null) {
17762            callingPackage = Integer.toString(Binder.getCallingUid());
17763        }
17764        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17765    }
17766
17767    @Override
17768    public void setComponentEnabledSetting(ComponentName componentName,
17769            int newState, int flags, int userId) {
17770        if (!sUserManager.exists(userId)) return;
17771        setEnabledSetting(componentName.getPackageName(),
17772                componentName.getClassName(), newState, flags, userId, null);
17773    }
17774
17775    private void setEnabledSetting(final String packageName, String className, int newState,
17776            final int flags, int userId, String callingPackage) {
17777        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17778              || newState == COMPONENT_ENABLED_STATE_ENABLED
17779              || newState == COMPONENT_ENABLED_STATE_DISABLED
17780              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17781              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17782            throw new IllegalArgumentException("Invalid new component state: "
17783                    + newState);
17784        }
17785        PackageSetting pkgSetting;
17786        final int uid = Binder.getCallingUid();
17787        final int permission;
17788        if (uid == Process.SYSTEM_UID) {
17789            permission = PackageManager.PERMISSION_GRANTED;
17790        } else {
17791            permission = mContext.checkCallingOrSelfPermission(
17792                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17793        }
17794        enforceCrossUserPermission(uid, userId,
17795                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17796        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17797        boolean sendNow = false;
17798        boolean isApp = (className == null);
17799        String componentName = isApp ? packageName : className;
17800        int packageUid = -1;
17801        ArrayList<String> components;
17802
17803        // writer
17804        synchronized (mPackages) {
17805            pkgSetting = mSettings.mPackages.get(packageName);
17806            if (pkgSetting == null) {
17807                if (className == null) {
17808                    throw new IllegalArgumentException("Unknown package: " + packageName);
17809                }
17810                throw new IllegalArgumentException(
17811                        "Unknown component: " + packageName + "/" + className);
17812            }
17813        }
17814
17815        // Limit who can change which apps
17816        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17817            // Don't allow apps that don't have permission to modify other apps
17818            if (!allowedByPermission) {
17819                throw new SecurityException(
17820                        "Permission Denial: attempt to change component state from pid="
17821                        + Binder.getCallingPid()
17822                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17823            }
17824            // Don't allow changing protected packages.
17825            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17826                throw new SecurityException("Cannot disable a protected package: " + packageName);
17827            }
17828        }
17829
17830        synchronized (mPackages) {
17831            if (uid == Process.SHELL_UID) {
17832                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17833                int oldState = pkgSetting.getEnabled(userId);
17834                if (className == null
17835                    &&
17836                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17837                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17838                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17839                    &&
17840                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17841                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17842                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17843                    // ok
17844                } else {
17845                    throw new SecurityException(
17846                            "Shell cannot change component state for " + packageName + "/"
17847                            + className + " to " + newState);
17848                }
17849            }
17850            if (className == null) {
17851                // We're dealing with an application/package level state change
17852                if (pkgSetting.getEnabled(userId) == newState) {
17853                    // Nothing to do
17854                    return;
17855                }
17856                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17857                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17858                    // Don't care about who enables an app.
17859                    callingPackage = null;
17860                }
17861                pkgSetting.setEnabled(newState, userId, callingPackage);
17862                // pkgSetting.pkg.mSetEnabled = newState;
17863            } else {
17864                // We're dealing with a component level state change
17865                // First, verify that this is a valid class name.
17866                PackageParser.Package pkg = pkgSetting.pkg;
17867                if (pkg == null || !pkg.hasComponentClassName(className)) {
17868                    if (pkg != null &&
17869                            pkg.applicationInfo.targetSdkVersion >=
17870                                    Build.VERSION_CODES.JELLY_BEAN) {
17871                        throw new IllegalArgumentException("Component class " + className
17872                                + " does not exist in " + packageName);
17873                    } else {
17874                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17875                                + className + " does not exist in " + packageName);
17876                    }
17877                }
17878                switch (newState) {
17879                case COMPONENT_ENABLED_STATE_ENABLED:
17880                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17881                        return;
17882                    }
17883                    break;
17884                case COMPONENT_ENABLED_STATE_DISABLED:
17885                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17886                        return;
17887                    }
17888                    break;
17889                case COMPONENT_ENABLED_STATE_DEFAULT:
17890                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17891                        return;
17892                    }
17893                    break;
17894                default:
17895                    Slog.e(TAG, "Invalid new component state: " + newState);
17896                    return;
17897                }
17898            }
17899            scheduleWritePackageRestrictionsLocked(userId);
17900            components = mPendingBroadcasts.get(userId, packageName);
17901            final boolean newPackage = components == null;
17902            if (newPackage) {
17903                components = new ArrayList<String>();
17904            }
17905            if (!components.contains(componentName)) {
17906                components.add(componentName);
17907            }
17908            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17909                sendNow = true;
17910                // Purge entry from pending broadcast list if another one exists already
17911                // since we are sending one right away.
17912                mPendingBroadcasts.remove(userId, packageName);
17913            } else {
17914                if (newPackage) {
17915                    mPendingBroadcasts.put(userId, packageName, components);
17916                }
17917                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17918                    // Schedule a message
17919                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17920                }
17921            }
17922        }
17923
17924        long callingId = Binder.clearCallingIdentity();
17925        try {
17926            if (sendNow) {
17927                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17928                sendPackageChangedBroadcast(packageName,
17929                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17930            }
17931        } finally {
17932            Binder.restoreCallingIdentity(callingId);
17933        }
17934    }
17935
17936    @Override
17937    public void flushPackageRestrictionsAsUser(int userId) {
17938        if (!sUserManager.exists(userId)) {
17939            return;
17940        }
17941        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17942                false /* checkShell */, "flushPackageRestrictions");
17943        synchronized (mPackages) {
17944            mSettings.writePackageRestrictionsLPr(userId);
17945            mDirtyUsers.remove(userId);
17946            if (mDirtyUsers.isEmpty()) {
17947                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17948            }
17949        }
17950    }
17951
17952    private void sendPackageChangedBroadcast(String packageName,
17953            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17954        if (DEBUG_INSTALL)
17955            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17956                    + componentNames);
17957        Bundle extras = new Bundle(4);
17958        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17959        String nameList[] = new String[componentNames.size()];
17960        componentNames.toArray(nameList);
17961        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17962        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17963        extras.putInt(Intent.EXTRA_UID, packageUid);
17964        // If this is not reporting a change of the overall package, then only send it
17965        // to registered receivers.  We don't want to launch a swath of apps for every
17966        // little component state change.
17967        final int flags = !componentNames.contains(packageName)
17968                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17969        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17970                new int[] {UserHandle.getUserId(packageUid)});
17971    }
17972
17973    @Override
17974    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17975        if (!sUserManager.exists(userId)) return;
17976        final int uid = Binder.getCallingUid();
17977        final int permission = mContext.checkCallingOrSelfPermission(
17978                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17979        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17980        enforceCrossUserPermission(uid, userId,
17981                true /* requireFullPermission */, true /* checkShell */, "stop package");
17982        // writer
17983        synchronized (mPackages) {
17984            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17985                    allowedByPermission, uid, userId)) {
17986                scheduleWritePackageRestrictionsLocked(userId);
17987            }
17988        }
17989    }
17990
17991    @Override
17992    public String getInstallerPackageName(String packageName) {
17993        // reader
17994        synchronized (mPackages) {
17995            return mSettings.getInstallerPackageNameLPr(packageName);
17996        }
17997    }
17998
17999    public boolean isOrphaned(String packageName) {
18000        // reader
18001        synchronized (mPackages) {
18002            return mSettings.isOrphaned(packageName);
18003        }
18004    }
18005
18006    @Override
18007    public int getApplicationEnabledSetting(String packageName, int userId) {
18008        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18009        int uid = Binder.getCallingUid();
18010        enforceCrossUserPermission(uid, userId,
18011                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18012        // reader
18013        synchronized (mPackages) {
18014            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18015        }
18016    }
18017
18018    @Override
18019    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18020        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18021        int uid = Binder.getCallingUid();
18022        enforceCrossUserPermission(uid, userId,
18023                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18024        // reader
18025        synchronized (mPackages) {
18026            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18027        }
18028    }
18029
18030    @Override
18031    public void enterSafeMode() {
18032        enforceSystemOrRoot("Only the system can request entering safe mode");
18033
18034        if (!mSystemReady) {
18035            mSafeMode = true;
18036        }
18037    }
18038
18039    @Override
18040    public void systemReady() {
18041        mSystemReady = true;
18042
18043        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18044        // disabled after already being started.
18045        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18046                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18047
18048        // Read the compatibilty setting when the system is ready.
18049        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18050                mContext.getContentResolver(),
18051                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18052        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18053        if (DEBUG_SETTINGS) {
18054            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18055        }
18056
18057        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18058
18059        synchronized (mPackages) {
18060            // Verify that all of the preferred activity components actually
18061            // exist.  It is possible for applications to be updated and at
18062            // that point remove a previously declared activity component that
18063            // had been set as a preferred activity.  We try to clean this up
18064            // the next time we encounter that preferred activity, but it is
18065            // possible for the user flow to never be able to return to that
18066            // situation so here we do a sanity check to make sure we haven't
18067            // left any junk around.
18068            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18069            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18070                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18071                removed.clear();
18072                for (PreferredActivity pa : pir.filterSet()) {
18073                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18074                        removed.add(pa);
18075                    }
18076                }
18077                if (removed.size() > 0) {
18078                    for (int r=0; r<removed.size(); r++) {
18079                        PreferredActivity pa = removed.get(r);
18080                        Slog.w(TAG, "Removing dangling preferred activity: "
18081                                + pa.mPref.mComponent);
18082                        pir.removeFilter(pa);
18083                    }
18084                    mSettings.writePackageRestrictionsLPr(
18085                            mSettings.mPreferredActivities.keyAt(i));
18086                }
18087            }
18088
18089            for (int userId : UserManagerService.getInstance().getUserIds()) {
18090                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18091                    grantPermissionsUserIds = ArrayUtils.appendInt(
18092                            grantPermissionsUserIds, userId);
18093                }
18094            }
18095        }
18096        sUserManager.systemReady();
18097
18098        // If we upgraded grant all default permissions before kicking off.
18099        for (int userId : grantPermissionsUserIds) {
18100            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18101        }
18102
18103        // If we did not grant default permissions, we preload from this the
18104        // default permission exceptions lazily to ensure we don't hit the
18105        // disk on a new user creation.
18106        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18107            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18108        }
18109
18110        // Kick off any messages waiting for system ready
18111        if (mPostSystemReadyMessages != null) {
18112            for (Message msg : mPostSystemReadyMessages) {
18113                msg.sendToTarget();
18114            }
18115            mPostSystemReadyMessages = null;
18116        }
18117
18118        // Watch for external volumes that come and go over time
18119        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18120        storage.registerListener(mStorageListener);
18121
18122        mInstallerService.systemReady();
18123        mPackageDexOptimizer.systemReady();
18124
18125        MountServiceInternal mountServiceInternal = LocalServices.getService(
18126                MountServiceInternal.class);
18127        mountServiceInternal.addExternalStoragePolicy(
18128                new MountServiceInternal.ExternalStorageMountPolicy() {
18129            @Override
18130            public int getMountMode(int uid, String packageName) {
18131                if (Process.isIsolated(uid)) {
18132                    return Zygote.MOUNT_EXTERNAL_NONE;
18133                }
18134                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18135                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18136                }
18137                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18138                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18139                }
18140                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18141                    return Zygote.MOUNT_EXTERNAL_READ;
18142                }
18143                return Zygote.MOUNT_EXTERNAL_WRITE;
18144            }
18145
18146            @Override
18147            public boolean hasExternalStorage(int uid, String packageName) {
18148                return true;
18149            }
18150        });
18151
18152        // Now that we're mostly running, clean up stale users and apps
18153        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18154        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18155    }
18156
18157    @Override
18158    public boolean isSafeMode() {
18159        return mSafeMode;
18160    }
18161
18162    @Override
18163    public boolean hasSystemUidErrors() {
18164        return mHasSystemUidErrors;
18165    }
18166
18167    static String arrayToString(int[] array) {
18168        StringBuffer buf = new StringBuffer(128);
18169        buf.append('[');
18170        if (array != null) {
18171            for (int i=0; i<array.length; i++) {
18172                if (i > 0) buf.append(", ");
18173                buf.append(array[i]);
18174            }
18175        }
18176        buf.append(']');
18177        return buf.toString();
18178    }
18179
18180    static class DumpState {
18181        public static final int DUMP_LIBS = 1 << 0;
18182        public static final int DUMP_FEATURES = 1 << 1;
18183        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18184        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18185        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18186        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18187        public static final int DUMP_PERMISSIONS = 1 << 6;
18188        public static final int DUMP_PACKAGES = 1 << 7;
18189        public static final int DUMP_SHARED_USERS = 1 << 8;
18190        public static final int DUMP_MESSAGES = 1 << 9;
18191        public static final int DUMP_PROVIDERS = 1 << 10;
18192        public static final int DUMP_VERIFIERS = 1 << 11;
18193        public static final int DUMP_PREFERRED = 1 << 12;
18194        public static final int DUMP_PREFERRED_XML = 1 << 13;
18195        public static final int DUMP_KEYSETS = 1 << 14;
18196        public static final int DUMP_VERSION = 1 << 15;
18197        public static final int DUMP_INSTALLS = 1 << 16;
18198        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18199        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18200        public static final int DUMP_FROZEN = 1 << 19;
18201        public static final int DUMP_DEXOPT = 1 << 20;
18202        public static final int DUMP_COMPILER_STATS = 1 << 21;
18203
18204        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18205
18206        private int mTypes;
18207
18208        private int mOptions;
18209
18210        private boolean mTitlePrinted;
18211
18212        private SharedUserSetting mSharedUser;
18213
18214        public boolean isDumping(int type) {
18215            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18216                return true;
18217            }
18218
18219            return (mTypes & type) != 0;
18220        }
18221
18222        public void setDump(int type) {
18223            mTypes |= type;
18224        }
18225
18226        public boolean isOptionEnabled(int option) {
18227            return (mOptions & option) != 0;
18228        }
18229
18230        public void setOptionEnabled(int option) {
18231            mOptions |= option;
18232        }
18233
18234        public boolean onTitlePrinted() {
18235            final boolean printed = mTitlePrinted;
18236            mTitlePrinted = true;
18237            return printed;
18238        }
18239
18240        public boolean getTitlePrinted() {
18241            return mTitlePrinted;
18242        }
18243
18244        public void setTitlePrinted(boolean enabled) {
18245            mTitlePrinted = enabled;
18246        }
18247
18248        public SharedUserSetting getSharedUser() {
18249            return mSharedUser;
18250        }
18251
18252        public void setSharedUser(SharedUserSetting user) {
18253            mSharedUser = user;
18254        }
18255    }
18256
18257    @Override
18258    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18259            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18260        (new PackageManagerShellCommand(this)).exec(
18261                this, in, out, err, args, resultReceiver);
18262    }
18263
18264    @Override
18265    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18266        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18267                != PackageManager.PERMISSION_GRANTED) {
18268            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18269                    + Binder.getCallingPid()
18270                    + ", uid=" + Binder.getCallingUid()
18271                    + " without permission "
18272                    + android.Manifest.permission.DUMP);
18273            return;
18274        }
18275
18276        DumpState dumpState = new DumpState();
18277        boolean fullPreferred = false;
18278        boolean checkin = false;
18279
18280        String packageName = null;
18281        ArraySet<String> permissionNames = null;
18282
18283        int opti = 0;
18284        while (opti < args.length) {
18285            String opt = args[opti];
18286            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18287                break;
18288            }
18289            opti++;
18290
18291            if ("-a".equals(opt)) {
18292                // Right now we only know how to print all.
18293            } else if ("-h".equals(opt)) {
18294                pw.println("Package manager dump options:");
18295                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18296                pw.println("    --checkin: dump for a checkin");
18297                pw.println("    -f: print details of intent filters");
18298                pw.println("    -h: print this help");
18299                pw.println("  cmd may be one of:");
18300                pw.println("    l[ibraries]: list known shared libraries");
18301                pw.println("    f[eatures]: list device features");
18302                pw.println("    k[eysets]: print known keysets");
18303                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18304                pw.println("    perm[issions]: dump permissions");
18305                pw.println("    permission [name ...]: dump declaration and use of given permission");
18306                pw.println("    pref[erred]: print preferred package settings");
18307                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18308                pw.println("    prov[iders]: dump content providers");
18309                pw.println("    p[ackages]: dump installed packages");
18310                pw.println("    s[hared-users]: dump shared user IDs");
18311                pw.println("    m[essages]: print collected runtime messages");
18312                pw.println("    v[erifiers]: print package verifier info");
18313                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18314                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18315                pw.println("    version: print database version info");
18316                pw.println("    write: write current settings now");
18317                pw.println("    installs: details about install sessions");
18318                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18319                pw.println("    dexopt: dump dexopt state");
18320                pw.println("    compiler-stats: dump compiler statistics");
18321                pw.println("    <package.name>: info about given package");
18322                return;
18323            } else if ("--checkin".equals(opt)) {
18324                checkin = true;
18325            } else if ("-f".equals(opt)) {
18326                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18327            } else {
18328                pw.println("Unknown argument: " + opt + "; use -h for help");
18329            }
18330        }
18331
18332        // Is the caller requesting to dump a particular piece of data?
18333        if (opti < args.length) {
18334            String cmd = args[opti];
18335            opti++;
18336            // Is this a package name?
18337            if ("android".equals(cmd) || cmd.contains(".")) {
18338                packageName = cmd;
18339                // When dumping a single package, we always dump all of its
18340                // filter information since the amount of data will be reasonable.
18341                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18342            } else if ("check-permission".equals(cmd)) {
18343                if (opti >= args.length) {
18344                    pw.println("Error: check-permission missing permission argument");
18345                    return;
18346                }
18347                String perm = args[opti];
18348                opti++;
18349                if (opti >= args.length) {
18350                    pw.println("Error: check-permission missing package argument");
18351                    return;
18352                }
18353                String pkg = args[opti];
18354                opti++;
18355                int user = UserHandle.getUserId(Binder.getCallingUid());
18356                if (opti < args.length) {
18357                    try {
18358                        user = Integer.parseInt(args[opti]);
18359                    } catch (NumberFormatException e) {
18360                        pw.println("Error: check-permission user argument is not a number: "
18361                                + args[opti]);
18362                        return;
18363                    }
18364                }
18365                pw.println(checkPermission(perm, pkg, user));
18366                return;
18367            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18368                dumpState.setDump(DumpState.DUMP_LIBS);
18369            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18370                dumpState.setDump(DumpState.DUMP_FEATURES);
18371            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18372                if (opti >= args.length) {
18373                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18374                            | DumpState.DUMP_SERVICE_RESOLVERS
18375                            | DumpState.DUMP_RECEIVER_RESOLVERS
18376                            | DumpState.DUMP_CONTENT_RESOLVERS);
18377                } else {
18378                    while (opti < args.length) {
18379                        String name = args[opti];
18380                        if ("a".equals(name) || "activity".equals(name)) {
18381                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18382                        } else if ("s".equals(name) || "service".equals(name)) {
18383                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18384                        } else if ("r".equals(name) || "receiver".equals(name)) {
18385                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18386                        } else if ("c".equals(name) || "content".equals(name)) {
18387                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18388                        } else {
18389                            pw.println("Error: unknown resolver table type: " + name);
18390                            return;
18391                        }
18392                        opti++;
18393                    }
18394                }
18395            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18396                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18397            } else if ("permission".equals(cmd)) {
18398                if (opti >= args.length) {
18399                    pw.println("Error: permission requires permission name");
18400                    return;
18401                }
18402                permissionNames = new ArraySet<>();
18403                while (opti < args.length) {
18404                    permissionNames.add(args[opti]);
18405                    opti++;
18406                }
18407                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18408                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18409            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18410                dumpState.setDump(DumpState.DUMP_PREFERRED);
18411            } else if ("preferred-xml".equals(cmd)) {
18412                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18413                if (opti < args.length && "--full".equals(args[opti])) {
18414                    fullPreferred = true;
18415                    opti++;
18416                }
18417            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18418                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18419            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18420                dumpState.setDump(DumpState.DUMP_PACKAGES);
18421            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18422                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18423            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18424                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18425            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18426                dumpState.setDump(DumpState.DUMP_MESSAGES);
18427            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18428                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18429            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18430                    || "intent-filter-verifiers".equals(cmd)) {
18431                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18432            } else if ("version".equals(cmd)) {
18433                dumpState.setDump(DumpState.DUMP_VERSION);
18434            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18435                dumpState.setDump(DumpState.DUMP_KEYSETS);
18436            } else if ("installs".equals(cmd)) {
18437                dumpState.setDump(DumpState.DUMP_INSTALLS);
18438            } else if ("frozen".equals(cmd)) {
18439                dumpState.setDump(DumpState.DUMP_FROZEN);
18440            } else if ("dexopt".equals(cmd)) {
18441                dumpState.setDump(DumpState.DUMP_DEXOPT);
18442            } else if ("compiler-stats".equals(cmd)) {
18443                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18444            } else if ("write".equals(cmd)) {
18445                synchronized (mPackages) {
18446                    mSettings.writeLPr();
18447                    pw.println("Settings written.");
18448                    return;
18449                }
18450            }
18451        }
18452
18453        if (checkin) {
18454            pw.println("vers,1");
18455        }
18456
18457        // reader
18458        synchronized (mPackages) {
18459            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18460                if (!checkin) {
18461                    if (dumpState.onTitlePrinted())
18462                        pw.println();
18463                    pw.println("Database versions:");
18464                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18465                }
18466            }
18467
18468            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18469                if (!checkin) {
18470                    if (dumpState.onTitlePrinted())
18471                        pw.println();
18472                    pw.println("Verifiers:");
18473                    pw.print("  Required: ");
18474                    pw.print(mRequiredVerifierPackage);
18475                    pw.print(" (uid=");
18476                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18477                            UserHandle.USER_SYSTEM));
18478                    pw.println(")");
18479                } else if (mRequiredVerifierPackage != null) {
18480                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18481                    pw.print(",");
18482                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18483                            UserHandle.USER_SYSTEM));
18484                }
18485            }
18486
18487            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18488                    packageName == null) {
18489                if (mIntentFilterVerifierComponent != null) {
18490                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18491                    if (!checkin) {
18492                        if (dumpState.onTitlePrinted())
18493                            pw.println();
18494                        pw.println("Intent Filter Verifier:");
18495                        pw.print("  Using: ");
18496                        pw.print(verifierPackageName);
18497                        pw.print(" (uid=");
18498                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18499                                UserHandle.USER_SYSTEM));
18500                        pw.println(")");
18501                    } else if (verifierPackageName != null) {
18502                        pw.print("ifv,"); pw.print(verifierPackageName);
18503                        pw.print(",");
18504                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18505                                UserHandle.USER_SYSTEM));
18506                    }
18507                } else {
18508                    pw.println();
18509                    pw.println("No Intent Filter Verifier available!");
18510                }
18511            }
18512
18513            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18514                boolean printedHeader = false;
18515                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18516                while (it.hasNext()) {
18517                    String name = it.next();
18518                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18519                    if (!checkin) {
18520                        if (!printedHeader) {
18521                            if (dumpState.onTitlePrinted())
18522                                pw.println();
18523                            pw.println("Libraries:");
18524                            printedHeader = true;
18525                        }
18526                        pw.print("  ");
18527                    } else {
18528                        pw.print("lib,");
18529                    }
18530                    pw.print(name);
18531                    if (!checkin) {
18532                        pw.print(" -> ");
18533                    }
18534                    if (ent.path != null) {
18535                        if (!checkin) {
18536                            pw.print("(jar) ");
18537                            pw.print(ent.path);
18538                        } else {
18539                            pw.print(",jar,");
18540                            pw.print(ent.path);
18541                        }
18542                    } else {
18543                        if (!checkin) {
18544                            pw.print("(apk) ");
18545                            pw.print(ent.apk);
18546                        } else {
18547                            pw.print(",apk,");
18548                            pw.print(ent.apk);
18549                        }
18550                    }
18551                    pw.println();
18552                }
18553            }
18554
18555            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18556                if (dumpState.onTitlePrinted())
18557                    pw.println();
18558                if (!checkin) {
18559                    pw.println("Features:");
18560                }
18561
18562                for (FeatureInfo feat : mAvailableFeatures.values()) {
18563                    if (checkin) {
18564                        pw.print("feat,");
18565                        pw.print(feat.name);
18566                        pw.print(",");
18567                        pw.println(feat.version);
18568                    } else {
18569                        pw.print("  ");
18570                        pw.print(feat.name);
18571                        if (feat.version > 0) {
18572                            pw.print(" version=");
18573                            pw.print(feat.version);
18574                        }
18575                        pw.println();
18576                    }
18577                }
18578            }
18579
18580            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18581                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18582                        : "Activity Resolver Table:", "  ", packageName,
18583                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18584                    dumpState.setTitlePrinted(true);
18585                }
18586            }
18587            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18588                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18589                        : "Receiver Resolver Table:", "  ", packageName,
18590                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18591                    dumpState.setTitlePrinted(true);
18592                }
18593            }
18594            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18595                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18596                        : "Service Resolver Table:", "  ", packageName,
18597                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18598                    dumpState.setTitlePrinted(true);
18599                }
18600            }
18601            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18602                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18603                        : "Provider Resolver Table:", "  ", packageName,
18604                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18605                    dumpState.setTitlePrinted(true);
18606                }
18607            }
18608
18609            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18610                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18611                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18612                    int user = mSettings.mPreferredActivities.keyAt(i);
18613                    if (pir.dump(pw,
18614                            dumpState.getTitlePrinted()
18615                                ? "\nPreferred Activities User " + user + ":"
18616                                : "Preferred Activities User " + user + ":", "  ",
18617                            packageName, true, false)) {
18618                        dumpState.setTitlePrinted(true);
18619                    }
18620                }
18621            }
18622
18623            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18624                pw.flush();
18625                FileOutputStream fout = new FileOutputStream(fd);
18626                BufferedOutputStream str = new BufferedOutputStream(fout);
18627                XmlSerializer serializer = new FastXmlSerializer();
18628                try {
18629                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18630                    serializer.startDocument(null, true);
18631                    serializer.setFeature(
18632                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18633                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18634                    serializer.endDocument();
18635                    serializer.flush();
18636                } catch (IllegalArgumentException e) {
18637                    pw.println("Failed writing: " + e);
18638                } catch (IllegalStateException e) {
18639                    pw.println("Failed writing: " + e);
18640                } catch (IOException e) {
18641                    pw.println("Failed writing: " + e);
18642                }
18643            }
18644
18645            if (!checkin
18646                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18647                    && packageName == null) {
18648                pw.println();
18649                int count = mSettings.mPackages.size();
18650                if (count == 0) {
18651                    pw.println("No applications!");
18652                    pw.println();
18653                } else {
18654                    final String prefix = "  ";
18655                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18656                    if (allPackageSettings.size() == 0) {
18657                        pw.println("No domain preferred apps!");
18658                        pw.println();
18659                    } else {
18660                        pw.println("App verification status:");
18661                        pw.println();
18662                        count = 0;
18663                        for (PackageSetting ps : allPackageSettings) {
18664                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18665                            if (ivi == null || ivi.getPackageName() == null) continue;
18666                            pw.println(prefix + "Package: " + ivi.getPackageName());
18667                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18668                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18669                            pw.println();
18670                            count++;
18671                        }
18672                        if (count == 0) {
18673                            pw.println(prefix + "No app verification established.");
18674                            pw.println();
18675                        }
18676                        for (int userId : sUserManager.getUserIds()) {
18677                            pw.println("App linkages for user " + userId + ":");
18678                            pw.println();
18679                            count = 0;
18680                            for (PackageSetting ps : allPackageSettings) {
18681                                final long status = ps.getDomainVerificationStatusForUser(userId);
18682                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18683                                    continue;
18684                                }
18685                                pw.println(prefix + "Package: " + ps.name);
18686                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18687                                String statusStr = IntentFilterVerificationInfo.
18688                                        getStatusStringFromValue(status);
18689                                pw.println(prefix + "Status:  " + statusStr);
18690                                pw.println();
18691                                count++;
18692                            }
18693                            if (count == 0) {
18694                                pw.println(prefix + "No configured app linkages.");
18695                                pw.println();
18696                            }
18697                        }
18698                    }
18699                }
18700            }
18701
18702            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18703                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18704                if (packageName == null && permissionNames == null) {
18705                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18706                        if (iperm == 0) {
18707                            if (dumpState.onTitlePrinted())
18708                                pw.println();
18709                            pw.println("AppOp Permissions:");
18710                        }
18711                        pw.print("  AppOp Permission ");
18712                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18713                        pw.println(":");
18714                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18715                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18716                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18717                        }
18718                    }
18719                }
18720            }
18721
18722            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18723                boolean printedSomething = false;
18724                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18725                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18726                        continue;
18727                    }
18728                    if (!printedSomething) {
18729                        if (dumpState.onTitlePrinted())
18730                            pw.println();
18731                        pw.println("Registered ContentProviders:");
18732                        printedSomething = true;
18733                    }
18734                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18735                    pw.print("    "); pw.println(p.toString());
18736                }
18737                printedSomething = false;
18738                for (Map.Entry<String, PackageParser.Provider> entry :
18739                        mProvidersByAuthority.entrySet()) {
18740                    PackageParser.Provider p = entry.getValue();
18741                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18742                        continue;
18743                    }
18744                    if (!printedSomething) {
18745                        if (dumpState.onTitlePrinted())
18746                            pw.println();
18747                        pw.println("ContentProvider Authorities:");
18748                        printedSomething = true;
18749                    }
18750                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18751                    pw.print("    "); pw.println(p.toString());
18752                    if (p.info != null && p.info.applicationInfo != null) {
18753                        final String appInfo = p.info.applicationInfo.toString();
18754                        pw.print("      applicationInfo="); pw.println(appInfo);
18755                    }
18756                }
18757            }
18758
18759            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18760                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18761            }
18762
18763            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18764                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18765            }
18766
18767            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18768                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18769            }
18770
18771            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18772                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18773            }
18774
18775            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18776                // XXX should handle packageName != null by dumping only install data that
18777                // the given package is involved with.
18778                if (dumpState.onTitlePrinted()) pw.println();
18779                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18780            }
18781
18782            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18783                // XXX should handle packageName != null by dumping only install data that
18784                // the given package is involved with.
18785                if (dumpState.onTitlePrinted()) pw.println();
18786
18787                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18788                ipw.println();
18789                ipw.println("Frozen packages:");
18790                ipw.increaseIndent();
18791                if (mFrozenPackages.size() == 0) {
18792                    ipw.println("(none)");
18793                } else {
18794                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18795                        ipw.println(mFrozenPackages.valueAt(i));
18796                    }
18797                }
18798                ipw.decreaseIndent();
18799            }
18800
18801            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18802                if (dumpState.onTitlePrinted()) pw.println();
18803                dumpDexoptStateLPr(pw, packageName);
18804            }
18805
18806            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18807                if (dumpState.onTitlePrinted()) pw.println();
18808                dumpCompilerStatsLPr(pw, packageName);
18809            }
18810
18811            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18812                if (dumpState.onTitlePrinted()) pw.println();
18813                mSettings.dumpReadMessagesLPr(pw, dumpState);
18814
18815                pw.println();
18816                pw.println("Package warning messages:");
18817                BufferedReader in = null;
18818                String line = null;
18819                try {
18820                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18821                    while ((line = in.readLine()) != null) {
18822                        if (line.contains("ignored: updated version")) continue;
18823                        pw.println(line);
18824                    }
18825                } catch (IOException ignored) {
18826                } finally {
18827                    IoUtils.closeQuietly(in);
18828                }
18829            }
18830
18831            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18832                BufferedReader in = null;
18833                String line = null;
18834                try {
18835                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18836                    while ((line = in.readLine()) != null) {
18837                        if (line.contains("ignored: updated version")) continue;
18838                        pw.print("msg,");
18839                        pw.println(line);
18840                    }
18841                } catch (IOException ignored) {
18842                } finally {
18843                    IoUtils.closeQuietly(in);
18844                }
18845            }
18846        }
18847    }
18848
18849    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18850        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18851        ipw.println();
18852        ipw.println("Dexopt state:");
18853        ipw.increaseIndent();
18854        Collection<PackageParser.Package> packages = null;
18855        if (packageName != null) {
18856            PackageParser.Package targetPackage = mPackages.get(packageName);
18857            if (targetPackage != null) {
18858                packages = Collections.singletonList(targetPackage);
18859            } else {
18860                ipw.println("Unable to find package: " + packageName);
18861                return;
18862            }
18863        } else {
18864            packages = mPackages.values();
18865        }
18866
18867        for (PackageParser.Package pkg : packages) {
18868            ipw.println("[" + pkg.packageName + "]");
18869            ipw.increaseIndent();
18870            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18871            ipw.decreaseIndent();
18872        }
18873    }
18874
18875    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
18876        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18877        ipw.println();
18878        ipw.println("Compiler stats:");
18879        ipw.increaseIndent();
18880        Collection<PackageParser.Package> packages = null;
18881        if (packageName != null) {
18882            PackageParser.Package targetPackage = mPackages.get(packageName);
18883            if (targetPackage != null) {
18884                packages = Collections.singletonList(targetPackage);
18885            } else {
18886                ipw.println("Unable to find package: " + packageName);
18887                return;
18888            }
18889        } else {
18890            packages = mPackages.values();
18891        }
18892
18893        for (PackageParser.Package pkg : packages) {
18894            ipw.println("[" + pkg.packageName + "]");
18895            ipw.increaseIndent();
18896
18897            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
18898            if (stats == null) {
18899                ipw.println("(No recorded stats)");
18900            } else {
18901                stats.dump(ipw);
18902            }
18903            ipw.decreaseIndent();
18904        }
18905    }
18906
18907    private String dumpDomainString(String packageName) {
18908        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18909                .getList();
18910        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18911
18912        ArraySet<String> result = new ArraySet<>();
18913        if (iviList.size() > 0) {
18914            for (IntentFilterVerificationInfo ivi : iviList) {
18915                for (String host : ivi.getDomains()) {
18916                    result.add(host);
18917                }
18918            }
18919        }
18920        if (filters != null && filters.size() > 0) {
18921            for (IntentFilter filter : filters) {
18922                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18923                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18924                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18925                    result.addAll(filter.getHostsList());
18926                }
18927            }
18928        }
18929
18930        StringBuilder sb = new StringBuilder(result.size() * 16);
18931        for (String domain : result) {
18932            if (sb.length() > 0) sb.append(" ");
18933            sb.append(domain);
18934        }
18935        return sb.toString();
18936    }
18937
18938    // ------- apps on sdcard specific code -------
18939    static final boolean DEBUG_SD_INSTALL = false;
18940
18941    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18942
18943    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18944
18945    private boolean mMediaMounted = false;
18946
18947    static String getEncryptKey() {
18948        try {
18949            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18950                    SD_ENCRYPTION_KEYSTORE_NAME);
18951            if (sdEncKey == null) {
18952                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18953                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18954                if (sdEncKey == null) {
18955                    Slog.e(TAG, "Failed to create encryption keys");
18956                    return null;
18957                }
18958            }
18959            return sdEncKey;
18960        } catch (NoSuchAlgorithmException nsae) {
18961            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18962            return null;
18963        } catch (IOException ioe) {
18964            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18965            return null;
18966        }
18967    }
18968
18969    /*
18970     * Update media status on PackageManager.
18971     */
18972    @Override
18973    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18974        int callingUid = Binder.getCallingUid();
18975        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18976            throw new SecurityException("Media status can only be updated by the system");
18977        }
18978        // reader; this apparently protects mMediaMounted, but should probably
18979        // be a different lock in that case.
18980        synchronized (mPackages) {
18981            Log.i(TAG, "Updating external media status from "
18982                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18983                    + (mediaStatus ? "mounted" : "unmounted"));
18984            if (DEBUG_SD_INSTALL)
18985                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18986                        + ", mMediaMounted=" + mMediaMounted);
18987            if (mediaStatus == mMediaMounted) {
18988                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18989                        : 0, -1);
18990                mHandler.sendMessage(msg);
18991                return;
18992            }
18993            mMediaMounted = mediaStatus;
18994        }
18995        // Queue up an async operation since the package installation may take a
18996        // little while.
18997        mHandler.post(new Runnable() {
18998            public void run() {
18999                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19000            }
19001        });
19002    }
19003
19004    /**
19005     * Called by MountService when the initial ASECs to scan are available.
19006     * Should block until all the ASEC containers are finished being scanned.
19007     */
19008    public void scanAvailableAsecs() {
19009        updateExternalMediaStatusInner(true, false, false);
19010    }
19011
19012    /*
19013     * Collect information of applications on external media, map them against
19014     * existing containers and update information based on current mount status.
19015     * Please note that we always have to report status if reportStatus has been
19016     * set to true especially when unloading packages.
19017     */
19018    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19019            boolean externalStorage) {
19020        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19021        int[] uidArr = EmptyArray.INT;
19022
19023        final String[] list = PackageHelper.getSecureContainerList();
19024        if (ArrayUtils.isEmpty(list)) {
19025            Log.i(TAG, "No secure containers found");
19026        } else {
19027            // Process list of secure containers and categorize them
19028            // as active or stale based on their package internal state.
19029
19030            // reader
19031            synchronized (mPackages) {
19032                for (String cid : list) {
19033                    // Leave stages untouched for now; installer service owns them
19034                    if (PackageInstallerService.isStageName(cid)) continue;
19035
19036                    if (DEBUG_SD_INSTALL)
19037                        Log.i(TAG, "Processing container " + cid);
19038                    String pkgName = getAsecPackageName(cid);
19039                    if (pkgName == null) {
19040                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19041                        continue;
19042                    }
19043                    if (DEBUG_SD_INSTALL)
19044                        Log.i(TAG, "Looking for pkg : " + pkgName);
19045
19046                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19047                    if (ps == null) {
19048                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19049                        continue;
19050                    }
19051
19052                    /*
19053                     * Skip packages that are not external if we're unmounting
19054                     * external storage.
19055                     */
19056                    if (externalStorage && !isMounted && !isExternal(ps)) {
19057                        continue;
19058                    }
19059
19060                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19061                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19062                    // The package status is changed only if the code path
19063                    // matches between settings and the container id.
19064                    if (ps.codePathString != null
19065                            && ps.codePathString.startsWith(args.getCodePath())) {
19066                        if (DEBUG_SD_INSTALL) {
19067                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19068                                    + " at code path: " + ps.codePathString);
19069                        }
19070
19071                        // We do have a valid package installed on sdcard
19072                        processCids.put(args, ps.codePathString);
19073                        final int uid = ps.appId;
19074                        if (uid != -1) {
19075                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19076                        }
19077                    } else {
19078                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19079                                + ps.codePathString);
19080                    }
19081                }
19082            }
19083
19084            Arrays.sort(uidArr);
19085        }
19086
19087        // Process packages with valid entries.
19088        if (isMounted) {
19089            if (DEBUG_SD_INSTALL)
19090                Log.i(TAG, "Loading packages");
19091            loadMediaPackages(processCids, uidArr, externalStorage);
19092            startCleaningPackages();
19093            mInstallerService.onSecureContainersAvailable();
19094        } else {
19095            if (DEBUG_SD_INSTALL)
19096                Log.i(TAG, "Unloading packages");
19097            unloadMediaPackages(processCids, uidArr, reportStatus);
19098        }
19099    }
19100
19101    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19102            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19103        final int size = infos.size();
19104        final String[] packageNames = new String[size];
19105        final int[] packageUids = new int[size];
19106        for (int i = 0; i < size; i++) {
19107            final ApplicationInfo info = infos.get(i);
19108            packageNames[i] = info.packageName;
19109            packageUids[i] = info.uid;
19110        }
19111        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19112                finishedReceiver);
19113    }
19114
19115    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19116            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19117        sendResourcesChangedBroadcast(mediaStatus, replacing,
19118                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19119    }
19120
19121    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19122            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19123        int size = pkgList.length;
19124        if (size > 0) {
19125            // Send broadcasts here
19126            Bundle extras = new Bundle();
19127            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19128            if (uidArr != null) {
19129                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19130            }
19131            if (replacing) {
19132                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19133            }
19134            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19135                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19136            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19137        }
19138    }
19139
19140   /*
19141     * Look at potentially valid container ids from processCids If package
19142     * information doesn't match the one on record or package scanning fails,
19143     * the cid is added to list of removeCids. We currently don't delete stale
19144     * containers.
19145     */
19146    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19147            boolean externalStorage) {
19148        ArrayList<String> pkgList = new ArrayList<String>();
19149        Set<AsecInstallArgs> keys = processCids.keySet();
19150
19151        for (AsecInstallArgs args : keys) {
19152            String codePath = processCids.get(args);
19153            if (DEBUG_SD_INSTALL)
19154                Log.i(TAG, "Loading container : " + args.cid);
19155            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19156            try {
19157                // Make sure there are no container errors first.
19158                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19159                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19160                            + " when installing from sdcard");
19161                    continue;
19162                }
19163                // Check code path here.
19164                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19165                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19166                            + " does not match one in settings " + codePath);
19167                    continue;
19168                }
19169                // Parse package
19170                int parseFlags = mDefParseFlags;
19171                if (args.isExternalAsec()) {
19172                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19173                }
19174                if (args.isFwdLocked()) {
19175                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19176                }
19177
19178                synchronized (mInstallLock) {
19179                    PackageParser.Package pkg = null;
19180                    try {
19181                        // Sadly we don't know the package name yet to freeze it
19182                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19183                                SCAN_IGNORE_FROZEN, 0, null);
19184                    } catch (PackageManagerException e) {
19185                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19186                    }
19187                    // Scan the package
19188                    if (pkg != null) {
19189                        /*
19190                         * TODO why is the lock being held? doPostInstall is
19191                         * called in other places without the lock. This needs
19192                         * to be straightened out.
19193                         */
19194                        // writer
19195                        synchronized (mPackages) {
19196                            retCode = PackageManager.INSTALL_SUCCEEDED;
19197                            pkgList.add(pkg.packageName);
19198                            // Post process args
19199                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19200                                    pkg.applicationInfo.uid);
19201                        }
19202                    } else {
19203                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19204                    }
19205                }
19206
19207            } finally {
19208                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19209                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19210                }
19211            }
19212        }
19213        // writer
19214        synchronized (mPackages) {
19215            // If the platform SDK has changed since the last time we booted,
19216            // we need to re-grant app permission to catch any new ones that
19217            // appear. This is really a hack, and means that apps can in some
19218            // cases get permissions that the user didn't initially explicitly
19219            // allow... it would be nice to have some better way to handle
19220            // this situation.
19221            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19222                    : mSettings.getInternalVersion();
19223            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19224                    : StorageManager.UUID_PRIVATE_INTERNAL;
19225
19226            int updateFlags = UPDATE_PERMISSIONS_ALL;
19227            if (ver.sdkVersion != mSdkVersion) {
19228                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19229                        + mSdkVersion + "; regranting permissions for external");
19230                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19231            }
19232            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19233
19234            // Yay, everything is now upgraded
19235            ver.forceCurrent();
19236
19237            // can downgrade to reader
19238            // Persist settings
19239            mSettings.writeLPr();
19240        }
19241        // Send a broadcast to let everyone know we are done processing
19242        if (pkgList.size() > 0) {
19243            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19244        }
19245    }
19246
19247   /*
19248     * Utility method to unload a list of specified containers
19249     */
19250    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19251        // Just unmount all valid containers.
19252        for (AsecInstallArgs arg : cidArgs) {
19253            synchronized (mInstallLock) {
19254                arg.doPostDeleteLI(false);
19255           }
19256       }
19257   }
19258
19259    /*
19260     * Unload packages mounted on external media. This involves deleting package
19261     * data from internal structures, sending broadcasts about disabled packages,
19262     * gc'ing to free up references, unmounting all secure containers
19263     * corresponding to packages on external media, and posting a
19264     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19265     * that we always have to post this message if status has been requested no
19266     * matter what.
19267     */
19268    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19269            final boolean reportStatus) {
19270        if (DEBUG_SD_INSTALL)
19271            Log.i(TAG, "unloading media packages");
19272        ArrayList<String> pkgList = new ArrayList<String>();
19273        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19274        final Set<AsecInstallArgs> keys = processCids.keySet();
19275        for (AsecInstallArgs args : keys) {
19276            String pkgName = args.getPackageName();
19277            if (DEBUG_SD_INSTALL)
19278                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19279            // Delete package internally
19280            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19281            synchronized (mInstallLock) {
19282                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19283                final boolean res;
19284                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19285                        "unloadMediaPackages")) {
19286                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19287                            null);
19288                }
19289                if (res) {
19290                    pkgList.add(pkgName);
19291                } else {
19292                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19293                    failedList.add(args);
19294                }
19295            }
19296        }
19297
19298        // reader
19299        synchronized (mPackages) {
19300            // We didn't update the settings after removing each package;
19301            // write them now for all packages.
19302            mSettings.writeLPr();
19303        }
19304
19305        // We have to absolutely send UPDATED_MEDIA_STATUS only
19306        // after confirming that all the receivers processed the ordered
19307        // broadcast when packages get disabled, force a gc to clean things up.
19308        // and unload all the containers.
19309        if (pkgList.size() > 0) {
19310            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19311                    new IIntentReceiver.Stub() {
19312                public void performReceive(Intent intent, int resultCode, String data,
19313                        Bundle extras, boolean ordered, boolean sticky,
19314                        int sendingUser) throws RemoteException {
19315                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19316                            reportStatus ? 1 : 0, 1, keys);
19317                    mHandler.sendMessage(msg);
19318                }
19319            });
19320        } else {
19321            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19322                    keys);
19323            mHandler.sendMessage(msg);
19324        }
19325    }
19326
19327    private void loadPrivatePackages(final VolumeInfo vol) {
19328        mHandler.post(new Runnable() {
19329            @Override
19330            public void run() {
19331                loadPrivatePackagesInner(vol);
19332            }
19333        });
19334    }
19335
19336    private void loadPrivatePackagesInner(VolumeInfo vol) {
19337        final String volumeUuid = vol.fsUuid;
19338        if (TextUtils.isEmpty(volumeUuid)) {
19339            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19340            return;
19341        }
19342
19343        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19344        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19345        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19346
19347        final VersionInfo ver;
19348        final List<PackageSetting> packages;
19349        synchronized (mPackages) {
19350            ver = mSettings.findOrCreateVersion(volumeUuid);
19351            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19352        }
19353
19354        for (PackageSetting ps : packages) {
19355            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19356            synchronized (mInstallLock) {
19357                final PackageParser.Package pkg;
19358                try {
19359                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19360                    loaded.add(pkg.applicationInfo);
19361
19362                } catch (PackageManagerException e) {
19363                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19364                }
19365
19366                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19367                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19368                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19369                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19370                }
19371            }
19372        }
19373
19374        // Reconcile app data for all started/unlocked users
19375        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19376        final UserManager um = mContext.getSystemService(UserManager.class);
19377        UserManagerInternal umInternal = getUserManagerInternal();
19378        for (UserInfo user : um.getUsers()) {
19379            final int flags;
19380            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19381                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19382            } else if (umInternal.isUserRunning(user.id)) {
19383                flags = StorageManager.FLAG_STORAGE_DE;
19384            } else {
19385                continue;
19386            }
19387
19388            try {
19389                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19390                synchronized (mInstallLock) {
19391                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19392                }
19393            } catch (IllegalStateException e) {
19394                // Device was probably ejected, and we'll process that event momentarily
19395                Slog.w(TAG, "Failed to prepare storage: " + e);
19396            }
19397        }
19398
19399        synchronized (mPackages) {
19400            int updateFlags = UPDATE_PERMISSIONS_ALL;
19401            if (ver.sdkVersion != mSdkVersion) {
19402                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19403                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19404                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19405            }
19406            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19407
19408            // Yay, everything is now upgraded
19409            ver.forceCurrent();
19410
19411            mSettings.writeLPr();
19412        }
19413
19414        for (PackageFreezer freezer : freezers) {
19415            freezer.close();
19416        }
19417
19418        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19419        sendResourcesChangedBroadcast(true, false, loaded, null);
19420    }
19421
19422    private void unloadPrivatePackages(final VolumeInfo vol) {
19423        mHandler.post(new Runnable() {
19424            @Override
19425            public void run() {
19426                unloadPrivatePackagesInner(vol);
19427            }
19428        });
19429    }
19430
19431    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19432        final String volumeUuid = vol.fsUuid;
19433        if (TextUtils.isEmpty(volumeUuid)) {
19434            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19435            return;
19436        }
19437
19438        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19439        synchronized (mInstallLock) {
19440        synchronized (mPackages) {
19441            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19442            for (PackageSetting ps : packages) {
19443                if (ps.pkg == null) continue;
19444
19445                final ApplicationInfo info = ps.pkg.applicationInfo;
19446                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19447                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19448
19449                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19450                        "unloadPrivatePackagesInner")) {
19451                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19452                            false, null)) {
19453                        unloaded.add(info);
19454                    } else {
19455                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19456                    }
19457                }
19458
19459                // Try very hard to release any references to this package
19460                // so we don't risk the system server being killed due to
19461                // open FDs
19462                AttributeCache.instance().removePackage(ps.name);
19463            }
19464
19465            mSettings.writeLPr();
19466        }
19467        }
19468
19469        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19470        sendResourcesChangedBroadcast(false, false, unloaded, null);
19471
19472        // Try very hard to release any references to this path so we don't risk
19473        // the system server being killed due to open FDs
19474        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19475
19476        for (int i = 0; i < 3; i++) {
19477            System.gc();
19478            System.runFinalization();
19479        }
19480    }
19481
19482    /**
19483     * Prepare storage areas for given user on all mounted devices.
19484     */
19485    void prepareUserData(int userId, int userSerial, int flags) {
19486        synchronized (mInstallLock) {
19487            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19488            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19489                final String volumeUuid = vol.getFsUuid();
19490                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19491            }
19492        }
19493    }
19494
19495    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19496            boolean allowRecover) {
19497        // Prepare storage and verify that serial numbers are consistent; if
19498        // there's a mismatch we need to destroy to avoid leaking data
19499        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19500        try {
19501            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19502
19503            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19504                UserManagerService.enforceSerialNumber(
19505                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19506                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19507                    UserManagerService.enforceSerialNumber(
19508                            Environment.getDataSystemDeDirectory(userId), userSerial);
19509                }
19510            }
19511            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19512                UserManagerService.enforceSerialNumber(
19513                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19514                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19515                    UserManagerService.enforceSerialNumber(
19516                            Environment.getDataSystemCeDirectory(userId), userSerial);
19517                }
19518            }
19519
19520            synchronized (mInstallLock) {
19521                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19522            }
19523        } catch (Exception e) {
19524            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19525                    + " because we failed to prepare: " + e);
19526            destroyUserDataLI(volumeUuid, userId,
19527                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19528
19529            if (allowRecover) {
19530                // Try one last time; if we fail again we're really in trouble
19531                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19532            }
19533        }
19534    }
19535
19536    /**
19537     * Destroy storage areas for given user on all mounted devices.
19538     */
19539    void destroyUserData(int userId, int flags) {
19540        synchronized (mInstallLock) {
19541            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19542            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19543                final String volumeUuid = vol.getFsUuid();
19544                destroyUserDataLI(volumeUuid, userId, flags);
19545            }
19546        }
19547    }
19548
19549    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19550        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19551        try {
19552            // Clean up app data, profile data, and media data
19553            mInstaller.destroyUserData(volumeUuid, userId, flags);
19554
19555            // Clean up system data
19556            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19557                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19558                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19559                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19560                }
19561                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19562                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19563                }
19564            }
19565
19566            // Data with special labels is now gone, so finish the job
19567            storage.destroyUserStorage(volumeUuid, userId, flags);
19568
19569        } catch (Exception e) {
19570            logCriticalInfo(Log.WARN,
19571                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19572        }
19573    }
19574
19575    /**
19576     * Examine all users present on given mounted volume, and destroy data
19577     * belonging to users that are no longer valid, or whose user ID has been
19578     * recycled.
19579     */
19580    private void reconcileUsers(String volumeUuid) {
19581        final List<File> files = new ArrayList<>();
19582        Collections.addAll(files, FileUtils
19583                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19584        Collections.addAll(files, FileUtils
19585                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19586        Collections.addAll(files, FileUtils
19587                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19588        Collections.addAll(files, FileUtils
19589                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19590        for (File file : files) {
19591            if (!file.isDirectory()) continue;
19592
19593            final int userId;
19594            final UserInfo info;
19595            try {
19596                userId = Integer.parseInt(file.getName());
19597                info = sUserManager.getUserInfo(userId);
19598            } catch (NumberFormatException e) {
19599                Slog.w(TAG, "Invalid user directory " + file);
19600                continue;
19601            }
19602
19603            boolean destroyUser = false;
19604            if (info == null) {
19605                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19606                        + " because no matching user was found");
19607                destroyUser = true;
19608            } else if (!mOnlyCore) {
19609                try {
19610                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19611                } catch (IOException e) {
19612                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19613                            + " because we failed to enforce serial number: " + e);
19614                    destroyUser = true;
19615                }
19616            }
19617
19618            if (destroyUser) {
19619                synchronized (mInstallLock) {
19620                    destroyUserDataLI(volumeUuid, userId,
19621                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19622                }
19623            }
19624        }
19625    }
19626
19627    private void assertPackageKnown(String volumeUuid, String packageName)
19628            throws PackageManagerException {
19629        synchronized (mPackages) {
19630            final PackageSetting ps = mSettings.mPackages.get(packageName);
19631            if (ps == null) {
19632                throw new PackageManagerException("Package " + packageName + " is unknown");
19633            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19634                throw new PackageManagerException(
19635                        "Package " + packageName + " found on unknown volume " + volumeUuid
19636                                + "; expected volume " + ps.volumeUuid);
19637            }
19638        }
19639    }
19640
19641    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19642            throws PackageManagerException {
19643        synchronized (mPackages) {
19644            final PackageSetting ps = mSettings.mPackages.get(packageName);
19645            if (ps == null) {
19646                throw new PackageManagerException("Package " + packageName + " is unknown");
19647            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19648                throw new PackageManagerException(
19649                        "Package " + packageName + " found on unknown volume " + volumeUuid
19650                                + "; expected volume " + ps.volumeUuid);
19651            } else if (!ps.getInstalled(userId)) {
19652                throw new PackageManagerException(
19653                        "Package " + packageName + " not installed for user " + userId);
19654            }
19655        }
19656    }
19657
19658    /**
19659     * Examine all apps present on given mounted volume, and destroy apps that
19660     * aren't expected, either due to uninstallation or reinstallation on
19661     * another volume.
19662     */
19663    private void reconcileApps(String volumeUuid) {
19664        final File[] files = FileUtils
19665                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19666        for (File file : files) {
19667            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19668                    && !PackageInstallerService.isStageName(file.getName());
19669            if (!isPackage) {
19670                // Ignore entries which are not packages
19671                continue;
19672            }
19673
19674            try {
19675                final PackageLite pkg = PackageParser.parsePackageLite(file,
19676                        PackageParser.PARSE_MUST_BE_APK);
19677                assertPackageKnown(volumeUuid, pkg.packageName);
19678
19679            } catch (PackageParserException | PackageManagerException e) {
19680                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19681                synchronized (mInstallLock) {
19682                    removeCodePathLI(file);
19683                }
19684            }
19685        }
19686    }
19687
19688    /**
19689     * Reconcile all app data for the given user.
19690     * <p>
19691     * Verifies that directories exist and that ownership and labeling is
19692     * correct for all installed apps on all mounted volumes.
19693     */
19694    void reconcileAppsData(int userId, int flags) {
19695        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19696        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19697            final String volumeUuid = vol.getFsUuid();
19698            synchronized (mInstallLock) {
19699                reconcileAppsDataLI(volumeUuid, userId, flags);
19700            }
19701        }
19702    }
19703
19704    /**
19705     * Reconcile all app data on given mounted volume.
19706     * <p>
19707     * Destroys app data that isn't expected, either due to uninstallation or
19708     * reinstallation on another volume.
19709     * <p>
19710     * Verifies that directories exist and that ownership and labeling is
19711     * correct for all installed apps.
19712     */
19713    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19714        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19715                + Integer.toHexString(flags));
19716
19717        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19718        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19719
19720        boolean restoreconNeeded = false;
19721
19722        // First look for stale data that doesn't belong, and check if things
19723        // have changed since we did our last restorecon
19724        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19725            if (StorageManager.isFileEncryptedNativeOrEmulated()
19726                    && !StorageManager.isUserKeyUnlocked(userId)) {
19727                throw new RuntimeException(
19728                        "Yikes, someone asked us to reconcile CE storage while " + userId
19729                                + " was still locked; this would have caused massive data loss!");
19730            }
19731
19732            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19733
19734            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19735            for (File file : files) {
19736                final String packageName = file.getName();
19737                try {
19738                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19739                } catch (PackageManagerException e) {
19740                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19741                    try {
19742                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19743                                StorageManager.FLAG_STORAGE_CE, 0);
19744                    } catch (InstallerException e2) {
19745                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19746                    }
19747                }
19748            }
19749        }
19750        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19751            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19752
19753            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19754            for (File file : files) {
19755                final String packageName = file.getName();
19756                try {
19757                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19758                } catch (PackageManagerException e) {
19759                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19760                    try {
19761                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19762                                StorageManager.FLAG_STORAGE_DE, 0);
19763                    } catch (InstallerException e2) {
19764                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19765                    }
19766                }
19767            }
19768        }
19769
19770        // Ensure that data directories are ready to roll for all packages
19771        // installed for this volume and user
19772        final List<PackageSetting> packages;
19773        synchronized (mPackages) {
19774            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19775        }
19776        int preparedCount = 0;
19777        for (PackageSetting ps : packages) {
19778            final String packageName = ps.name;
19779            if (ps.pkg == null) {
19780                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19781                // TODO: might be due to legacy ASEC apps; we should circle back
19782                // and reconcile again once they're scanned
19783                continue;
19784            }
19785
19786            if (ps.getInstalled(userId)) {
19787                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19788
19789                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19790                    // We may have just shuffled around app data directories, so
19791                    // prepare them one more time
19792                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19793                }
19794
19795                preparedCount++;
19796            }
19797        }
19798
19799        if (restoreconNeeded) {
19800            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19801                SELinuxMMAC.setRestoreconDone(ceDir);
19802            }
19803            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19804                SELinuxMMAC.setRestoreconDone(deDir);
19805            }
19806        }
19807
19808        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19809                + " packages; restoreconNeeded was " + restoreconNeeded);
19810    }
19811
19812    /**
19813     * Prepare app data for the given app just after it was installed or
19814     * upgraded. This method carefully only touches users that it's installed
19815     * for, and it forces a restorecon to handle any seinfo changes.
19816     * <p>
19817     * Verifies that directories exist and that ownership and labeling is
19818     * correct for all installed apps. If there is an ownership mismatch, it
19819     * will try recovering system apps by wiping data; third-party app data is
19820     * left intact.
19821     * <p>
19822     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19823     */
19824    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19825        final PackageSetting ps;
19826        synchronized (mPackages) {
19827            ps = mSettings.mPackages.get(pkg.packageName);
19828            mSettings.writeKernelMappingLPr(ps);
19829        }
19830
19831        final UserManager um = mContext.getSystemService(UserManager.class);
19832        UserManagerInternal umInternal = getUserManagerInternal();
19833        for (UserInfo user : um.getUsers()) {
19834            final int flags;
19835            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19836                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19837            } else if (umInternal.isUserRunning(user.id)) {
19838                flags = StorageManager.FLAG_STORAGE_DE;
19839            } else {
19840                continue;
19841            }
19842
19843            if (ps.getInstalled(user.id)) {
19844                // Whenever an app changes, force a restorecon of its data
19845                // TODO: when user data is locked, mark that we're still dirty
19846                prepareAppDataLIF(pkg, user.id, flags, true);
19847            }
19848        }
19849    }
19850
19851    /**
19852     * Prepare app data for the given app.
19853     * <p>
19854     * Verifies that directories exist and that ownership and labeling is
19855     * correct for all installed apps. If there is an ownership mismatch, this
19856     * will try recovering system apps by wiping data; third-party app data is
19857     * left intact.
19858     */
19859    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19860            boolean restoreconNeeded) {
19861        if (pkg == null) {
19862            Slog.wtf(TAG, "Package was null!", new Throwable());
19863            return;
19864        }
19865        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19866        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19867        for (int i = 0; i < childCount; i++) {
19868            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19869        }
19870    }
19871
19872    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19873            boolean restoreconNeeded) {
19874        if (DEBUG_APP_DATA) {
19875            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19876                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19877        }
19878
19879        final String volumeUuid = pkg.volumeUuid;
19880        final String packageName = pkg.packageName;
19881        final ApplicationInfo app = pkg.applicationInfo;
19882        final int appId = UserHandle.getAppId(app.uid);
19883
19884        Preconditions.checkNotNull(app.seinfo);
19885
19886        try {
19887            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19888                    appId, app.seinfo, app.targetSdkVersion);
19889        } catch (InstallerException e) {
19890            if (app.isSystemApp()) {
19891                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19892                        + ", but trying to recover: " + e);
19893                destroyAppDataLeafLIF(pkg, userId, flags);
19894                try {
19895                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19896                            appId, app.seinfo, app.targetSdkVersion);
19897                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19898                } catch (InstallerException e2) {
19899                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19900                }
19901            } else {
19902                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19903            }
19904        }
19905
19906        if (restoreconNeeded) {
19907            try {
19908                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19909                        app.seinfo);
19910            } catch (InstallerException e) {
19911                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19912            }
19913        }
19914
19915        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19916            try {
19917                // CE storage is unlocked right now, so read out the inode and
19918                // remember for use later when it's locked
19919                // TODO: mark this structure as dirty so we persist it!
19920                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19921                        StorageManager.FLAG_STORAGE_CE);
19922                synchronized (mPackages) {
19923                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19924                    if (ps != null) {
19925                        ps.setCeDataInode(ceDataInode, userId);
19926                    }
19927                }
19928            } catch (InstallerException e) {
19929                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19930            }
19931        }
19932
19933        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19934    }
19935
19936    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19937        if (pkg == null) {
19938            Slog.wtf(TAG, "Package was null!", new Throwable());
19939            return;
19940        }
19941        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19942        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19943        for (int i = 0; i < childCount; i++) {
19944            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19945        }
19946    }
19947
19948    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19949        final String volumeUuid = pkg.volumeUuid;
19950        final String packageName = pkg.packageName;
19951        final ApplicationInfo app = pkg.applicationInfo;
19952
19953        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19954            // Create a native library symlink only if we have native libraries
19955            // and if the native libraries are 32 bit libraries. We do not provide
19956            // this symlink for 64 bit libraries.
19957            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19958                final String nativeLibPath = app.nativeLibraryDir;
19959                try {
19960                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19961                            nativeLibPath, userId);
19962                } catch (InstallerException e) {
19963                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19964                }
19965            }
19966        }
19967    }
19968
19969    /**
19970     * For system apps on non-FBE devices, this method migrates any existing
19971     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19972     * requested by the app.
19973     */
19974    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19975        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19976                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19977            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19978                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19979            try {
19980                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19981                        storageTarget);
19982            } catch (InstallerException e) {
19983                logCriticalInfo(Log.WARN,
19984                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19985            }
19986            return true;
19987        } else {
19988            return false;
19989        }
19990    }
19991
19992    public PackageFreezer freezePackage(String packageName, String killReason) {
19993        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
19994    }
19995
19996    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
19997        return new PackageFreezer(packageName, userId, killReason);
19998    }
19999
20000    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20001            String killReason) {
20002        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20003    }
20004
20005    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20006            String killReason) {
20007        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20008            return new PackageFreezer();
20009        } else {
20010            return freezePackage(packageName, userId, killReason);
20011        }
20012    }
20013
20014    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20015            String killReason) {
20016        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20017    }
20018
20019    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20020            String killReason) {
20021        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20022            return new PackageFreezer();
20023        } else {
20024            return freezePackage(packageName, userId, killReason);
20025        }
20026    }
20027
20028    /**
20029     * Class that freezes and kills the given package upon creation, and
20030     * unfreezes it upon closing. This is typically used when doing surgery on
20031     * app code/data to prevent the app from running while you're working.
20032     */
20033    private class PackageFreezer implements AutoCloseable {
20034        private final String mPackageName;
20035        private final PackageFreezer[] mChildren;
20036
20037        private final boolean mWeFroze;
20038
20039        private final AtomicBoolean mClosed = new AtomicBoolean();
20040        private final CloseGuard mCloseGuard = CloseGuard.get();
20041
20042        /**
20043         * Create and return a stub freezer that doesn't actually do anything,
20044         * typically used when someone requested
20045         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20046         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20047         */
20048        public PackageFreezer() {
20049            mPackageName = null;
20050            mChildren = null;
20051            mWeFroze = false;
20052            mCloseGuard.open("close");
20053        }
20054
20055        public PackageFreezer(String packageName, int userId, String killReason) {
20056            synchronized (mPackages) {
20057                mPackageName = packageName;
20058                mWeFroze = mFrozenPackages.add(mPackageName);
20059
20060                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20061                if (ps != null) {
20062                    killApplication(ps.name, ps.appId, userId, killReason);
20063                }
20064
20065                final PackageParser.Package p = mPackages.get(packageName);
20066                if (p != null && p.childPackages != null) {
20067                    final int N = p.childPackages.size();
20068                    mChildren = new PackageFreezer[N];
20069                    for (int i = 0; i < N; i++) {
20070                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20071                                userId, killReason);
20072                    }
20073                } else {
20074                    mChildren = null;
20075                }
20076            }
20077            mCloseGuard.open("close");
20078        }
20079
20080        @Override
20081        protected void finalize() throws Throwable {
20082            try {
20083                mCloseGuard.warnIfOpen();
20084                close();
20085            } finally {
20086                super.finalize();
20087            }
20088        }
20089
20090        @Override
20091        public void close() {
20092            mCloseGuard.close();
20093            if (mClosed.compareAndSet(false, true)) {
20094                synchronized (mPackages) {
20095                    if (mWeFroze) {
20096                        mFrozenPackages.remove(mPackageName);
20097                    }
20098
20099                    if (mChildren != null) {
20100                        for (PackageFreezer freezer : mChildren) {
20101                            freezer.close();
20102                        }
20103                    }
20104                }
20105            }
20106        }
20107    }
20108
20109    /**
20110     * Verify that given package is currently frozen.
20111     */
20112    private void checkPackageFrozen(String packageName) {
20113        synchronized (mPackages) {
20114            if (!mFrozenPackages.contains(packageName)) {
20115                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20116            }
20117        }
20118    }
20119
20120    @Override
20121    public int movePackage(final String packageName, final String volumeUuid) {
20122        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20123
20124        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20125        final int moveId = mNextMoveId.getAndIncrement();
20126        mHandler.post(new Runnable() {
20127            @Override
20128            public void run() {
20129                try {
20130                    movePackageInternal(packageName, volumeUuid, moveId, user);
20131                } catch (PackageManagerException e) {
20132                    Slog.w(TAG, "Failed to move " + packageName, e);
20133                    mMoveCallbacks.notifyStatusChanged(moveId,
20134                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20135                }
20136            }
20137        });
20138        return moveId;
20139    }
20140
20141    private void movePackageInternal(final String packageName, final String volumeUuid,
20142            final int moveId, UserHandle user) throws PackageManagerException {
20143        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20144        final PackageManager pm = mContext.getPackageManager();
20145
20146        final boolean currentAsec;
20147        final String currentVolumeUuid;
20148        final File codeFile;
20149        final String installerPackageName;
20150        final String packageAbiOverride;
20151        final int appId;
20152        final String seinfo;
20153        final String label;
20154        final int targetSdkVersion;
20155        final PackageFreezer freezer;
20156        final int[] installedUserIds;
20157
20158        // reader
20159        synchronized (mPackages) {
20160            final PackageParser.Package pkg = mPackages.get(packageName);
20161            final PackageSetting ps = mSettings.mPackages.get(packageName);
20162            if (pkg == null || ps == null) {
20163                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20164            }
20165
20166            if (pkg.applicationInfo.isSystemApp()) {
20167                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20168                        "Cannot move system application");
20169            }
20170
20171            if (pkg.applicationInfo.isExternalAsec()) {
20172                currentAsec = true;
20173                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20174            } else if (pkg.applicationInfo.isForwardLocked()) {
20175                currentAsec = true;
20176                currentVolumeUuid = "forward_locked";
20177            } else {
20178                currentAsec = false;
20179                currentVolumeUuid = ps.volumeUuid;
20180
20181                final File probe = new File(pkg.codePath);
20182                final File probeOat = new File(probe, "oat");
20183                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20184                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20185                            "Move only supported for modern cluster style installs");
20186                }
20187            }
20188
20189            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20190                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20191                        "Package already moved to " + volumeUuid);
20192            }
20193            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20194                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20195                        "Device admin cannot be moved");
20196            }
20197
20198            if (mFrozenPackages.contains(packageName)) {
20199                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20200                        "Failed to move already frozen package");
20201            }
20202
20203            codeFile = new File(pkg.codePath);
20204            installerPackageName = ps.installerPackageName;
20205            packageAbiOverride = ps.cpuAbiOverrideString;
20206            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20207            seinfo = pkg.applicationInfo.seinfo;
20208            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20209            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20210            freezer = freezePackage(packageName, "movePackageInternal");
20211            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20212        }
20213
20214        final Bundle extras = new Bundle();
20215        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20216        extras.putString(Intent.EXTRA_TITLE, label);
20217        mMoveCallbacks.notifyCreated(moveId, extras);
20218
20219        int installFlags;
20220        final boolean moveCompleteApp;
20221        final File measurePath;
20222
20223        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20224            installFlags = INSTALL_INTERNAL;
20225            moveCompleteApp = !currentAsec;
20226            measurePath = Environment.getDataAppDirectory(volumeUuid);
20227        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20228            installFlags = INSTALL_EXTERNAL;
20229            moveCompleteApp = false;
20230            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20231        } else {
20232            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20233            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20234                    || !volume.isMountedWritable()) {
20235                freezer.close();
20236                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20237                        "Move location not mounted private volume");
20238            }
20239
20240            Preconditions.checkState(!currentAsec);
20241
20242            installFlags = INSTALL_INTERNAL;
20243            moveCompleteApp = true;
20244            measurePath = Environment.getDataAppDirectory(volumeUuid);
20245        }
20246
20247        final PackageStats stats = new PackageStats(null, -1);
20248        synchronized (mInstaller) {
20249            for (int userId : installedUserIds) {
20250                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20251                    freezer.close();
20252                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20253                            "Failed to measure package size");
20254                }
20255            }
20256        }
20257
20258        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20259                + stats.dataSize);
20260
20261        final long startFreeBytes = measurePath.getFreeSpace();
20262        final long sizeBytes;
20263        if (moveCompleteApp) {
20264            sizeBytes = stats.codeSize + stats.dataSize;
20265        } else {
20266            sizeBytes = stats.codeSize;
20267        }
20268
20269        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20270            freezer.close();
20271            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20272                    "Not enough free space to move");
20273        }
20274
20275        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20276
20277        final CountDownLatch installedLatch = new CountDownLatch(1);
20278        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20279            @Override
20280            public void onUserActionRequired(Intent intent) throws RemoteException {
20281                throw new IllegalStateException();
20282            }
20283
20284            @Override
20285            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20286                    Bundle extras) throws RemoteException {
20287                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20288                        + PackageManager.installStatusToString(returnCode, msg));
20289
20290                installedLatch.countDown();
20291                freezer.close();
20292
20293                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20294                switch (status) {
20295                    case PackageInstaller.STATUS_SUCCESS:
20296                        mMoveCallbacks.notifyStatusChanged(moveId,
20297                                PackageManager.MOVE_SUCCEEDED);
20298                        break;
20299                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20300                        mMoveCallbacks.notifyStatusChanged(moveId,
20301                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20302                        break;
20303                    default:
20304                        mMoveCallbacks.notifyStatusChanged(moveId,
20305                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20306                        break;
20307                }
20308            }
20309        };
20310
20311        final MoveInfo move;
20312        if (moveCompleteApp) {
20313            // Kick off a thread to report progress estimates
20314            new Thread() {
20315                @Override
20316                public void run() {
20317                    while (true) {
20318                        try {
20319                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20320                                break;
20321                            }
20322                        } catch (InterruptedException ignored) {
20323                        }
20324
20325                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20326                        final int progress = 10 + (int) MathUtils.constrain(
20327                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20328                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20329                    }
20330                }
20331            }.start();
20332
20333            final String dataAppName = codeFile.getName();
20334            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20335                    dataAppName, appId, seinfo, targetSdkVersion);
20336        } else {
20337            move = null;
20338        }
20339
20340        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20341
20342        final Message msg = mHandler.obtainMessage(INIT_COPY);
20343        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20344        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20345                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20346                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20347        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20348        msg.obj = params;
20349
20350        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20351                System.identityHashCode(msg.obj));
20352        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20353                System.identityHashCode(msg.obj));
20354
20355        mHandler.sendMessage(msg);
20356    }
20357
20358    @Override
20359    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20360        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20361
20362        final int realMoveId = mNextMoveId.getAndIncrement();
20363        final Bundle extras = new Bundle();
20364        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20365        mMoveCallbacks.notifyCreated(realMoveId, extras);
20366
20367        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20368            @Override
20369            public void onCreated(int moveId, Bundle extras) {
20370                // Ignored
20371            }
20372
20373            @Override
20374            public void onStatusChanged(int moveId, int status, long estMillis) {
20375                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20376            }
20377        };
20378
20379        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20380        storage.setPrimaryStorageUuid(volumeUuid, callback);
20381        return realMoveId;
20382    }
20383
20384    @Override
20385    public int getMoveStatus(int moveId) {
20386        mContext.enforceCallingOrSelfPermission(
20387                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20388        return mMoveCallbacks.mLastStatus.get(moveId);
20389    }
20390
20391    @Override
20392    public void registerMoveCallback(IPackageMoveObserver callback) {
20393        mContext.enforceCallingOrSelfPermission(
20394                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20395        mMoveCallbacks.register(callback);
20396    }
20397
20398    @Override
20399    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20400        mContext.enforceCallingOrSelfPermission(
20401                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20402        mMoveCallbacks.unregister(callback);
20403    }
20404
20405    @Override
20406    public boolean setInstallLocation(int loc) {
20407        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20408                null);
20409        if (getInstallLocation() == loc) {
20410            return true;
20411        }
20412        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20413                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20414            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20415                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20416            return true;
20417        }
20418        return false;
20419   }
20420
20421    @Override
20422    public int getInstallLocation() {
20423        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20424                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20425                PackageHelper.APP_INSTALL_AUTO);
20426    }
20427
20428    /** Called by UserManagerService */
20429    void cleanUpUser(UserManagerService userManager, int userHandle) {
20430        synchronized (mPackages) {
20431            mDirtyUsers.remove(userHandle);
20432            mUserNeedsBadging.delete(userHandle);
20433            mSettings.removeUserLPw(userHandle);
20434            mPendingBroadcasts.remove(userHandle);
20435            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20436            removeUnusedPackagesLPw(userManager, userHandle);
20437        }
20438    }
20439
20440    /**
20441     * We're removing userHandle and would like to remove any downloaded packages
20442     * that are no longer in use by any other user.
20443     * @param userHandle the user being removed
20444     */
20445    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20446        final boolean DEBUG_CLEAN_APKS = false;
20447        int [] users = userManager.getUserIds();
20448        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20449        while (psit.hasNext()) {
20450            PackageSetting ps = psit.next();
20451            if (ps.pkg == null) {
20452                continue;
20453            }
20454            final String packageName = ps.pkg.packageName;
20455            // Skip over if system app
20456            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20457                continue;
20458            }
20459            if (DEBUG_CLEAN_APKS) {
20460                Slog.i(TAG, "Checking package " + packageName);
20461            }
20462            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20463            if (keep) {
20464                if (DEBUG_CLEAN_APKS) {
20465                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20466                }
20467            } else {
20468                for (int i = 0; i < users.length; i++) {
20469                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20470                        keep = true;
20471                        if (DEBUG_CLEAN_APKS) {
20472                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20473                                    + users[i]);
20474                        }
20475                        break;
20476                    }
20477                }
20478            }
20479            if (!keep) {
20480                if (DEBUG_CLEAN_APKS) {
20481                    Slog.i(TAG, "  Removing package " + packageName);
20482                }
20483                mHandler.post(new Runnable() {
20484                    public void run() {
20485                        deletePackageX(packageName, userHandle, 0);
20486                    } //end run
20487                });
20488            }
20489        }
20490    }
20491
20492    /** Called by UserManagerService */
20493    void createNewUser(int userId) {
20494        synchronized (mInstallLock) {
20495            mSettings.createNewUserLI(this, mInstaller, userId);
20496        }
20497        synchronized (mPackages) {
20498            scheduleWritePackageRestrictionsLocked(userId);
20499            scheduleWritePackageListLocked(userId);
20500            applyFactoryDefaultBrowserLPw(userId);
20501            primeDomainVerificationsLPw(userId);
20502        }
20503    }
20504
20505    void onNewUserCreated(final int userId) {
20506        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20507        // If permission review for legacy apps is required, we represent
20508        // dagerous permissions for such apps as always granted runtime
20509        // permissions to keep per user flag state whether review is needed.
20510        // Hence, if a new user is added we have to propagate dangerous
20511        // permission grants for these legacy apps.
20512        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20513            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20514                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20515        }
20516    }
20517
20518    @Override
20519    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20520        mContext.enforceCallingOrSelfPermission(
20521                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20522                "Only package verification agents can read the verifier device identity");
20523
20524        synchronized (mPackages) {
20525            return mSettings.getVerifierDeviceIdentityLPw();
20526        }
20527    }
20528
20529    @Override
20530    public void setPermissionEnforced(String permission, boolean enforced) {
20531        // TODO: Now that we no longer change GID for storage, this should to away.
20532        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20533                "setPermissionEnforced");
20534        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20535            synchronized (mPackages) {
20536                if (mSettings.mReadExternalStorageEnforced == null
20537                        || mSettings.mReadExternalStorageEnforced != enforced) {
20538                    mSettings.mReadExternalStorageEnforced = enforced;
20539                    mSettings.writeLPr();
20540                }
20541            }
20542            // kill any non-foreground processes so we restart them and
20543            // grant/revoke the GID.
20544            final IActivityManager am = ActivityManagerNative.getDefault();
20545            if (am != null) {
20546                final long token = Binder.clearCallingIdentity();
20547                try {
20548                    am.killProcessesBelowForeground("setPermissionEnforcement");
20549                } catch (RemoteException e) {
20550                } finally {
20551                    Binder.restoreCallingIdentity(token);
20552                }
20553            }
20554        } else {
20555            throw new IllegalArgumentException("No selective enforcement for " + permission);
20556        }
20557    }
20558
20559    @Override
20560    @Deprecated
20561    public boolean isPermissionEnforced(String permission) {
20562        return true;
20563    }
20564
20565    @Override
20566    public boolean isStorageLow() {
20567        final long token = Binder.clearCallingIdentity();
20568        try {
20569            final DeviceStorageMonitorInternal
20570                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20571            if (dsm != null) {
20572                return dsm.isMemoryLow();
20573            } else {
20574                return false;
20575            }
20576        } finally {
20577            Binder.restoreCallingIdentity(token);
20578        }
20579    }
20580
20581    @Override
20582    public IPackageInstaller getPackageInstaller() {
20583        return mInstallerService;
20584    }
20585
20586    private boolean userNeedsBadging(int userId) {
20587        int index = mUserNeedsBadging.indexOfKey(userId);
20588        if (index < 0) {
20589            final UserInfo userInfo;
20590            final long token = Binder.clearCallingIdentity();
20591            try {
20592                userInfo = sUserManager.getUserInfo(userId);
20593            } finally {
20594                Binder.restoreCallingIdentity(token);
20595            }
20596            final boolean b;
20597            if (userInfo != null && userInfo.isManagedProfile()) {
20598                b = true;
20599            } else {
20600                b = false;
20601            }
20602            mUserNeedsBadging.put(userId, b);
20603            return b;
20604        }
20605        return mUserNeedsBadging.valueAt(index);
20606    }
20607
20608    @Override
20609    public KeySet getKeySetByAlias(String packageName, String alias) {
20610        if (packageName == null || alias == null) {
20611            return null;
20612        }
20613        synchronized(mPackages) {
20614            final PackageParser.Package pkg = mPackages.get(packageName);
20615            if (pkg == null) {
20616                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20617                throw new IllegalArgumentException("Unknown package: " + packageName);
20618            }
20619            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20620            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20621        }
20622    }
20623
20624    @Override
20625    public KeySet getSigningKeySet(String packageName) {
20626        if (packageName == null) {
20627            return null;
20628        }
20629        synchronized(mPackages) {
20630            final PackageParser.Package pkg = mPackages.get(packageName);
20631            if (pkg == null) {
20632                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20633                throw new IllegalArgumentException("Unknown package: " + packageName);
20634            }
20635            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20636                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20637                throw new SecurityException("May not access signing KeySet of other apps.");
20638            }
20639            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20640            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20641        }
20642    }
20643
20644    @Override
20645    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20646        if (packageName == null || ks == null) {
20647            return false;
20648        }
20649        synchronized(mPackages) {
20650            final PackageParser.Package pkg = mPackages.get(packageName);
20651            if (pkg == null) {
20652                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20653                throw new IllegalArgumentException("Unknown package: " + packageName);
20654            }
20655            IBinder ksh = ks.getToken();
20656            if (ksh instanceof KeySetHandle) {
20657                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20658                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20659            }
20660            return false;
20661        }
20662    }
20663
20664    @Override
20665    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20666        if (packageName == null || ks == null) {
20667            return false;
20668        }
20669        synchronized(mPackages) {
20670            final PackageParser.Package pkg = mPackages.get(packageName);
20671            if (pkg == null) {
20672                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20673                throw new IllegalArgumentException("Unknown package: " + packageName);
20674            }
20675            IBinder ksh = ks.getToken();
20676            if (ksh instanceof KeySetHandle) {
20677                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20678                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20679            }
20680            return false;
20681        }
20682    }
20683
20684    private void deletePackageIfUnusedLPr(final String packageName) {
20685        PackageSetting ps = mSettings.mPackages.get(packageName);
20686        if (ps == null) {
20687            return;
20688        }
20689        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20690            // TODO Implement atomic delete if package is unused
20691            // It is currently possible that the package will be deleted even if it is installed
20692            // after this method returns.
20693            mHandler.post(new Runnable() {
20694                public void run() {
20695                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20696                }
20697            });
20698        }
20699    }
20700
20701    /**
20702     * Check and throw if the given before/after packages would be considered a
20703     * downgrade.
20704     */
20705    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20706            throws PackageManagerException {
20707        if (after.versionCode < before.mVersionCode) {
20708            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20709                    "Update version code " + after.versionCode + " is older than current "
20710                    + before.mVersionCode);
20711        } else if (after.versionCode == before.mVersionCode) {
20712            if (after.baseRevisionCode < before.baseRevisionCode) {
20713                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20714                        "Update base revision code " + after.baseRevisionCode
20715                        + " is older than current " + before.baseRevisionCode);
20716            }
20717
20718            if (!ArrayUtils.isEmpty(after.splitNames)) {
20719                for (int i = 0; i < after.splitNames.length; i++) {
20720                    final String splitName = after.splitNames[i];
20721                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20722                    if (j != -1) {
20723                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20724                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20725                                    "Update split " + splitName + " revision code "
20726                                    + after.splitRevisionCodes[i] + " is older than current "
20727                                    + before.splitRevisionCodes[j]);
20728                        }
20729                    }
20730                }
20731            }
20732        }
20733    }
20734
20735    private static class MoveCallbacks extends Handler {
20736        private static final int MSG_CREATED = 1;
20737        private static final int MSG_STATUS_CHANGED = 2;
20738
20739        private final RemoteCallbackList<IPackageMoveObserver>
20740                mCallbacks = new RemoteCallbackList<>();
20741
20742        private final SparseIntArray mLastStatus = new SparseIntArray();
20743
20744        public MoveCallbacks(Looper looper) {
20745            super(looper);
20746        }
20747
20748        public void register(IPackageMoveObserver callback) {
20749            mCallbacks.register(callback);
20750        }
20751
20752        public void unregister(IPackageMoveObserver callback) {
20753            mCallbacks.unregister(callback);
20754        }
20755
20756        @Override
20757        public void handleMessage(Message msg) {
20758            final SomeArgs args = (SomeArgs) msg.obj;
20759            final int n = mCallbacks.beginBroadcast();
20760            for (int i = 0; i < n; i++) {
20761                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20762                try {
20763                    invokeCallback(callback, msg.what, args);
20764                } catch (RemoteException ignored) {
20765                }
20766            }
20767            mCallbacks.finishBroadcast();
20768            args.recycle();
20769        }
20770
20771        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20772                throws RemoteException {
20773            switch (what) {
20774                case MSG_CREATED: {
20775                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20776                    break;
20777                }
20778                case MSG_STATUS_CHANGED: {
20779                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20780                    break;
20781                }
20782            }
20783        }
20784
20785        private void notifyCreated(int moveId, Bundle extras) {
20786            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20787
20788            final SomeArgs args = SomeArgs.obtain();
20789            args.argi1 = moveId;
20790            args.arg2 = extras;
20791            obtainMessage(MSG_CREATED, args).sendToTarget();
20792        }
20793
20794        private void notifyStatusChanged(int moveId, int status) {
20795            notifyStatusChanged(moveId, status, -1);
20796        }
20797
20798        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20799            Slog.v(TAG, "Move " + moveId + " status " + status);
20800
20801            final SomeArgs args = SomeArgs.obtain();
20802            args.argi1 = moveId;
20803            args.argi2 = status;
20804            args.arg3 = estMillis;
20805            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20806
20807            synchronized (mLastStatus) {
20808                mLastStatus.put(moveId, status);
20809            }
20810        }
20811    }
20812
20813    private final static class OnPermissionChangeListeners extends Handler {
20814        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20815
20816        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20817                new RemoteCallbackList<>();
20818
20819        public OnPermissionChangeListeners(Looper looper) {
20820            super(looper);
20821        }
20822
20823        @Override
20824        public void handleMessage(Message msg) {
20825            switch (msg.what) {
20826                case MSG_ON_PERMISSIONS_CHANGED: {
20827                    final int uid = msg.arg1;
20828                    handleOnPermissionsChanged(uid);
20829                } break;
20830            }
20831        }
20832
20833        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20834            mPermissionListeners.register(listener);
20835
20836        }
20837
20838        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20839            mPermissionListeners.unregister(listener);
20840        }
20841
20842        public void onPermissionsChanged(int uid) {
20843            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20844                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20845            }
20846        }
20847
20848        private void handleOnPermissionsChanged(int uid) {
20849            final int count = mPermissionListeners.beginBroadcast();
20850            try {
20851                for (int i = 0; i < count; i++) {
20852                    IOnPermissionsChangeListener callback = mPermissionListeners
20853                            .getBroadcastItem(i);
20854                    try {
20855                        callback.onPermissionsChanged(uid);
20856                    } catch (RemoteException e) {
20857                        Log.e(TAG, "Permission listener is dead", e);
20858                    }
20859                }
20860            } finally {
20861                mPermissionListeners.finishBroadcast();
20862            }
20863        }
20864    }
20865
20866    private class PackageManagerInternalImpl extends PackageManagerInternal {
20867        @Override
20868        public void setLocationPackagesProvider(PackagesProvider provider) {
20869            synchronized (mPackages) {
20870                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20871            }
20872        }
20873
20874        @Override
20875        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20876            synchronized (mPackages) {
20877                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20878            }
20879        }
20880
20881        @Override
20882        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20883            synchronized (mPackages) {
20884                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20885            }
20886        }
20887
20888        @Override
20889        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20890            synchronized (mPackages) {
20891                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20892            }
20893        }
20894
20895        @Override
20896        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20897            synchronized (mPackages) {
20898                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20899            }
20900        }
20901
20902        @Override
20903        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20904            synchronized (mPackages) {
20905                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20906            }
20907        }
20908
20909        @Override
20910        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20911            synchronized (mPackages) {
20912                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20913                        packageName, userId);
20914            }
20915        }
20916
20917        @Override
20918        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20919            synchronized (mPackages) {
20920                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20921                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20922                        packageName, userId);
20923            }
20924        }
20925
20926        @Override
20927        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20928            synchronized (mPackages) {
20929                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20930                        packageName, userId);
20931            }
20932        }
20933
20934        @Override
20935        public void setKeepUninstalledPackages(final List<String> packageList) {
20936            Preconditions.checkNotNull(packageList);
20937            List<String> removedFromList = null;
20938            synchronized (mPackages) {
20939                if (mKeepUninstalledPackages != null) {
20940                    final int packagesCount = mKeepUninstalledPackages.size();
20941                    for (int i = 0; i < packagesCount; i++) {
20942                        String oldPackage = mKeepUninstalledPackages.get(i);
20943                        if (packageList != null && packageList.contains(oldPackage)) {
20944                            continue;
20945                        }
20946                        if (removedFromList == null) {
20947                            removedFromList = new ArrayList<>();
20948                        }
20949                        removedFromList.add(oldPackage);
20950                    }
20951                }
20952                mKeepUninstalledPackages = new ArrayList<>(packageList);
20953                if (removedFromList != null) {
20954                    final int removedCount = removedFromList.size();
20955                    for (int i = 0; i < removedCount; i++) {
20956                        deletePackageIfUnusedLPr(removedFromList.get(i));
20957                    }
20958                }
20959            }
20960        }
20961
20962        @Override
20963        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20964            synchronized (mPackages) {
20965                // If we do not support permission review, done.
20966                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20967                    return false;
20968                }
20969
20970                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20971                if (packageSetting == null) {
20972                    return false;
20973                }
20974
20975                // Permission review applies only to apps not supporting the new permission model.
20976                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20977                    return false;
20978                }
20979
20980                // Legacy apps have the permission and get user consent on launch.
20981                PermissionsState permissionsState = packageSetting.getPermissionsState();
20982                return permissionsState.isPermissionReviewRequired(userId);
20983            }
20984        }
20985
20986        @Override
20987        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20988            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20989        }
20990
20991        @Override
20992        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20993                int userId) {
20994            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20995        }
20996
20997        @Override
20998        public void setDeviceAndProfileOwnerPackages(
20999                int deviceOwnerUserId, String deviceOwnerPackage,
21000                SparseArray<String> profileOwnerPackages) {
21001            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21002                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21003        }
21004
21005        @Override
21006        public boolean isPackageDataProtected(int userId, String packageName) {
21007            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21008        }
21009    }
21010
21011    @Override
21012    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21013        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21014        synchronized (mPackages) {
21015            final long identity = Binder.clearCallingIdentity();
21016            try {
21017                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21018                        packageNames, userId);
21019            } finally {
21020                Binder.restoreCallingIdentity(identity);
21021            }
21022        }
21023    }
21024
21025    private static void enforceSystemOrPhoneCaller(String tag) {
21026        int callingUid = Binder.getCallingUid();
21027        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21028            throw new SecurityException(
21029                    "Cannot call " + tag + " from UID " + callingUid);
21030        }
21031    }
21032
21033    boolean isHistoricalPackageUsageAvailable() {
21034        return mPackageUsage.isHistoricalPackageUsageAvailable();
21035    }
21036
21037    /**
21038     * Return a <b>copy</b> of the collection of packages known to the package manager.
21039     * @return A copy of the values of mPackages.
21040     */
21041    Collection<PackageParser.Package> getPackages() {
21042        synchronized (mPackages) {
21043            return new ArrayList<>(mPackages.values());
21044        }
21045    }
21046
21047    /**
21048     * Logs process start information (including base APK hash) to the security log.
21049     * @hide
21050     */
21051    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21052            String apkFile, int pid) {
21053        if (!SecurityLog.isLoggingEnabled()) {
21054            return;
21055        }
21056        Bundle data = new Bundle();
21057        data.putLong("startTimestamp", System.currentTimeMillis());
21058        data.putString("processName", processName);
21059        data.putInt("uid", uid);
21060        data.putString("seinfo", seinfo);
21061        data.putString("apkFile", apkFile);
21062        data.putInt("pid", pid);
21063        Message msg = mProcessLoggingHandler.obtainMessage(
21064                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21065        msg.setData(data);
21066        mProcessLoggingHandler.sendMessage(msg);
21067    }
21068
21069    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21070        return mCompilerStats.getPackageStats(pkgName);
21071    }
21072
21073    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21074        return getOrCreateCompilerPackageStats(pkg.packageName);
21075    }
21076
21077    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21078        return mCompilerStats.getOrCreatePackageStats(pkgName);
21079    }
21080
21081    public void deleteCompilerPackageStats(String pkgName) {
21082        mCompilerStats.deletePackageStats(pkgName);
21083    }
21084}
21085