PackageManagerService.java revision 0b69970e36dece05302b60a685a9bb0aa6546ed3
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    /** The location for ASEC container files on internal storage. */
542    final String mAsecInternalPath;
543
544    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
545    // LOCK HELD.  Can be called with mInstallLock held.
546    @GuardedBy("mInstallLock")
547    final Installer mInstaller;
548
549    /** Directory where installed third-party apps stored */
550    final File mAppInstallDir;
551    final File mEphemeralInstallDir;
552
553    /**
554     * Directory to which applications installed internally have their
555     * 32 bit native libraries copied.
556     */
557    private File mAppLib32InstallDir;
558
559    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
560    // apps.
561    final File mDrmAppPrivateInstallDir;
562
563    // ----------------------------------------------------------------
564
565    // Lock for state used when installing and doing other long running
566    // operations.  Methods that must be called with this lock held have
567    // the suffix "LI".
568    final Object mInstallLock = new Object();
569
570    // ----------------------------------------------------------------
571
572    // Keys are String (package name), values are Package.  This also serves
573    // as the lock for the global state.  Methods that must be called with
574    // this lock held have the prefix "LP".
575    @GuardedBy("mPackages")
576    final ArrayMap<String, PackageParser.Package> mPackages =
577            new ArrayMap<String, PackageParser.Package>();
578
579    final ArrayMap<String, Set<String>> mKnownCodebase =
580            new ArrayMap<String, Set<String>>();
581
582    // Tracks available target package names -> overlay package paths.
583    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
584        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
585
586    /**
587     * Tracks new system packages [received in an OTA] that we expect to
588     * find updated user-installed versions. Keys are package name, values
589     * are package location.
590     */
591    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
592    /**
593     * Tracks high priority intent filters for protected actions. During boot, certain
594     * filter actions are protected and should never be allowed to have a high priority
595     * intent filter for them. However, there is one, and only one exception -- the
596     * setup wizard. It must be able to define a high priority intent filter for these
597     * actions to ensure there are no escapes from the wizard. We need to delay processing
598     * of these during boot as we need to look at all of the system packages in order
599     * to know which component is the setup wizard.
600     */
601    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
602    /**
603     * Whether or not processing protected filters should be deferred.
604     */
605    private boolean mDeferProtectedFilters = true;
606
607    /**
608     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
609     */
610    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
611    /**
612     * Whether or not system app permissions should be promoted from install to runtime.
613     */
614    boolean mPromoteSystemApps;
615
616    @GuardedBy("mPackages")
617    final Settings mSettings;
618
619    /**
620     * Set of package names that are currently "frozen", which means active
621     * surgery is being done on the code/data for that package. The platform
622     * will refuse to launch frozen packages to avoid race conditions.
623     *
624     * @see PackageFreezer
625     */
626    @GuardedBy("mPackages")
627    final ArraySet<String> mFrozenPackages = new ArraySet<>();
628
629    final ProtectedPackages mProtectedPackages;
630
631    boolean mFirstBoot;
632
633    // System configuration read by SystemConfig.
634    final int[] mGlobalGids;
635    final SparseArray<ArraySet<String>> mSystemPermissions;
636    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
637
638    // If mac_permissions.xml was found for seinfo labeling.
639    boolean mFoundPolicyFile;
640
641    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
642
643    public static final class SharedLibraryEntry {
644        public final String path;
645        public final String apk;
646
647        SharedLibraryEntry(String _path, String _apk) {
648            path = _path;
649            apk = _apk;
650        }
651    }
652
653    // Currently known shared libraries.
654    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
655            new ArrayMap<String, SharedLibraryEntry>();
656
657    // All available activities, for your resolving pleasure.
658    final ActivityIntentResolver mActivities =
659            new ActivityIntentResolver();
660
661    // All available receivers, for your resolving pleasure.
662    final ActivityIntentResolver mReceivers =
663            new ActivityIntentResolver();
664
665    // All available services, for your resolving pleasure.
666    final ServiceIntentResolver mServices = new ServiceIntentResolver();
667
668    // All available providers, for your resolving pleasure.
669    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
670
671    // Mapping from provider base names (first directory in content URI codePath)
672    // to the provider information.
673    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
674            new ArrayMap<String, PackageParser.Provider>();
675
676    // Mapping from instrumentation class names to info about them.
677    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
678            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
679
680    // Mapping from permission names to info about them.
681    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
682            new ArrayMap<String, PackageParser.PermissionGroup>();
683
684    // Packages whose data we have transfered into another package, thus
685    // should no longer exist.
686    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
687
688    // Broadcast actions that are only available to the system.
689    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
690
691    /** List of packages waiting for verification. */
692    final SparseArray<PackageVerificationState> mPendingVerification
693            = new SparseArray<PackageVerificationState>();
694
695    /** Set of packages associated with each app op permission. */
696    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
697
698    final PackageInstallerService mInstallerService;
699
700    private final PackageDexOptimizer mPackageDexOptimizer;
701
702    private AtomicInteger mNextMoveId = new AtomicInteger();
703    private final MoveCallbacks mMoveCallbacks;
704
705    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
706
707    // Cache of users who need badging.
708    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
709
710    /** Token for keys in mPendingVerification. */
711    private int mPendingVerificationToken = 0;
712
713    volatile boolean mSystemReady;
714    volatile boolean mSafeMode;
715    volatile boolean mHasSystemUidErrors;
716
717    ApplicationInfo mAndroidApplication;
718    final ActivityInfo mResolveActivity = new ActivityInfo();
719    final ResolveInfo mResolveInfo = new ResolveInfo();
720    ComponentName mResolveComponentName;
721    PackageParser.Package mPlatformPackage;
722    ComponentName mCustomResolverComponentName;
723
724    boolean mResolverReplaced = false;
725
726    private final @Nullable ComponentName mIntentFilterVerifierComponent;
727    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
728
729    private int mIntentFilterVerificationToken = 0;
730
731    /** Component that knows whether or not an ephemeral application exists */
732    final ComponentName mEphemeralResolverComponent;
733    /** The service connection to the ephemeral resolver */
734    final EphemeralResolverConnection mEphemeralResolverConnection;
735
736    /** Component used to install ephemeral applications */
737    final ComponentName mEphemeralInstallerComponent;
738    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
739    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
740
741    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
742            = new SparseArray<IntentFilterVerificationState>();
743
744    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
745
746    // List of packages names to keep cached, even if they are uninstalled for all users
747    private List<String> mKeepUninstalledPackages;
748
749    private UserManagerInternal mUserManagerInternal;
750
751    private static class IFVerificationParams {
752        PackageParser.Package pkg;
753        boolean replacing;
754        int userId;
755        int verifierUid;
756
757        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
758                int _userId, int _verifierUid) {
759            pkg = _pkg;
760            replacing = _replacing;
761            userId = _userId;
762            replacing = _replacing;
763            verifierUid = _verifierUid;
764        }
765    }
766
767    private interface IntentFilterVerifier<T extends IntentFilter> {
768        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
769                                               T filter, String packageName);
770        void startVerifications(int userId);
771        void receiveVerificationResponse(int verificationId);
772    }
773
774    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
775        private Context mContext;
776        private ComponentName mIntentFilterVerifierComponent;
777        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
778
779        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
780            mContext = context;
781            mIntentFilterVerifierComponent = verifierComponent;
782        }
783
784        private String getDefaultScheme() {
785            return IntentFilter.SCHEME_HTTPS;
786        }
787
788        @Override
789        public void startVerifications(int userId) {
790            // Launch verifications requests
791            int count = mCurrentIntentFilterVerifications.size();
792            for (int n=0; n<count; n++) {
793                int verificationId = mCurrentIntentFilterVerifications.get(n);
794                final IntentFilterVerificationState ivs =
795                        mIntentFilterVerificationStates.get(verificationId);
796
797                String packageName = ivs.getPackageName();
798
799                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
800                final int filterCount = filters.size();
801                ArraySet<String> domainsSet = new ArraySet<>();
802                for (int m=0; m<filterCount; m++) {
803                    PackageParser.ActivityIntentInfo filter = filters.get(m);
804                    domainsSet.addAll(filter.getHostsList());
805                }
806                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
807                synchronized (mPackages) {
808                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
809                            packageName, domainsList) != null) {
810                        scheduleWriteSettingsLocked();
811                    }
812                }
813                sendVerificationRequest(userId, verificationId, ivs);
814            }
815            mCurrentIntentFilterVerifications.clear();
816        }
817
818        private void sendVerificationRequest(int userId, int verificationId,
819                IntentFilterVerificationState ivs) {
820
821            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
822            verificationIntent.putExtra(
823                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
824                    verificationId);
825            verificationIntent.putExtra(
826                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
827                    getDefaultScheme());
828            verificationIntent.putExtra(
829                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
830                    ivs.getHostsString());
831            verificationIntent.putExtra(
832                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
833                    ivs.getPackageName());
834            verificationIntent.setComponent(mIntentFilterVerifierComponent);
835            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
836
837            UserHandle user = new UserHandle(userId);
838            mContext.sendBroadcastAsUser(verificationIntent, user);
839            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
840                    "Sending IntentFilter verification broadcast");
841        }
842
843        public void receiveVerificationResponse(int verificationId) {
844            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
845
846            final boolean verified = ivs.isVerified();
847
848            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
849            final int count = filters.size();
850            if (DEBUG_DOMAIN_VERIFICATION) {
851                Slog.i(TAG, "Received verification response " + verificationId
852                        + " for " + count + " filters, verified=" + verified);
853            }
854            for (int n=0; n<count; n++) {
855                PackageParser.ActivityIntentInfo filter = filters.get(n);
856                filter.setVerified(verified);
857
858                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
859                        + " verified with result:" + verified + " and hosts:"
860                        + ivs.getHostsString());
861            }
862
863            mIntentFilterVerificationStates.remove(verificationId);
864
865            final String packageName = ivs.getPackageName();
866            IntentFilterVerificationInfo ivi = null;
867
868            synchronized (mPackages) {
869                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
870            }
871            if (ivi == null) {
872                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
873                        + verificationId + " packageName:" + packageName);
874                return;
875            }
876            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
877                    "Updating IntentFilterVerificationInfo for package " + packageName
878                            +" verificationId:" + verificationId);
879
880            synchronized (mPackages) {
881                if (verified) {
882                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
883                } else {
884                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
885                }
886                scheduleWriteSettingsLocked();
887
888                final int userId = ivs.getUserId();
889                if (userId != UserHandle.USER_ALL) {
890                    final int userStatus =
891                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
892
893                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
894                    boolean needUpdate = false;
895
896                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
897                    // already been set by the User thru the Disambiguation dialog
898                    switch (userStatus) {
899                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
900                            if (verified) {
901                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
902                            } else {
903                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
904                            }
905                            needUpdate = true;
906                            break;
907
908                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
909                            if (verified) {
910                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
911                                needUpdate = true;
912                            }
913                            break;
914
915                        default:
916                            // Nothing to do
917                    }
918
919                    if (needUpdate) {
920                        mSettings.updateIntentFilterVerificationStatusLPw(
921                                packageName, updatedStatus, userId);
922                        scheduleWritePackageRestrictionsLocked(userId);
923                    }
924                }
925            }
926        }
927
928        @Override
929        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
930                    ActivityIntentInfo filter, String packageName) {
931            if (!hasValidDomains(filter)) {
932                return false;
933            }
934            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
935            if (ivs == null) {
936                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
937                        packageName);
938            }
939            if (DEBUG_DOMAIN_VERIFICATION) {
940                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
941            }
942            ivs.addFilter(filter);
943            return true;
944        }
945
946        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
947                int userId, int verificationId, String packageName) {
948            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
949                    verifierUid, userId, packageName);
950            ivs.setPendingState();
951            synchronized (mPackages) {
952                mIntentFilterVerificationStates.append(verificationId, ivs);
953                mCurrentIntentFilterVerifications.add(verificationId);
954            }
955            return ivs;
956        }
957    }
958
959    private static boolean hasValidDomains(ActivityIntentInfo filter) {
960        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
961                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
962                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
963    }
964
965    // Set of pending broadcasts for aggregating enable/disable of components.
966    static class PendingPackageBroadcasts {
967        // for each user id, a map of <package name -> components within that package>
968        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
969
970        public PendingPackageBroadcasts() {
971            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
972        }
973
974        public ArrayList<String> get(int userId, String packageName) {
975            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
976            return packages.get(packageName);
977        }
978
979        public void put(int userId, String packageName, ArrayList<String> components) {
980            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
981            packages.put(packageName, components);
982        }
983
984        public void remove(int userId, String packageName) {
985            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
986            if (packages != null) {
987                packages.remove(packageName);
988            }
989        }
990
991        public void remove(int userId) {
992            mUidMap.remove(userId);
993        }
994
995        public int userIdCount() {
996            return mUidMap.size();
997        }
998
999        public int userIdAt(int n) {
1000            return mUidMap.keyAt(n);
1001        }
1002
1003        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1004            return mUidMap.get(userId);
1005        }
1006
1007        public int size() {
1008            // total number of pending broadcast entries across all userIds
1009            int num = 0;
1010            for (int i = 0; i< mUidMap.size(); i++) {
1011                num += mUidMap.valueAt(i).size();
1012            }
1013            return num;
1014        }
1015
1016        public void clear() {
1017            mUidMap.clear();
1018        }
1019
1020        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1021            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1022            if (map == null) {
1023                map = new ArrayMap<String, ArrayList<String>>();
1024                mUidMap.put(userId, map);
1025            }
1026            return map;
1027        }
1028    }
1029    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1030
1031    // Service Connection to remote media container service to copy
1032    // package uri's from external media onto secure containers
1033    // or internal storage.
1034    private IMediaContainerService mContainerService = null;
1035
1036    static final int SEND_PENDING_BROADCAST = 1;
1037    static final int MCS_BOUND = 3;
1038    static final int END_COPY = 4;
1039    static final int INIT_COPY = 5;
1040    static final int MCS_UNBIND = 6;
1041    static final int START_CLEANING_PACKAGE = 7;
1042    static final int FIND_INSTALL_LOC = 8;
1043    static final int POST_INSTALL = 9;
1044    static final int MCS_RECONNECT = 10;
1045    static final int MCS_GIVE_UP = 11;
1046    static final int UPDATED_MEDIA_STATUS = 12;
1047    static final int WRITE_SETTINGS = 13;
1048    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1049    static final int PACKAGE_VERIFIED = 15;
1050    static final int CHECK_PENDING_VERIFICATION = 16;
1051    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1052    static final int INTENT_FILTER_VERIFIED = 18;
1053    static final int WRITE_PACKAGE_LIST = 19;
1054
1055    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1056
1057    // Delay time in millisecs
1058    static final int BROADCAST_DELAY = 10 * 1000;
1059
1060    static UserManagerService sUserManager;
1061
1062    // Stores a list of users whose package restrictions file needs to be updated
1063    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1064
1065    final private DefaultContainerConnection mDefContainerConn =
1066            new DefaultContainerConnection();
1067    class DefaultContainerConnection implements ServiceConnection {
1068        public void onServiceConnected(ComponentName name, IBinder service) {
1069            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1070            IMediaContainerService imcs =
1071                IMediaContainerService.Stub.asInterface(service);
1072            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1073        }
1074
1075        public void onServiceDisconnected(ComponentName name) {
1076            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1077        }
1078    }
1079
1080    // Recordkeeping of restore-after-install operations that are currently in flight
1081    // between the Package Manager and the Backup Manager
1082    static class PostInstallData {
1083        public InstallArgs args;
1084        public PackageInstalledInfo res;
1085
1086        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1087            args = _a;
1088            res = _r;
1089        }
1090    }
1091
1092    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1093    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1094
1095    // XML tags for backup/restore of various bits of state
1096    private static final String TAG_PREFERRED_BACKUP = "pa";
1097    private static final String TAG_DEFAULT_APPS = "da";
1098    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1099
1100    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1101    private static final String TAG_ALL_GRANTS = "rt-grants";
1102    private static final String TAG_GRANT = "grant";
1103    private static final String ATTR_PACKAGE_NAME = "pkg";
1104
1105    private static final String TAG_PERMISSION = "perm";
1106    private static final String ATTR_PERMISSION_NAME = "name";
1107    private static final String ATTR_IS_GRANTED = "g";
1108    private static final String ATTR_USER_SET = "set";
1109    private static final String ATTR_USER_FIXED = "fixed";
1110    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1111
1112    // System/policy permission grants are not backed up
1113    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1114            FLAG_PERMISSION_POLICY_FIXED
1115            | FLAG_PERMISSION_SYSTEM_FIXED
1116            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1117
1118    // And we back up these user-adjusted states
1119    private static final int USER_RUNTIME_GRANT_MASK =
1120            FLAG_PERMISSION_USER_SET
1121            | FLAG_PERMISSION_USER_FIXED
1122            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1123
1124    final @Nullable String mRequiredVerifierPackage;
1125    final @NonNull String mRequiredInstallerPackage;
1126    final @NonNull String mRequiredUninstallerPackage;
1127    final @Nullable String mSetupWizardPackage;
1128    final @NonNull String mServicesSystemSharedLibraryPackageName;
1129    final @NonNull String mSharedSystemSharedLibraryPackageName;
1130
1131    private final PackageUsage mPackageUsage = new PackageUsage();
1132    private final CompilerStats mCompilerStats = new CompilerStats();
1133
1134    class PackageHandler extends Handler {
1135        private boolean mBound = false;
1136        final ArrayList<HandlerParams> mPendingInstalls =
1137            new ArrayList<HandlerParams>();
1138
1139        private boolean connectToService() {
1140            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1141                    " DefaultContainerService");
1142            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1143            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1144            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1145                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1146                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1147                mBound = true;
1148                return true;
1149            }
1150            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1151            return false;
1152        }
1153
1154        private void disconnectService() {
1155            mContainerService = null;
1156            mBound = false;
1157            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1158            mContext.unbindService(mDefContainerConn);
1159            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1160        }
1161
1162        PackageHandler(Looper looper) {
1163            super(looper);
1164        }
1165
1166        public void handleMessage(Message msg) {
1167            try {
1168                doHandleMessage(msg);
1169            } finally {
1170                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1171            }
1172        }
1173
1174        void doHandleMessage(Message msg) {
1175            switch (msg.what) {
1176                case INIT_COPY: {
1177                    HandlerParams params = (HandlerParams) msg.obj;
1178                    int idx = mPendingInstalls.size();
1179                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1180                    // If a bind was already initiated we dont really
1181                    // need to do anything. The pending install
1182                    // will be processed later on.
1183                    if (!mBound) {
1184                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1185                                System.identityHashCode(mHandler));
1186                        // If this is the only one pending we might
1187                        // have to bind to the service again.
1188                        if (!connectToService()) {
1189                            Slog.e(TAG, "Failed to bind to media container service");
1190                            params.serviceError();
1191                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1192                                    System.identityHashCode(mHandler));
1193                            if (params.traceMethod != null) {
1194                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1195                                        params.traceCookie);
1196                            }
1197                            return;
1198                        } else {
1199                            // Once we bind to the service, the first
1200                            // pending request will be processed.
1201                            mPendingInstalls.add(idx, params);
1202                        }
1203                    } else {
1204                        mPendingInstalls.add(idx, params);
1205                        // Already bound to the service. Just make
1206                        // sure we trigger off processing the first request.
1207                        if (idx == 0) {
1208                            mHandler.sendEmptyMessage(MCS_BOUND);
1209                        }
1210                    }
1211                    break;
1212                }
1213                case MCS_BOUND: {
1214                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1215                    if (msg.obj != null) {
1216                        mContainerService = (IMediaContainerService) msg.obj;
1217                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1218                                System.identityHashCode(mHandler));
1219                    }
1220                    if (mContainerService == null) {
1221                        if (!mBound) {
1222                            // Something seriously wrong since we are not bound and we are not
1223                            // waiting for connection. Bail out.
1224                            Slog.e(TAG, "Cannot bind to media container service");
1225                            for (HandlerParams params : mPendingInstalls) {
1226                                // Indicate service bind error
1227                                params.serviceError();
1228                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1229                                        System.identityHashCode(params));
1230                                if (params.traceMethod != null) {
1231                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1232                                            params.traceMethod, params.traceCookie);
1233                                }
1234                                return;
1235                            }
1236                            mPendingInstalls.clear();
1237                        } else {
1238                            Slog.w(TAG, "Waiting to connect to media container service");
1239                        }
1240                    } else if (mPendingInstalls.size() > 0) {
1241                        HandlerParams params = mPendingInstalls.get(0);
1242                        if (params != null) {
1243                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1244                                    System.identityHashCode(params));
1245                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1246                            if (params.startCopy()) {
1247                                // We are done...  look for more work or to
1248                                // go idle.
1249                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1250                                        "Checking for more work or unbind...");
1251                                // Delete pending install
1252                                if (mPendingInstalls.size() > 0) {
1253                                    mPendingInstalls.remove(0);
1254                                }
1255                                if (mPendingInstalls.size() == 0) {
1256                                    if (mBound) {
1257                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1258                                                "Posting delayed MCS_UNBIND");
1259                                        removeMessages(MCS_UNBIND);
1260                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1261                                        // Unbind after a little delay, to avoid
1262                                        // continual thrashing.
1263                                        sendMessageDelayed(ubmsg, 10000);
1264                                    }
1265                                } else {
1266                                    // There are more pending requests in queue.
1267                                    // Just post MCS_BOUND message to trigger processing
1268                                    // of next pending install.
1269                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1270                                            "Posting MCS_BOUND for next work");
1271                                    mHandler.sendEmptyMessage(MCS_BOUND);
1272                                }
1273                            }
1274                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1275                        }
1276                    } else {
1277                        // Should never happen ideally.
1278                        Slog.w(TAG, "Empty queue");
1279                    }
1280                    break;
1281                }
1282                case MCS_RECONNECT: {
1283                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1284                    if (mPendingInstalls.size() > 0) {
1285                        if (mBound) {
1286                            disconnectService();
1287                        }
1288                        if (!connectToService()) {
1289                            Slog.e(TAG, "Failed to bind to media container service");
1290                            for (HandlerParams params : mPendingInstalls) {
1291                                // Indicate service bind error
1292                                params.serviceError();
1293                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1294                                        System.identityHashCode(params));
1295                            }
1296                            mPendingInstalls.clear();
1297                        }
1298                    }
1299                    break;
1300                }
1301                case MCS_UNBIND: {
1302                    // If there is no actual work left, then time to unbind.
1303                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1304
1305                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1306                        if (mBound) {
1307                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1308
1309                            disconnectService();
1310                        }
1311                    } else if (mPendingInstalls.size() > 0) {
1312                        // There are more pending requests in queue.
1313                        // Just post MCS_BOUND message to trigger processing
1314                        // of next pending install.
1315                        mHandler.sendEmptyMessage(MCS_BOUND);
1316                    }
1317
1318                    break;
1319                }
1320                case MCS_GIVE_UP: {
1321                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1322                    HandlerParams params = mPendingInstalls.remove(0);
1323                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1324                            System.identityHashCode(params));
1325                    break;
1326                }
1327                case SEND_PENDING_BROADCAST: {
1328                    String packages[];
1329                    ArrayList<String> components[];
1330                    int size = 0;
1331                    int uids[];
1332                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1333                    synchronized (mPackages) {
1334                        if (mPendingBroadcasts == null) {
1335                            return;
1336                        }
1337                        size = mPendingBroadcasts.size();
1338                        if (size <= 0) {
1339                            // Nothing to be done. Just return
1340                            return;
1341                        }
1342                        packages = new String[size];
1343                        components = new ArrayList[size];
1344                        uids = new int[size];
1345                        int i = 0;  // filling out the above arrays
1346
1347                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1348                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1349                            Iterator<Map.Entry<String, ArrayList<String>>> it
1350                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1351                                            .entrySet().iterator();
1352                            while (it.hasNext() && i < size) {
1353                                Map.Entry<String, ArrayList<String>> ent = it.next();
1354                                packages[i] = ent.getKey();
1355                                components[i] = ent.getValue();
1356                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1357                                uids[i] = (ps != null)
1358                                        ? UserHandle.getUid(packageUserId, ps.appId)
1359                                        : -1;
1360                                i++;
1361                            }
1362                        }
1363                        size = i;
1364                        mPendingBroadcasts.clear();
1365                    }
1366                    // Send broadcasts
1367                    for (int i = 0; i < size; i++) {
1368                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1369                    }
1370                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1371                    break;
1372                }
1373                case START_CLEANING_PACKAGE: {
1374                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1375                    final String packageName = (String)msg.obj;
1376                    final int userId = msg.arg1;
1377                    final boolean andCode = msg.arg2 != 0;
1378                    synchronized (mPackages) {
1379                        if (userId == UserHandle.USER_ALL) {
1380                            int[] users = sUserManager.getUserIds();
1381                            for (int user : users) {
1382                                mSettings.addPackageToCleanLPw(
1383                                        new PackageCleanItem(user, packageName, andCode));
1384                            }
1385                        } else {
1386                            mSettings.addPackageToCleanLPw(
1387                                    new PackageCleanItem(userId, packageName, andCode));
1388                        }
1389                    }
1390                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1391                    startCleaningPackages();
1392                } break;
1393                case POST_INSTALL: {
1394                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1395
1396                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1397                    final boolean didRestore = (msg.arg2 != 0);
1398                    mRunningInstalls.delete(msg.arg1);
1399
1400                    if (data != null) {
1401                        InstallArgs args = data.args;
1402                        PackageInstalledInfo parentRes = data.res;
1403
1404                        final boolean grantPermissions = (args.installFlags
1405                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1406                        final boolean killApp = (args.installFlags
1407                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1408                        final String[] grantedPermissions = args.installGrantPermissions;
1409
1410                        // Handle the parent package
1411                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1412                                grantedPermissions, didRestore, args.installerPackageName,
1413                                args.observer);
1414
1415                        // Handle the child packages
1416                        final int childCount = (parentRes.addedChildPackages != null)
1417                                ? parentRes.addedChildPackages.size() : 0;
1418                        for (int i = 0; i < childCount; i++) {
1419                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1420                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1421                                    grantedPermissions, false, args.installerPackageName,
1422                                    args.observer);
1423                        }
1424
1425                        // Log tracing if needed
1426                        if (args.traceMethod != null) {
1427                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1428                                    args.traceCookie);
1429                        }
1430                    } else {
1431                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1432                    }
1433
1434                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1435                } break;
1436                case UPDATED_MEDIA_STATUS: {
1437                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1438                    boolean reportStatus = msg.arg1 == 1;
1439                    boolean doGc = msg.arg2 == 1;
1440                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1441                    if (doGc) {
1442                        // Force a gc to clear up stale containers.
1443                        Runtime.getRuntime().gc();
1444                    }
1445                    if (msg.obj != null) {
1446                        @SuppressWarnings("unchecked")
1447                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1448                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1449                        // Unload containers
1450                        unloadAllContainers(args);
1451                    }
1452                    if (reportStatus) {
1453                        try {
1454                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1455                            PackageHelper.getMountService().finishMediaUpdate();
1456                        } catch (RemoteException e) {
1457                            Log.e(TAG, "MountService not running?");
1458                        }
1459                    }
1460                } break;
1461                case WRITE_SETTINGS: {
1462                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1463                    synchronized (mPackages) {
1464                        removeMessages(WRITE_SETTINGS);
1465                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1466                        mSettings.writeLPr();
1467                        mDirtyUsers.clear();
1468                    }
1469                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1470                } break;
1471                case WRITE_PACKAGE_RESTRICTIONS: {
1472                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1473                    synchronized (mPackages) {
1474                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1475                        for (int userId : mDirtyUsers) {
1476                            mSettings.writePackageRestrictionsLPr(userId);
1477                        }
1478                        mDirtyUsers.clear();
1479                    }
1480                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1481                } break;
1482                case WRITE_PACKAGE_LIST: {
1483                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1484                    synchronized (mPackages) {
1485                        removeMessages(WRITE_PACKAGE_LIST);
1486                        mSettings.writePackageListLPr(msg.arg1);
1487                    }
1488                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1489                } break;
1490                case CHECK_PENDING_VERIFICATION: {
1491                    final int verificationId = msg.arg1;
1492                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1493
1494                    if ((state != null) && !state.timeoutExtended()) {
1495                        final InstallArgs args = state.getInstallArgs();
1496                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1497
1498                        Slog.i(TAG, "Verification timed out for " + originUri);
1499                        mPendingVerification.remove(verificationId);
1500
1501                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1502
1503                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1504                            Slog.i(TAG, "Continuing with installation of " + originUri);
1505                            state.setVerifierResponse(Binder.getCallingUid(),
1506                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1507                            broadcastPackageVerified(verificationId, originUri,
1508                                    PackageManager.VERIFICATION_ALLOW,
1509                                    state.getInstallArgs().getUser());
1510                            try {
1511                                ret = args.copyApk(mContainerService, true);
1512                            } catch (RemoteException e) {
1513                                Slog.e(TAG, "Could not contact the ContainerService");
1514                            }
1515                        } else {
1516                            broadcastPackageVerified(verificationId, originUri,
1517                                    PackageManager.VERIFICATION_REJECT,
1518                                    state.getInstallArgs().getUser());
1519                        }
1520
1521                        Trace.asyncTraceEnd(
1522                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1523
1524                        processPendingInstall(args, ret);
1525                        mHandler.sendEmptyMessage(MCS_UNBIND);
1526                    }
1527                    break;
1528                }
1529                case PACKAGE_VERIFIED: {
1530                    final int verificationId = msg.arg1;
1531
1532                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1533                    if (state == null) {
1534                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1535                        break;
1536                    }
1537
1538                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1539
1540                    state.setVerifierResponse(response.callerUid, response.code);
1541
1542                    if (state.isVerificationComplete()) {
1543                        mPendingVerification.remove(verificationId);
1544
1545                        final InstallArgs args = state.getInstallArgs();
1546                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1547
1548                        int ret;
1549                        if (state.isInstallAllowed()) {
1550                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1551                            broadcastPackageVerified(verificationId, originUri,
1552                                    response.code, state.getInstallArgs().getUser());
1553                            try {
1554                                ret = args.copyApk(mContainerService, true);
1555                            } catch (RemoteException e) {
1556                                Slog.e(TAG, "Could not contact the ContainerService");
1557                            }
1558                        } else {
1559                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1560                        }
1561
1562                        Trace.asyncTraceEnd(
1563                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1564
1565                        processPendingInstall(args, ret);
1566                        mHandler.sendEmptyMessage(MCS_UNBIND);
1567                    }
1568
1569                    break;
1570                }
1571                case START_INTENT_FILTER_VERIFICATIONS: {
1572                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1573                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1574                            params.replacing, params.pkg);
1575                    break;
1576                }
1577                case INTENT_FILTER_VERIFIED: {
1578                    final int verificationId = msg.arg1;
1579
1580                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1581                            verificationId);
1582                    if (state == null) {
1583                        Slog.w(TAG, "Invalid IntentFilter verification token "
1584                                + verificationId + " received");
1585                        break;
1586                    }
1587
1588                    final int userId = state.getUserId();
1589
1590                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1591                            "Processing IntentFilter verification with token:"
1592                            + verificationId + " and userId:" + userId);
1593
1594                    final IntentFilterVerificationResponse response =
1595                            (IntentFilterVerificationResponse) msg.obj;
1596
1597                    state.setVerifierResponse(response.callerUid, response.code);
1598
1599                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1600                            "IntentFilter verification with token:" + verificationId
1601                            + " and userId:" + userId
1602                            + " is settings verifier response with response code:"
1603                            + response.code);
1604
1605                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1606                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1607                                + response.getFailedDomainsString());
1608                    }
1609
1610                    if (state.isVerificationComplete()) {
1611                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1612                    } else {
1613                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1614                                "IntentFilter verification with token:" + verificationId
1615                                + " was not said to be complete");
1616                    }
1617
1618                    break;
1619                }
1620            }
1621        }
1622    }
1623
1624    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1625            boolean killApp, String[] grantedPermissions,
1626            boolean launchedForRestore, String installerPackage,
1627            IPackageInstallObserver2 installObserver) {
1628        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1629            // Send the removed broadcasts
1630            if (res.removedInfo != null) {
1631                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1632            }
1633
1634            // Now that we successfully installed the package, grant runtime
1635            // permissions if requested before broadcasting the install.
1636            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1637                    >= Build.VERSION_CODES.M) {
1638                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1639            }
1640
1641            final boolean update = res.removedInfo != null
1642                    && res.removedInfo.removedPackage != null;
1643
1644            // If this is the first time we have child packages for a disabled privileged
1645            // app that had no children, we grant requested runtime permissions to the new
1646            // children if the parent on the system image had them already granted.
1647            if (res.pkg.parentPackage != null) {
1648                synchronized (mPackages) {
1649                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1650                }
1651            }
1652
1653            synchronized (mPackages) {
1654                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1655            }
1656
1657            final String packageName = res.pkg.applicationInfo.packageName;
1658            Bundle extras = new Bundle(1);
1659            extras.putInt(Intent.EXTRA_UID, res.uid);
1660
1661            // Determine the set of users who are adding this package for
1662            // the first time vs. those who are seeing an update.
1663            int[] firstUsers = EMPTY_INT_ARRAY;
1664            int[] updateUsers = EMPTY_INT_ARRAY;
1665            if (res.origUsers == null || res.origUsers.length == 0) {
1666                firstUsers = res.newUsers;
1667            } else {
1668                for (int newUser : res.newUsers) {
1669                    boolean isNew = true;
1670                    for (int origUser : res.origUsers) {
1671                        if (origUser == newUser) {
1672                            isNew = false;
1673                            break;
1674                        }
1675                    }
1676                    if (isNew) {
1677                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1678                    } else {
1679                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1680                    }
1681                }
1682            }
1683
1684            // Send installed broadcasts if the install/update is not ephemeral
1685            if (!isEphemeral(res.pkg)) {
1686                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1687
1688                // Send added for users that see the package for the first time
1689                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1690                        extras, 0 /*flags*/, null /*targetPackage*/,
1691                        null /*finishedReceiver*/, firstUsers);
1692
1693                // Send added for users that don't see the package for the first time
1694                if (update) {
1695                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1696                }
1697                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1698                        extras, 0 /*flags*/, null /*targetPackage*/,
1699                        null /*finishedReceiver*/, updateUsers);
1700
1701                // Send replaced for users that don't see the package for the first time
1702                if (update) {
1703                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1704                            packageName, extras, 0 /*flags*/,
1705                            null /*targetPackage*/, null /*finishedReceiver*/,
1706                            updateUsers);
1707                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1708                            null /*package*/, null /*extras*/, 0 /*flags*/,
1709                            packageName /*targetPackage*/,
1710                            null /*finishedReceiver*/, updateUsers);
1711                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1712                    // First-install and we did a restore, so we're responsible for the
1713                    // first-launch broadcast.
1714                    if (DEBUG_BACKUP) {
1715                        Slog.i(TAG, "Post-restore of " + packageName
1716                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1717                    }
1718                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1719                }
1720
1721                // Send broadcast package appeared if forward locked/external for all users
1722                // treat asec-hosted packages like removable media on upgrade
1723                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1724                    if (DEBUG_INSTALL) {
1725                        Slog.i(TAG, "upgrading pkg " + res.pkg
1726                                + " is ASEC-hosted -> AVAILABLE");
1727                    }
1728                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1729                    ArrayList<String> pkgList = new ArrayList<>(1);
1730                    pkgList.add(packageName);
1731                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1732                }
1733            }
1734
1735            // Work that needs to happen on first install within each user
1736            if (firstUsers != null && firstUsers.length > 0) {
1737                synchronized (mPackages) {
1738                    for (int userId : firstUsers) {
1739                        // If this app is a browser and it's newly-installed for some
1740                        // users, clear any default-browser state in those users. The
1741                        // app's nature doesn't depend on the user, so we can just check
1742                        // its browser nature in any user and generalize.
1743                        if (packageIsBrowser(packageName, userId)) {
1744                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1745                        }
1746
1747                        // We may also need to apply pending (restored) runtime
1748                        // permission grants within these users.
1749                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1750                    }
1751                }
1752            }
1753
1754            // Log current value of "unknown sources" setting
1755            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1756                    getUnknownSourcesSettings());
1757
1758            // Force a gc to clear up things
1759            Runtime.getRuntime().gc();
1760
1761            // Remove the replaced package's older resources safely now
1762            // We delete after a gc for applications  on sdcard.
1763            if (res.removedInfo != null && res.removedInfo.args != null) {
1764                synchronized (mInstallLock) {
1765                    res.removedInfo.args.doPostDeleteLI(true);
1766                }
1767            }
1768        }
1769
1770        // If someone is watching installs - notify them
1771        if (installObserver != null) {
1772            try {
1773                Bundle extras = extrasForInstallResult(res);
1774                installObserver.onPackageInstalled(res.name, res.returnCode,
1775                        res.returnMsg, extras);
1776            } catch (RemoteException e) {
1777                Slog.i(TAG, "Observer no longer exists.");
1778            }
1779        }
1780    }
1781
1782    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1783            PackageParser.Package pkg) {
1784        if (pkg.parentPackage == null) {
1785            return;
1786        }
1787        if (pkg.requestedPermissions == null) {
1788            return;
1789        }
1790        final PackageSetting disabledSysParentPs = mSettings
1791                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1792        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1793                || !disabledSysParentPs.isPrivileged()
1794                || (disabledSysParentPs.childPackageNames != null
1795                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1796            return;
1797        }
1798        final int[] allUserIds = sUserManager.getUserIds();
1799        final int permCount = pkg.requestedPermissions.size();
1800        for (int i = 0; i < permCount; i++) {
1801            String permission = pkg.requestedPermissions.get(i);
1802            BasePermission bp = mSettings.mPermissions.get(permission);
1803            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1804                continue;
1805            }
1806            for (int userId : allUserIds) {
1807                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1808                        permission, userId)) {
1809                    grantRuntimePermission(pkg.packageName, permission, userId);
1810                }
1811            }
1812        }
1813    }
1814
1815    private StorageEventListener mStorageListener = new StorageEventListener() {
1816        @Override
1817        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1818            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1819                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1820                    final String volumeUuid = vol.getFsUuid();
1821
1822                    // Clean up any users or apps that were removed or recreated
1823                    // while this volume was missing
1824                    reconcileUsers(volumeUuid);
1825                    reconcileApps(volumeUuid);
1826
1827                    // Clean up any install sessions that expired or were
1828                    // cancelled while this volume was missing
1829                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1830
1831                    loadPrivatePackages(vol);
1832
1833                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1834                    unloadPrivatePackages(vol);
1835                }
1836            }
1837
1838            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1839                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1840                    updateExternalMediaStatus(true, false);
1841                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1842                    updateExternalMediaStatus(false, false);
1843                }
1844            }
1845        }
1846
1847        @Override
1848        public void onVolumeForgotten(String fsUuid) {
1849            if (TextUtils.isEmpty(fsUuid)) {
1850                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1851                return;
1852            }
1853
1854            // Remove any apps installed on the forgotten volume
1855            synchronized (mPackages) {
1856                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1857                for (PackageSetting ps : packages) {
1858                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1859                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1860                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1861                }
1862
1863                mSettings.onVolumeForgotten(fsUuid);
1864                mSettings.writeLPr();
1865            }
1866        }
1867    };
1868
1869    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1870            String[] grantedPermissions) {
1871        for (int userId : userIds) {
1872            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1873        }
1874
1875        // We could have touched GID membership, so flush out packages.list
1876        synchronized (mPackages) {
1877            mSettings.writePackageListLPr();
1878        }
1879    }
1880
1881    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1882            String[] grantedPermissions) {
1883        SettingBase sb = (SettingBase) pkg.mExtras;
1884        if (sb == null) {
1885            return;
1886        }
1887
1888        PermissionsState permissionsState = sb.getPermissionsState();
1889
1890        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1891                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1892
1893        for (String permission : pkg.requestedPermissions) {
1894            final BasePermission bp;
1895            synchronized (mPackages) {
1896                bp = mSettings.mPermissions.get(permission);
1897            }
1898            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1899                    && (grantedPermissions == null
1900                           || ArrayUtils.contains(grantedPermissions, permission))) {
1901                final int flags = permissionsState.getPermissionFlags(permission, userId);
1902                // Installer cannot change immutable permissions.
1903                if ((flags & immutableFlags) == 0) {
1904                    grantRuntimePermission(pkg.packageName, permission, userId);
1905                }
1906            }
1907        }
1908    }
1909
1910    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1911        Bundle extras = null;
1912        switch (res.returnCode) {
1913            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1914                extras = new Bundle();
1915                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1916                        res.origPermission);
1917                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1918                        res.origPackage);
1919                break;
1920            }
1921            case PackageManager.INSTALL_SUCCEEDED: {
1922                extras = new Bundle();
1923                extras.putBoolean(Intent.EXTRA_REPLACING,
1924                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1925                break;
1926            }
1927        }
1928        return extras;
1929    }
1930
1931    void scheduleWriteSettingsLocked() {
1932        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1933            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1934        }
1935    }
1936
1937    void scheduleWritePackageListLocked(int userId) {
1938        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1939            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1940            msg.arg1 = userId;
1941            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1942        }
1943    }
1944
1945    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1946        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1947        scheduleWritePackageRestrictionsLocked(userId);
1948    }
1949
1950    void scheduleWritePackageRestrictionsLocked(int userId) {
1951        final int[] userIds = (userId == UserHandle.USER_ALL)
1952                ? sUserManager.getUserIds() : new int[]{userId};
1953        for (int nextUserId : userIds) {
1954            if (!sUserManager.exists(nextUserId)) return;
1955            mDirtyUsers.add(nextUserId);
1956            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1957                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1958            }
1959        }
1960    }
1961
1962    public static PackageManagerService main(Context context, Installer installer,
1963            boolean factoryTest, boolean onlyCore) {
1964        // Self-check for initial settings.
1965        PackageManagerServiceCompilerMapping.checkProperties();
1966
1967        PackageManagerService m = new PackageManagerService(context, installer,
1968                factoryTest, onlyCore);
1969        m.enableSystemUserPackages();
1970        ServiceManager.addService("package", m);
1971        return m;
1972    }
1973
1974    private void enableSystemUserPackages() {
1975        if (!UserManager.isSplitSystemUser()) {
1976            return;
1977        }
1978        // For system user, enable apps based on the following conditions:
1979        // - app is whitelisted or belong to one of these groups:
1980        //   -- system app which has no launcher icons
1981        //   -- system app which has INTERACT_ACROSS_USERS permission
1982        //   -- system IME app
1983        // - app is not in the blacklist
1984        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1985        Set<String> enableApps = new ArraySet<>();
1986        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1987                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1988                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1989        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1990        enableApps.addAll(wlApps);
1991        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1992                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1993        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1994        enableApps.removeAll(blApps);
1995        Log.i(TAG, "Applications installed for system user: " + enableApps);
1996        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1997                UserHandle.SYSTEM);
1998        final int allAppsSize = allAps.size();
1999        synchronized (mPackages) {
2000            for (int i = 0; i < allAppsSize; i++) {
2001                String pName = allAps.get(i);
2002                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2003                // Should not happen, but we shouldn't be failing if it does
2004                if (pkgSetting == null) {
2005                    continue;
2006                }
2007                boolean install = enableApps.contains(pName);
2008                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2009                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2010                            + " for system user");
2011                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2012                }
2013            }
2014        }
2015    }
2016
2017    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2018        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2019                Context.DISPLAY_SERVICE);
2020        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2021    }
2022
2023    /**
2024     * Requests that files preopted on a secondary system partition be copied to the data partition
2025     * if possible.  Note that the actual copying of the files is accomplished by init for security
2026     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2027     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2028     */
2029    private static void requestCopyPreoptedFiles() {
2030        final int WAIT_TIME_MS = 100;
2031        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2032        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2033            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2034            // We will wait for up to 100 seconds.
2035            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2036            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2037                try {
2038                    Thread.sleep(WAIT_TIME_MS);
2039                } catch (InterruptedException e) {
2040                    // Do nothing
2041                }
2042                if (SystemClock.uptimeMillis() > timeEnd) {
2043                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2044                    Slog.wtf(TAG, "cppreopt did not finish!");
2045                    break;
2046                }
2047            }
2048        }
2049    }
2050
2051    public PackageManagerService(Context context, Installer installer,
2052            boolean factoryTest, boolean onlyCore) {
2053        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2054                SystemClock.uptimeMillis());
2055
2056        if (mSdkVersion <= 0) {
2057            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2058        }
2059
2060        mContext = context;
2061        mFactoryTest = factoryTest;
2062        mOnlyCore = onlyCore;
2063        mMetrics = new DisplayMetrics();
2064        mSettings = new Settings(mPackages);
2065        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2066                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2067        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2068                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2069        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2070                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2071        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2072                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2073        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2074                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2075        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2076                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2077
2078        String separateProcesses = SystemProperties.get("debug.separate_processes");
2079        if (separateProcesses != null && separateProcesses.length() > 0) {
2080            if ("*".equals(separateProcesses)) {
2081                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2082                mSeparateProcesses = null;
2083                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2084            } else {
2085                mDefParseFlags = 0;
2086                mSeparateProcesses = separateProcesses.split(",");
2087                Slog.w(TAG, "Running with debug.separate_processes: "
2088                        + separateProcesses);
2089            }
2090        } else {
2091            mDefParseFlags = 0;
2092            mSeparateProcesses = null;
2093        }
2094
2095        mInstaller = installer;
2096        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2097                "*dexopt*");
2098        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2099
2100        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2101                FgThread.get().getLooper());
2102
2103        getDefaultDisplayMetrics(context, mMetrics);
2104
2105        SystemConfig systemConfig = SystemConfig.getInstance();
2106        mGlobalGids = systemConfig.getGlobalGids();
2107        mSystemPermissions = systemConfig.getSystemPermissions();
2108        mAvailableFeatures = systemConfig.getAvailableFeatures();
2109
2110        mProtectedPackages = new ProtectedPackages(mContext);
2111
2112        synchronized (mInstallLock) {
2113        // writer
2114        synchronized (mPackages) {
2115            mHandlerThread = new ServiceThread(TAG,
2116                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2117            mHandlerThread.start();
2118            mHandler = new PackageHandler(mHandlerThread.getLooper());
2119            mProcessLoggingHandler = new ProcessLoggingHandler();
2120            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2121
2122            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2123
2124            File dataDir = Environment.getDataDirectory();
2125            mAppInstallDir = new File(dataDir, "app");
2126            mAppLib32InstallDir = new File(dataDir, "app-lib");
2127            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2128            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2129            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2130
2131            sUserManager = new UserManagerService(context, this, mPackages);
2132
2133            // Propagate permission configuration in to package manager.
2134            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2135                    = systemConfig.getPermissions();
2136            for (int i=0; i<permConfig.size(); i++) {
2137                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2138                BasePermission bp = mSettings.mPermissions.get(perm.name);
2139                if (bp == null) {
2140                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2141                    mSettings.mPermissions.put(perm.name, bp);
2142                }
2143                if (perm.gids != null) {
2144                    bp.setGids(perm.gids, perm.perUser);
2145                }
2146            }
2147
2148            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2149            for (int i=0; i<libConfig.size(); i++) {
2150                mSharedLibraries.put(libConfig.keyAt(i),
2151                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2152            }
2153
2154            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2155
2156            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2157
2158            if (mFirstBoot) {
2159                requestCopyPreoptedFiles();
2160            }
2161
2162            String customResolverActivity = Resources.getSystem().getString(
2163                    R.string.config_customResolverActivity);
2164            if (TextUtils.isEmpty(customResolverActivity)) {
2165                customResolverActivity = null;
2166            } else {
2167                mCustomResolverComponentName = ComponentName.unflattenFromString(
2168                        customResolverActivity);
2169            }
2170
2171            long startTime = SystemClock.uptimeMillis();
2172
2173            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2174                    startTime);
2175
2176            // Set flag to monitor and not change apk file paths when
2177            // scanning install directories.
2178            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2179
2180            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2181            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2182
2183            if (bootClassPath == null) {
2184                Slog.w(TAG, "No BOOTCLASSPATH found!");
2185            }
2186
2187            if (systemServerClassPath == null) {
2188                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2189            }
2190
2191            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2192            final String[] dexCodeInstructionSets =
2193                    getDexCodeInstructionSets(
2194                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2195
2196            /**
2197             * Ensure all external libraries have had dexopt run on them.
2198             */
2199            if (mSharedLibraries.size() > 0) {
2200                // NOTE: For now, we're compiling these system "shared libraries"
2201                // (and framework jars) into all available architectures. It's possible
2202                // to compile them only when we come across an app that uses them (there's
2203                // already logic for that in scanPackageLI) but that adds some complexity.
2204                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2205                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2206                        final String lib = libEntry.path;
2207                        if (lib == null) {
2208                            continue;
2209                        }
2210
2211                        try {
2212                            // Shared libraries do not have profiles so we perform a full
2213                            // AOT compilation (if needed).
2214                            int dexoptNeeded = DexFile.getDexOptNeeded(
2215                                    lib, dexCodeInstructionSet,
2216                                    getCompilerFilterForReason(REASON_SHARED_APK),
2217                                    false /* newProfile */);
2218                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2219                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2220                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2221                                        getCompilerFilterForReason(REASON_SHARED_APK),
2222                                        StorageManager.UUID_PRIVATE_INTERNAL,
2223                                        SKIP_SHARED_LIBRARY_CHECK);
2224                            }
2225                        } catch (FileNotFoundException e) {
2226                            Slog.w(TAG, "Library not found: " + lib);
2227                        } catch (IOException | InstallerException e) {
2228                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2229                                    + e.getMessage());
2230                        }
2231                    }
2232                }
2233            }
2234
2235            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2236
2237            final VersionInfo ver = mSettings.getInternalVersion();
2238            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2239
2240            // when upgrading from pre-M, promote system app permissions from install to runtime
2241            mPromoteSystemApps =
2242                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2243
2244            // When upgrading from pre-N, we need to handle package extraction like first boot,
2245            // as there is no profiling data available.
2246            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2247
2248            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2249
2250            // save off the names of pre-existing system packages prior to scanning; we don't
2251            // want to automatically grant runtime permissions for new system apps
2252            if (mPromoteSystemApps) {
2253                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2254                while (pkgSettingIter.hasNext()) {
2255                    PackageSetting ps = pkgSettingIter.next();
2256                    if (isSystemApp(ps)) {
2257                        mExistingSystemPackages.add(ps.name);
2258                    }
2259                }
2260            }
2261
2262            // Collect vendor overlay packages.
2263            // (Do this before scanning any apps.)
2264            // For security and version matching reason, only consider
2265            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2266            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2267            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2268                    | PackageParser.PARSE_IS_SYSTEM
2269                    | PackageParser.PARSE_IS_SYSTEM_DIR
2270                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2271
2272            // Find base frameworks (resource packages without code).
2273            scanDirTracedLI(frameworkDir, mDefParseFlags
2274                    | PackageParser.PARSE_IS_SYSTEM
2275                    | PackageParser.PARSE_IS_SYSTEM_DIR
2276                    | PackageParser.PARSE_IS_PRIVILEGED,
2277                    scanFlags | SCAN_NO_DEX, 0);
2278
2279            // Collected privileged system packages.
2280            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2281            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2282                    | PackageParser.PARSE_IS_SYSTEM
2283                    | PackageParser.PARSE_IS_SYSTEM_DIR
2284                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2285
2286            // Collect ordinary system packages.
2287            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2288            scanDirTracedLI(systemAppDir, mDefParseFlags
2289                    | PackageParser.PARSE_IS_SYSTEM
2290                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2291
2292            // Collect all vendor packages.
2293            File vendorAppDir = new File("/vendor/app");
2294            try {
2295                vendorAppDir = vendorAppDir.getCanonicalFile();
2296            } catch (IOException e) {
2297                // failed to look up canonical path, continue with original one
2298            }
2299            scanDirTracedLI(vendorAppDir, mDefParseFlags
2300                    | PackageParser.PARSE_IS_SYSTEM
2301                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2302
2303            // Collect all OEM packages.
2304            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2305            scanDirTracedLI(oemAppDir, mDefParseFlags
2306                    | PackageParser.PARSE_IS_SYSTEM
2307                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2308
2309            // Prune any system packages that no longer exist.
2310            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2311            if (!mOnlyCore) {
2312                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2313                while (psit.hasNext()) {
2314                    PackageSetting ps = psit.next();
2315
2316                    /*
2317                     * If this is not a system app, it can't be a
2318                     * disable system app.
2319                     */
2320                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2321                        continue;
2322                    }
2323
2324                    /*
2325                     * If the package is scanned, it's not erased.
2326                     */
2327                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2328                    if (scannedPkg != null) {
2329                        /*
2330                         * If the system app is both scanned and in the
2331                         * disabled packages list, then it must have been
2332                         * added via OTA. Remove it from the currently
2333                         * scanned package so the previously user-installed
2334                         * application can be scanned.
2335                         */
2336                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2337                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2338                                    + ps.name + "; removing system app.  Last known codePath="
2339                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2340                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2341                                    + scannedPkg.mVersionCode);
2342                            removePackageLI(scannedPkg, true);
2343                            mExpectingBetter.put(ps.name, ps.codePath);
2344                        }
2345
2346                        continue;
2347                    }
2348
2349                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2350                        psit.remove();
2351                        logCriticalInfo(Log.WARN, "System package " + ps.name
2352                                + " no longer exists; it's data will be wiped");
2353                        // Actual deletion of code and data will be handled by later
2354                        // reconciliation step
2355                    } else {
2356                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2357                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2358                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2359                        }
2360                    }
2361                }
2362            }
2363
2364            //look for any incomplete package installations
2365            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2366            for (int i = 0; i < deletePkgsList.size(); i++) {
2367                // Actual deletion of code and data will be handled by later
2368                // reconciliation step
2369                final String packageName = deletePkgsList.get(i).name;
2370                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2371                synchronized (mPackages) {
2372                    mSettings.removePackageLPw(packageName);
2373                }
2374            }
2375
2376            //delete tmp files
2377            deleteTempPackageFiles();
2378
2379            // Remove any shared userIDs that have no associated packages
2380            mSettings.pruneSharedUsersLPw();
2381
2382            if (!mOnlyCore) {
2383                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2384                        SystemClock.uptimeMillis());
2385                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2386
2387                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2388                        | PackageParser.PARSE_FORWARD_LOCK,
2389                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2390
2391                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2392                        | PackageParser.PARSE_IS_EPHEMERAL,
2393                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2394
2395                /**
2396                 * Remove disable package settings for any updated system
2397                 * apps that were removed via an OTA. If they're not a
2398                 * previously-updated app, remove them completely.
2399                 * Otherwise, just revoke their system-level permissions.
2400                 */
2401                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2402                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2403                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2404
2405                    String msg;
2406                    if (deletedPkg == null) {
2407                        msg = "Updated system package " + deletedAppName
2408                                + " no longer exists; it's data will be wiped";
2409                        // Actual deletion of code and data will be handled by later
2410                        // reconciliation step
2411                    } else {
2412                        msg = "Updated system app + " + deletedAppName
2413                                + " no longer present; removing system privileges for "
2414                                + deletedAppName;
2415
2416                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2417
2418                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2419                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2420                    }
2421                    logCriticalInfo(Log.WARN, msg);
2422                }
2423
2424                /**
2425                 * Make sure all system apps that we expected to appear on
2426                 * the userdata partition actually showed up. If they never
2427                 * appeared, crawl back and revive the system version.
2428                 */
2429                for (int i = 0; i < mExpectingBetter.size(); i++) {
2430                    final String packageName = mExpectingBetter.keyAt(i);
2431                    if (!mPackages.containsKey(packageName)) {
2432                        final File scanFile = mExpectingBetter.valueAt(i);
2433
2434                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2435                                + " but never showed up; reverting to system");
2436
2437                        int reparseFlags = mDefParseFlags;
2438                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2439                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2440                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2441                                    | PackageParser.PARSE_IS_PRIVILEGED;
2442                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2443                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2444                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2445                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2446                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2447                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2448                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2449                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2450                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2451                        } else {
2452                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2453                            continue;
2454                        }
2455
2456                        mSettings.enableSystemPackageLPw(packageName);
2457
2458                        try {
2459                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2460                        } catch (PackageManagerException e) {
2461                            Slog.e(TAG, "Failed to parse original system package: "
2462                                    + e.getMessage());
2463                        }
2464                    }
2465                }
2466            }
2467            mExpectingBetter.clear();
2468
2469            // Resolve protected action filters. Only the setup wizard is allowed to
2470            // have a high priority filter for these actions.
2471            mSetupWizardPackage = getSetupWizardPackageName();
2472            if (mProtectedFilters.size() > 0) {
2473                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2474                    Slog.i(TAG, "No setup wizard;"
2475                        + " All protected intents capped to priority 0");
2476                }
2477                for (ActivityIntentInfo filter : mProtectedFilters) {
2478                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2479                        if (DEBUG_FILTERS) {
2480                            Slog.i(TAG, "Found setup wizard;"
2481                                + " allow priority " + filter.getPriority() + ";"
2482                                + " package: " + filter.activity.info.packageName
2483                                + " activity: " + filter.activity.className
2484                                + " priority: " + filter.getPriority());
2485                        }
2486                        // skip setup wizard; allow it to keep the high priority filter
2487                        continue;
2488                    }
2489                    Slog.w(TAG, "Protected action; cap priority to 0;"
2490                            + " package: " + filter.activity.info.packageName
2491                            + " activity: " + filter.activity.className
2492                            + " origPrio: " + filter.getPriority());
2493                    filter.setPriority(0);
2494                }
2495            }
2496            mDeferProtectedFilters = false;
2497            mProtectedFilters.clear();
2498
2499            // Now that we know all of the shared libraries, update all clients to have
2500            // the correct library paths.
2501            updateAllSharedLibrariesLPw();
2502
2503            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2504                // NOTE: We ignore potential failures here during a system scan (like
2505                // the rest of the commands above) because there's precious little we
2506                // can do about it. A settings error is reported, though.
2507                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2508                        false /* boot complete */);
2509            }
2510
2511            // Now that we know all the packages we are keeping,
2512            // read and update their last usage times.
2513            mPackageUsage.read(mPackages);
2514            mCompilerStats.read();
2515
2516            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2517                    SystemClock.uptimeMillis());
2518            Slog.i(TAG, "Time to scan packages: "
2519                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2520                    + " seconds");
2521
2522            // If the platform SDK has changed since the last time we booted,
2523            // we need to re-grant app permission to catch any new ones that
2524            // appear.  This is really a hack, and means that apps can in some
2525            // cases get permissions that the user didn't initially explicitly
2526            // allow...  it would be nice to have some better way to handle
2527            // this situation.
2528            int updateFlags = UPDATE_PERMISSIONS_ALL;
2529            if (ver.sdkVersion != mSdkVersion) {
2530                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2531                        + mSdkVersion + "; regranting permissions for internal storage");
2532                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2533            }
2534            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2535            ver.sdkVersion = mSdkVersion;
2536
2537            // If this is the first boot or an update from pre-M, and it is a normal
2538            // boot, then we need to initialize the default preferred apps across
2539            // all defined users.
2540            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2541                for (UserInfo user : sUserManager.getUsers(true)) {
2542                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2543                    applyFactoryDefaultBrowserLPw(user.id);
2544                    primeDomainVerificationsLPw(user.id);
2545                }
2546            }
2547
2548            // Prepare storage for system user really early during boot,
2549            // since core system apps like SettingsProvider and SystemUI
2550            // can't wait for user to start
2551            final int storageFlags;
2552            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2553                storageFlags = StorageManager.FLAG_STORAGE_DE;
2554            } else {
2555                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2556            }
2557            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2558                    storageFlags);
2559
2560            // If this is first boot after an OTA, and a normal boot, then
2561            // we need to clear code cache directories.
2562            // Note that we do *not* clear the application profiles. These remain valid
2563            // across OTAs and are used to drive profile verification (post OTA) and
2564            // profile compilation (without waiting to collect a fresh set of profiles).
2565            if (mIsUpgrade && !onlyCore) {
2566                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2567                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2568                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2569                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2570                        // No apps are running this early, so no need to freeze
2571                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2572                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2573                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2574                    }
2575                }
2576                ver.fingerprint = Build.FINGERPRINT;
2577            }
2578
2579            checkDefaultBrowser();
2580
2581            // clear only after permissions and other defaults have been updated
2582            mExistingSystemPackages.clear();
2583            mPromoteSystemApps = false;
2584
2585            // All the changes are done during package scanning.
2586            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2587
2588            // can downgrade to reader
2589            mSettings.writeLPr();
2590
2591            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2592            // early on (before the package manager declares itself as early) because other
2593            // components in the system server might ask for package contexts for these apps.
2594            //
2595            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2596            // (i.e, that the data partition is unavailable).
2597            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2598                long start = System.nanoTime();
2599                List<PackageParser.Package> coreApps = new ArrayList<>();
2600                for (PackageParser.Package pkg : mPackages.values()) {
2601                    if (pkg.coreApp) {
2602                        coreApps.add(pkg);
2603                    }
2604                }
2605
2606                int[] stats = performDexOptUpgrade(coreApps, false,
2607                        getCompilerFilterForReason(REASON_CORE_APP));
2608
2609                final int elapsedTimeSeconds =
2610                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2611                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2612
2613                if (DEBUG_DEXOPT) {
2614                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2615                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2616                }
2617
2618
2619                // TODO: Should we log these stats to tron too ?
2620                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2621                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2622                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2623                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2624            }
2625
2626            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2627                    SystemClock.uptimeMillis());
2628
2629            if (!mOnlyCore) {
2630                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2631                mRequiredInstallerPackage = getRequiredInstallerLPr();
2632                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2633                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2634                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2635                        mIntentFilterVerifierComponent);
2636                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2637                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2638                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2639                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2640            } else {
2641                mRequiredVerifierPackage = null;
2642                mRequiredInstallerPackage = null;
2643                mRequiredUninstallerPackage = null;
2644                mIntentFilterVerifierComponent = null;
2645                mIntentFilterVerifier = null;
2646                mServicesSystemSharedLibraryPackageName = null;
2647                mSharedSystemSharedLibraryPackageName = null;
2648            }
2649
2650            mInstallerService = new PackageInstallerService(context, this);
2651
2652            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2653            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2654            // both the installer and resolver must be present to enable ephemeral
2655            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2656                if (DEBUG_EPHEMERAL) {
2657                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2658                            + " installer:" + ephemeralInstallerComponent);
2659                }
2660                mEphemeralResolverComponent = ephemeralResolverComponent;
2661                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2662                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2663                mEphemeralResolverConnection =
2664                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2665            } else {
2666                if (DEBUG_EPHEMERAL) {
2667                    final String missingComponent =
2668                            (ephemeralResolverComponent == null)
2669                            ? (ephemeralInstallerComponent == null)
2670                                    ? "resolver and installer"
2671                                    : "resolver"
2672                            : "installer";
2673                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2674                }
2675                mEphemeralResolverComponent = null;
2676                mEphemeralInstallerComponent = null;
2677                mEphemeralResolverConnection = null;
2678            }
2679
2680            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2681        } // synchronized (mPackages)
2682        } // synchronized (mInstallLock)
2683
2684        // Now after opening every single application zip, make sure they
2685        // are all flushed.  Not really needed, but keeps things nice and
2686        // tidy.
2687        Runtime.getRuntime().gc();
2688
2689        // The initial scanning above does many calls into installd while
2690        // holding the mPackages lock, but we're mostly interested in yelling
2691        // once we have a booted system.
2692        mInstaller.setWarnIfHeld(mPackages);
2693
2694        // Expose private service for system components to use.
2695        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2696    }
2697
2698    @Override
2699    public boolean isFirstBoot() {
2700        return mFirstBoot;
2701    }
2702
2703    @Override
2704    public boolean isOnlyCoreApps() {
2705        return mOnlyCore;
2706    }
2707
2708    @Override
2709    public boolean isUpgrade() {
2710        return mIsUpgrade;
2711    }
2712
2713    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2714        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2715
2716        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2717                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2718                UserHandle.USER_SYSTEM);
2719        if (matches.size() == 1) {
2720            return matches.get(0).getComponentInfo().packageName;
2721        } else if (matches.size() == 0) {
2722            Log.e(TAG, "There should probably be a verifier, but, none were found");
2723            return null;
2724        }
2725        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2726    }
2727
2728    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2729        synchronized (mPackages) {
2730            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2731            if (libraryEntry == null) {
2732                throw new IllegalStateException("Missing required shared library:" + libraryName);
2733            }
2734            return libraryEntry.apk;
2735        }
2736    }
2737
2738    private @NonNull String getRequiredInstallerLPr() {
2739        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2740        intent.addCategory(Intent.CATEGORY_DEFAULT);
2741        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2742
2743        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2744                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2745                UserHandle.USER_SYSTEM);
2746        if (matches.size() == 1) {
2747            ResolveInfo resolveInfo = matches.get(0);
2748            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2749                throw new RuntimeException("The installer must be a privileged app");
2750            }
2751            return matches.get(0).getComponentInfo().packageName;
2752        } else {
2753            throw new RuntimeException("There must be exactly one installer; found " + matches);
2754        }
2755    }
2756
2757    private @NonNull String getRequiredUninstallerLPr() {
2758        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2759        intent.addCategory(Intent.CATEGORY_DEFAULT);
2760        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2761
2762        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2763                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2764                UserHandle.USER_SYSTEM);
2765        if (resolveInfo == null ||
2766                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2767            throw new RuntimeException("There must be exactly one uninstaller; found "
2768                    + resolveInfo);
2769        }
2770        return resolveInfo.getComponentInfo().packageName;
2771    }
2772
2773    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2774        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2775
2776        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2777                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2778                UserHandle.USER_SYSTEM);
2779        ResolveInfo best = null;
2780        final int N = matches.size();
2781        for (int i = 0; i < N; i++) {
2782            final ResolveInfo cur = matches.get(i);
2783            final String packageName = cur.getComponentInfo().packageName;
2784            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2785                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2786                continue;
2787            }
2788
2789            if (best == null || cur.priority > best.priority) {
2790                best = cur;
2791            }
2792        }
2793
2794        if (best != null) {
2795            return best.getComponentInfo().getComponentName();
2796        } else {
2797            throw new RuntimeException("There must be at least one intent filter verifier");
2798        }
2799    }
2800
2801    private @Nullable ComponentName getEphemeralResolverLPr() {
2802        final String[] packageArray =
2803                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2804        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2805            if (DEBUG_EPHEMERAL) {
2806                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2807            }
2808            return null;
2809        }
2810
2811        final int resolveFlags =
2812                MATCH_DIRECT_BOOT_AWARE
2813                | MATCH_DIRECT_BOOT_UNAWARE
2814                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2815        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2816        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2817                resolveFlags, UserHandle.USER_SYSTEM);
2818
2819        final int N = resolvers.size();
2820        if (N == 0) {
2821            if (DEBUG_EPHEMERAL) {
2822                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2823            }
2824            return null;
2825        }
2826
2827        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2828        for (int i = 0; i < N; i++) {
2829            final ResolveInfo info = resolvers.get(i);
2830
2831            if (info.serviceInfo == null) {
2832                continue;
2833            }
2834
2835            final String packageName = info.serviceInfo.packageName;
2836            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2837                if (DEBUG_EPHEMERAL) {
2838                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2839                            + " pkg: " + packageName + ", info:" + info);
2840                }
2841                continue;
2842            }
2843
2844            if (DEBUG_EPHEMERAL) {
2845                Slog.v(TAG, "Ephemeral resolver found;"
2846                        + " pkg: " + packageName + ", info:" + info);
2847            }
2848            return new ComponentName(packageName, info.serviceInfo.name);
2849        }
2850        if (DEBUG_EPHEMERAL) {
2851            Slog.v(TAG, "Ephemeral resolver NOT found");
2852        }
2853        return null;
2854    }
2855
2856    private @Nullable ComponentName getEphemeralInstallerLPr() {
2857        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2858        intent.addCategory(Intent.CATEGORY_DEFAULT);
2859        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2860
2861        final int resolveFlags =
2862                MATCH_DIRECT_BOOT_AWARE
2863                | MATCH_DIRECT_BOOT_UNAWARE
2864                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2865        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2866                resolveFlags, UserHandle.USER_SYSTEM);
2867        if (matches.size() == 0) {
2868            return null;
2869        } else if (matches.size() == 1) {
2870            return matches.get(0).getComponentInfo().getComponentName();
2871        } else {
2872            throw new RuntimeException(
2873                    "There must be at most one ephemeral installer; found " + matches);
2874        }
2875    }
2876
2877    private void primeDomainVerificationsLPw(int userId) {
2878        if (DEBUG_DOMAIN_VERIFICATION) {
2879            Slog.d(TAG, "Priming domain verifications in user " + userId);
2880        }
2881
2882        SystemConfig systemConfig = SystemConfig.getInstance();
2883        ArraySet<String> packages = systemConfig.getLinkedApps();
2884        ArraySet<String> domains = new ArraySet<String>();
2885
2886        for (String packageName : packages) {
2887            PackageParser.Package pkg = mPackages.get(packageName);
2888            if (pkg != null) {
2889                if (!pkg.isSystemApp()) {
2890                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2891                    continue;
2892                }
2893
2894                domains.clear();
2895                for (PackageParser.Activity a : pkg.activities) {
2896                    for (ActivityIntentInfo filter : a.intents) {
2897                        if (hasValidDomains(filter)) {
2898                            domains.addAll(filter.getHostsList());
2899                        }
2900                    }
2901                }
2902
2903                if (domains.size() > 0) {
2904                    if (DEBUG_DOMAIN_VERIFICATION) {
2905                        Slog.v(TAG, "      + " + packageName);
2906                    }
2907                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2908                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2909                    // and then 'always' in the per-user state actually used for intent resolution.
2910                    final IntentFilterVerificationInfo ivi;
2911                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2912                            new ArrayList<String>(domains));
2913                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2914                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2915                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2916                } else {
2917                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2918                            + "' does not handle web links");
2919                }
2920            } else {
2921                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2922            }
2923        }
2924
2925        scheduleWritePackageRestrictionsLocked(userId);
2926        scheduleWriteSettingsLocked();
2927    }
2928
2929    private void applyFactoryDefaultBrowserLPw(int userId) {
2930        // The default browser app's package name is stored in a string resource,
2931        // with a product-specific overlay used for vendor customization.
2932        String browserPkg = mContext.getResources().getString(
2933                com.android.internal.R.string.default_browser);
2934        if (!TextUtils.isEmpty(browserPkg)) {
2935            // non-empty string => required to be a known package
2936            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2937            if (ps == null) {
2938                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2939                browserPkg = null;
2940            } else {
2941                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2942            }
2943        }
2944
2945        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2946        // default.  If there's more than one, just leave everything alone.
2947        if (browserPkg == null) {
2948            calculateDefaultBrowserLPw(userId);
2949        }
2950    }
2951
2952    private void calculateDefaultBrowserLPw(int userId) {
2953        List<String> allBrowsers = resolveAllBrowserApps(userId);
2954        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2955        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2956    }
2957
2958    private List<String> resolveAllBrowserApps(int userId) {
2959        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2960        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2961                PackageManager.MATCH_ALL, userId);
2962
2963        final int count = list.size();
2964        List<String> result = new ArrayList<String>(count);
2965        for (int i=0; i<count; i++) {
2966            ResolveInfo info = list.get(i);
2967            if (info.activityInfo == null
2968                    || !info.handleAllWebDataURI
2969                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2970                    || result.contains(info.activityInfo.packageName)) {
2971                continue;
2972            }
2973            result.add(info.activityInfo.packageName);
2974        }
2975
2976        return result;
2977    }
2978
2979    private boolean packageIsBrowser(String packageName, int userId) {
2980        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2981                PackageManager.MATCH_ALL, userId);
2982        final int N = list.size();
2983        for (int i = 0; i < N; i++) {
2984            ResolveInfo info = list.get(i);
2985            if (packageName.equals(info.activityInfo.packageName)) {
2986                return true;
2987            }
2988        }
2989        return false;
2990    }
2991
2992    private void checkDefaultBrowser() {
2993        final int myUserId = UserHandle.myUserId();
2994        final String packageName = getDefaultBrowserPackageName(myUserId);
2995        if (packageName != null) {
2996            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2997            if (info == null) {
2998                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2999                synchronized (mPackages) {
3000                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3001                }
3002            }
3003        }
3004    }
3005
3006    @Override
3007    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3008            throws RemoteException {
3009        try {
3010            return super.onTransact(code, data, reply, flags);
3011        } catch (RuntimeException e) {
3012            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3013                Slog.wtf(TAG, "Package Manager Crash", e);
3014            }
3015            throw e;
3016        }
3017    }
3018
3019    static int[] appendInts(int[] cur, int[] add) {
3020        if (add == null) return cur;
3021        if (cur == null) return add;
3022        final int N = add.length;
3023        for (int i=0; i<N; i++) {
3024            cur = appendInt(cur, add[i]);
3025        }
3026        return cur;
3027    }
3028
3029    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3030        if (!sUserManager.exists(userId)) return null;
3031        if (ps == null) {
3032            return null;
3033        }
3034        final PackageParser.Package p = ps.pkg;
3035        if (p == null) {
3036            return null;
3037        }
3038
3039        final PermissionsState permissionsState = ps.getPermissionsState();
3040
3041        // Compute GIDs only if requested
3042        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3043                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3044        // Compute granted permissions only if package has requested permissions
3045        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3046                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3047        final PackageUserState state = ps.readUserState(userId);
3048
3049        return PackageParser.generatePackageInfo(p, gids, flags,
3050                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3051    }
3052
3053    @Override
3054    public void checkPackageStartable(String packageName, int userId) {
3055        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3056
3057        synchronized (mPackages) {
3058            final PackageSetting ps = mSettings.mPackages.get(packageName);
3059            if (ps == null) {
3060                throw new SecurityException("Package " + packageName + " was not found!");
3061            }
3062
3063            if (!ps.getInstalled(userId)) {
3064                throw new SecurityException(
3065                        "Package " + packageName + " was not installed for user " + userId + "!");
3066            }
3067
3068            if (mSafeMode && !ps.isSystem()) {
3069                throw new SecurityException("Package " + packageName + " not a system app!");
3070            }
3071
3072            if (mFrozenPackages.contains(packageName)) {
3073                throw new SecurityException("Package " + packageName + " is currently frozen!");
3074            }
3075
3076            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3077                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3078                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3079            }
3080        }
3081    }
3082
3083    @Override
3084    public boolean isPackageAvailable(String packageName, int userId) {
3085        if (!sUserManager.exists(userId)) return false;
3086        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3087                false /* requireFullPermission */, false /* checkShell */, "is package available");
3088        synchronized (mPackages) {
3089            PackageParser.Package p = mPackages.get(packageName);
3090            if (p != null) {
3091                final PackageSetting ps = (PackageSetting) p.mExtras;
3092                if (ps != null) {
3093                    final PackageUserState state = ps.readUserState(userId);
3094                    if (state != null) {
3095                        return PackageParser.isAvailable(state);
3096                    }
3097                }
3098            }
3099        }
3100        return false;
3101    }
3102
3103    @Override
3104    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3105        if (!sUserManager.exists(userId)) return null;
3106        flags = updateFlagsForPackage(flags, userId, packageName);
3107        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3108                false /* requireFullPermission */, false /* checkShell */, "get package info");
3109        // reader
3110        synchronized (mPackages) {
3111            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3112            PackageParser.Package p = null;
3113            if (matchFactoryOnly) {
3114                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3115                if (ps != null) {
3116                    return generatePackageInfo(ps, flags, userId);
3117                }
3118            }
3119            if (p == null) {
3120                p = mPackages.get(packageName);
3121                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3122                    return null;
3123                }
3124            }
3125            if (DEBUG_PACKAGE_INFO)
3126                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3127            if (p != null) {
3128                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3129            }
3130            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3131                final PackageSetting ps = mSettings.mPackages.get(packageName);
3132                return generatePackageInfo(ps, flags, userId);
3133            }
3134        }
3135        return null;
3136    }
3137
3138    @Override
3139    public String[] currentToCanonicalPackageNames(String[] names) {
3140        String[] out = new String[names.length];
3141        // reader
3142        synchronized (mPackages) {
3143            for (int i=names.length-1; i>=0; i--) {
3144                PackageSetting ps = mSettings.mPackages.get(names[i]);
3145                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3146            }
3147        }
3148        return out;
3149    }
3150
3151    @Override
3152    public String[] canonicalToCurrentPackageNames(String[] names) {
3153        String[] out = new String[names.length];
3154        // reader
3155        synchronized (mPackages) {
3156            for (int i=names.length-1; i>=0; i--) {
3157                String cur = mSettings.mRenamedPackages.get(names[i]);
3158                out[i] = cur != null ? cur : names[i];
3159            }
3160        }
3161        return out;
3162    }
3163
3164    @Override
3165    public int getPackageUid(String packageName, int flags, int userId) {
3166        if (!sUserManager.exists(userId)) return -1;
3167        flags = updateFlagsForPackage(flags, userId, packageName);
3168        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3169                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3170
3171        // reader
3172        synchronized (mPackages) {
3173            final PackageParser.Package p = mPackages.get(packageName);
3174            if (p != null && p.isMatch(flags)) {
3175                return UserHandle.getUid(userId, p.applicationInfo.uid);
3176            }
3177            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3178                final PackageSetting ps = mSettings.mPackages.get(packageName);
3179                if (ps != null && ps.isMatch(flags)) {
3180                    return UserHandle.getUid(userId, ps.appId);
3181                }
3182            }
3183        }
3184
3185        return -1;
3186    }
3187
3188    @Override
3189    public int[] getPackageGids(String packageName, int flags, int userId) {
3190        if (!sUserManager.exists(userId)) return null;
3191        flags = updateFlagsForPackage(flags, userId, packageName);
3192        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3193                false /* requireFullPermission */, false /* checkShell */,
3194                "getPackageGids");
3195
3196        // reader
3197        synchronized (mPackages) {
3198            final PackageParser.Package p = mPackages.get(packageName);
3199            if (p != null && p.isMatch(flags)) {
3200                PackageSetting ps = (PackageSetting) p.mExtras;
3201                return ps.getPermissionsState().computeGids(userId);
3202            }
3203            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3204                final PackageSetting ps = mSettings.mPackages.get(packageName);
3205                if (ps != null && ps.isMatch(flags)) {
3206                    return ps.getPermissionsState().computeGids(userId);
3207                }
3208            }
3209        }
3210
3211        return null;
3212    }
3213
3214    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3215        if (bp.perm != null) {
3216            return PackageParser.generatePermissionInfo(bp.perm, flags);
3217        }
3218        PermissionInfo pi = new PermissionInfo();
3219        pi.name = bp.name;
3220        pi.packageName = bp.sourcePackage;
3221        pi.nonLocalizedLabel = bp.name;
3222        pi.protectionLevel = bp.protectionLevel;
3223        return pi;
3224    }
3225
3226    @Override
3227    public PermissionInfo getPermissionInfo(String name, int flags) {
3228        // reader
3229        synchronized (mPackages) {
3230            final BasePermission p = mSettings.mPermissions.get(name);
3231            if (p != null) {
3232                return generatePermissionInfo(p, flags);
3233            }
3234            return null;
3235        }
3236    }
3237
3238    @Override
3239    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3240            int flags) {
3241        // reader
3242        synchronized (mPackages) {
3243            if (group != null && !mPermissionGroups.containsKey(group)) {
3244                // This is thrown as NameNotFoundException
3245                return null;
3246            }
3247
3248            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3249            for (BasePermission p : mSettings.mPermissions.values()) {
3250                if (group == null) {
3251                    if (p.perm == null || p.perm.info.group == null) {
3252                        out.add(generatePermissionInfo(p, flags));
3253                    }
3254                } else {
3255                    if (p.perm != null && group.equals(p.perm.info.group)) {
3256                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3257                    }
3258                }
3259            }
3260            return new ParceledListSlice<>(out);
3261        }
3262    }
3263
3264    @Override
3265    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3266        // reader
3267        synchronized (mPackages) {
3268            return PackageParser.generatePermissionGroupInfo(
3269                    mPermissionGroups.get(name), flags);
3270        }
3271    }
3272
3273    @Override
3274    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3275        // reader
3276        synchronized (mPackages) {
3277            final int N = mPermissionGroups.size();
3278            ArrayList<PermissionGroupInfo> out
3279                    = new ArrayList<PermissionGroupInfo>(N);
3280            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3281                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3282            }
3283            return new ParceledListSlice<>(out);
3284        }
3285    }
3286
3287    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3288            int userId) {
3289        if (!sUserManager.exists(userId)) return null;
3290        PackageSetting ps = mSettings.mPackages.get(packageName);
3291        if (ps != null) {
3292            if (ps.pkg == null) {
3293                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3294                if (pInfo != null) {
3295                    return pInfo.applicationInfo;
3296                }
3297                return null;
3298            }
3299            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3300                    ps.readUserState(userId), userId);
3301        }
3302        return null;
3303    }
3304
3305    @Override
3306    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3307        if (!sUserManager.exists(userId)) return null;
3308        flags = updateFlagsForApplication(flags, userId, packageName);
3309        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3310                false /* requireFullPermission */, false /* checkShell */, "get application info");
3311        // writer
3312        synchronized (mPackages) {
3313            PackageParser.Package p = mPackages.get(packageName);
3314            if (DEBUG_PACKAGE_INFO) Log.v(
3315                    TAG, "getApplicationInfo " + packageName
3316                    + ": " + p);
3317            if (p != null) {
3318                PackageSetting ps = mSettings.mPackages.get(packageName);
3319                if (ps == null) return null;
3320                // Note: isEnabledLP() does not apply here - always return info
3321                return PackageParser.generateApplicationInfo(
3322                        p, flags, ps.readUserState(userId), userId);
3323            }
3324            if ("android".equals(packageName)||"system".equals(packageName)) {
3325                return mAndroidApplication;
3326            }
3327            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3328                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3329            }
3330        }
3331        return null;
3332    }
3333
3334    @Override
3335    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3336            final IPackageDataObserver observer) {
3337        mContext.enforceCallingOrSelfPermission(
3338                android.Manifest.permission.CLEAR_APP_CACHE, null);
3339        // Queue up an async operation since clearing cache may take a little while.
3340        mHandler.post(new Runnable() {
3341            public void run() {
3342                mHandler.removeCallbacks(this);
3343                boolean success = true;
3344                synchronized (mInstallLock) {
3345                    try {
3346                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3347                    } catch (InstallerException e) {
3348                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3349                        success = false;
3350                    }
3351                }
3352                if (observer != null) {
3353                    try {
3354                        observer.onRemoveCompleted(null, success);
3355                    } catch (RemoteException e) {
3356                        Slog.w(TAG, "RemoveException when invoking call back");
3357                    }
3358                }
3359            }
3360        });
3361    }
3362
3363    @Override
3364    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3365            final IntentSender pi) {
3366        mContext.enforceCallingOrSelfPermission(
3367                android.Manifest.permission.CLEAR_APP_CACHE, null);
3368        // Queue up an async operation since clearing cache may take a little while.
3369        mHandler.post(new Runnable() {
3370            public void run() {
3371                mHandler.removeCallbacks(this);
3372                boolean success = true;
3373                synchronized (mInstallLock) {
3374                    try {
3375                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3376                    } catch (InstallerException e) {
3377                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3378                        success = false;
3379                    }
3380                }
3381                if(pi != null) {
3382                    try {
3383                        // Callback via pending intent
3384                        int code = success ? 1 : 0;
3385                        pi.sendIntent(null, code, null,
3386                                null, null);
3387                    } catch (SendIntentException e1) {
3388                        Slog.i(TAG, "Failed to send pending intent");
3389                    }
3390                }
3391            }
3392        });
3393    }
3394
3395    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3396        synchronized (mInstallLock) {
3397            try {
3398                mInstaller.freeCache(volumeUuid, freeStorageSize);
3399            } catch (InstallerException e) {
3400                throw new IOException("Failed to free enough space", e);
3401            }
3402        }
3403    }
3404
3405    /**
3406     * Update given flags based on encryption status of current user.
3407     */
3408    private int updateFlags(int flags, int userId) {
3409        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3410                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3411            // Caller expressed an explicit opinion about what encryption
3412            // aware/unaware components they want to see, so fall through and
3413            // give them what they want
3414        } else {
3415            // Caller expressed no opinion, so match based on user state
3416            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3417                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3418            } else {
3419                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3420            }
3421        }
3422        return flags;
3423    }
3424
3425    private UserManagerInternal getUserManagerInternal() {
3426        if (mUserManagerInternal == null) {
3427            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3428        }
3429        return mUserManagerInternal;
3430    }
3431
3432    /**
3433     * Update given flags when being used to request {@link PackageInfo}.
3434     */
3435    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3436        boolean triaged = true;
3437        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3438                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3439            // Caller is asking for component details, so they'd better be
3440            // asking for specific encryption matching behavior, or be triaged
3441            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3442                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3443                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3444                triaged = false;
3445            }
3446        }
3447        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3448                | PackageManager.MATCH_SYSTEM_ONLY
3449                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3450            triaged = false;
3451        }
3452        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3453            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3454                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3455        }
3456        return updateFlags(flags, userId);
3457    }
3458
3459    /**
3460     * Update given flags when being used to request {@link ApplicationInfo}.
3461     */
3462    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3463        return updateFlagsForPackage(flags, userId, cookie);
3464    }
3465
3466    /**
3467     * Update given flags when being used to request {@link ComponentInfo}.
3468     */
3469    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3470        if (cookie instanceof Intent) {
3471            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3472                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3473            }
3474        }
3475
3476        boolean triaged = true;
3477        // Caller is asking for component details, so they'd better be
3478        // asking for specific encryption matching behavior, or be triaged
3479        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3480                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3481                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3482            triaged = false;
3483        }
3484        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3485            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3486                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3487        }
3488
3489        return updateFlags(flags, userId);
3490    }
3491
3492    /**
3493     * Update given flags when being used to request {@link ResolveInfo}.
3494     */
3495    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3496        // Safe mode means we shouldn't match any third-party components
3497        if (mSafeMode) {
3498            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3499        }
3500
3501        return updateFlagsForComponent(flags, userId, cookie);
3502    }
3503
3504    @Override
3505    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3506        if (!sUserManager.exists(userId)) return null;
3507        flags = updateFlagsForComponent(flags, userId, component);
3508        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3509                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3510        synchronized (mPackages) {
3511            PackageParser.Activity a = mActivities.mActivities.get(component);
3512
3513            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3514            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3515                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3516                if (ps == null) return null;
3517                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3518                        userId);
3519            }
3520            if (mResolveComponentName.equals(component)) {
3521                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3522                        new PackageUserState(), userId);
3523            }
3524        }
3525        return null;
3526    }
3527
3528    @Override
3529    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3530            String resolvedType) {
3531        synchronized (mPackages) {
3532            if (component.equals(mResolveComponentName)) {
3533                // The resolver supports EVERYTHING!
3534                return true;
3535            }
3536            PackageParser.Activity a = mActivities.mActivities.get(component);
3537            if (a == null) {
3538                return false;
3539            }
3540            for (int i=0; i<a.intents.size(); i++) {
3541                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3542                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3543                    return true;
3544                }
3545            }
3546            return false;
3547        }
3548    }
3549
3550    @Override
3551    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3552        if (!sUserManager.exists(userId)) return null;
3553        flags = updateFlagsForComponent(flags, userId, component);
3554        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3555                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3556        synchronized (mPackages) {
3557            PackageParser.Activity a = mReceivers.mActivities.get(component);
3558            if (DEBUG_PACKAGE_INFO) Log.v(
3559                TAG, "getReceiverInfo " + component + ": " + a);
3560            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3561                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3562                if (ps == null) return null;
3563                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3564                        userId);
3565            }
3566        }
3567        return null;
3568    }
3569
3570    @Override
3571    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3572        if (!sUserManager.exists(userId)) return null;
3573        flags = updateFlagsForComponent(flags, userId, component);
3574        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3575                false /* requireFullPermission */, false /* checkShell */, "get service info");
3576        synchronized (mPackages) {
3577            PackageParser.Service s = mServices.mServices.get(component);
3578            if (DEBUG_PACKAGE_INFO) Log.v(
3579                TAG, "getServiceInfo " + component + ": " + s);
3580            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3581                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3582                if (ps == null) return null;
3583                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3584                        userId);
3585            }
3586        }
3587        return null;
3588    }
3589
3590    @Override
3591    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3592        if (!sUserManager.exists(userId)) return null;
3593        flags = updateFlagsForComponent(flags, userId, component);
3594        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3595                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3596        synchronized (mPackages) {
3597            PackageParser.Provider p = mProviders.mProviders.get(component);
3598            if (DEBUG_PACKAGE_INFO) Log.v(
3599                TAG, "getProviderInfo " + component + ": " + p);
3600            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3601                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3602                if (ps == null) return null;
3603                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3604                        userId);
3605            }
3606        }
3607        return null;
3608    }
3609
3610    @Override
3611    public String[] getSystemSharedLibraryNames() {
3612        Set<String> libSet;
3613        synchronized (mPackages) {
3614            libSet = mSharedLibraries.keySet();
3615            int size = libSet.size();
3616            if (size > 0) {
3617                String[] libs = new String[size];
3618                libSet.toArray(libs);
3619                return libs;
3620            }
3621        }
3622        return null;
3623    }
3624
3625    @Override
3626    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3627        synchronized (mPackages) {
3628            return mServicesSystemSharedLibraryPackageName;
3629        }
3630    }
3631
3632    @Override
3633    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3634        synchronized (mPackages) {
3635            return mSharedSystemSharedLibraryPackageName;
3636        }
3637    }
3638
3639    @Override
3640    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3641        synchronized (mPackages) {
3642            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3643
3644            final FeatureInfo fi = new FeatureInfo();
3645            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3646                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3647            res.add(fi);
3648
3649            return new ParceledListSlice<>(res);
3650        }
3651    }
3652
3653    @Override
3654    public boolean hasSystemFeature(String name, int version) {
3655        synchronized (mPackages) {
3656            final FeatureInfo feat = mAvailableFeatures.get(name);
3657            if (feat == null) {
3658                return false;
3659            } else {
3660                return feat.version >= version;
3661            }
3662        }
3663    }
3664
3665    @Override
3666    public int checkPermission(String permName, String pkgName, int userId) {
3667        if (!sUserManager.exists(userId)) {
3668            return PackageManager.PERMISSION_DENIED;
3669        }
3670
3671        synchronized (mPackages) {
3672            final PackageParser.Package p = mPackages.get(pkgName);
3673            if (p != null && p.mExtras != null) {
3674                final PackageSetting ps = (PackageSetting) p.mExtras;
3675                final PermissionsState permissionsState = ps.getPermissionsState();
3676                if (permissionsState.hasPermission(permName, userId)) {
3677                    return PackageManager.PERMISSION_GRANTED;
3678                }
3679                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3680                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3681                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3682                    return PackageManager.PERMISSION_GRANTED;
3683                }
3684            }
3685        }
3686
3687        return PackageManager.PERMISSION_DENIED;
3688    }
3689
3690    @Override
3691    public int checkUidPermission(String permName, int uid) {
3692        final int userId = UserHandle.getUserId(uid);
3693
3694        if (!sUserManager.exists(userId)) {
3695            return PackageManager.PERMISSION_DENIED;
3696        }
3697
3698        synchronized (mPackages) {
3699            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3700            if (obj != null) {
3701                final SettingBase ps = (SettingBase) obj;
3702                final PermissionsState permissionsState = ps.getPermissionsState();
3703                if (permissionsState.hasPermission(permName, userId)) {
3704                    return PackageManager.PERMISSION_GRANTED;
3705                }
3706                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3707                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3708                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3709                    return PackageManager.PERMISSION_GRANTED;
3710                }
3711            } else {
3712                ArraySet<String> perms = mSystemPermissions.get(uid);
3713                if (perms != null) {
3714                    if (perms.contains(permName)) {
3715                        return PackageManager.PERMISSION_GRANTED;
3716                    }
3717                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3718                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3719                        return PackageManager.PERMISSION_GRANTED;
3720                    }
3721                }
3722            }
3723        }
3724
3725        return PackageManager.PERMISSION_DENIED;
3726    }
3727
3728    @Override
3729    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3730        if (UserHandle.getCallingUserId() != userId) {
3731            mContext.enforceCallingPermission(
3732                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3733                    "isPermissionRevokedByPolicy for user " + userId);
3734        }
3735
3736        if (checkPermission(permission, packageName, userId)
3737                == PackageManager.PERMISSION_GRANTED) {
3738            return false;
3739        }
3740
3741        final long identity = Binder.clearCallingIdentity();
3742        try {
3743            final int flags = getPermissionFlags(permission, packageName, userId);
3744            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3745        } finally {
3746            Binder.restoreCallingIdentity(identity);
3747        }
3748    }
3749
3750    @Override
3751    public String getPermissionControllerPackageName() {
3752        synchronized (mPackages) {
3753            return mRequiredInstallerPackage;
3754        }
3755    }
3756
3757    /**
3758     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3759     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3760     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3761     * @param message the message to log on security exception
3762     */
3763    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3764            boolean checkShell, String message) {
3765        if (userId < 0) {
3766            throw new IllegalArgumentException("Invalid userId " + userId);
3767        }
3768        if (checkShell) {
3769            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3770        }
3771        if (userId == UserHandle.getUserId(callingUid)) return;
3772        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3773            if (requireFullPermission) {
3774                mContext.enforceCallingOrSelfPermission(
3775                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3776            } else {
3777                try {
3778                    mContext.enforceCallingOrSelfPermission(
3779                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3780                } catch (SecurityException se) {
3781                    mContext.enforceCallingOrSelfPermission(
3782                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3783                }
3784            }
3785        }
3786    }
3787
3788    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3789        if (callingUid == Process.SHELL_UID) {
3790            if (userHandle >= 0
3791                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3792                throw new SecurityException("Shell does not have permission to access user "
3793                        + userHandle);
3794            } else if (userHandle < 0) {
3795                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3796                        + Debug.getCallers(3));
3797            }
3798        }
3799    }
3800
3801    private BasePermission findPermissionTreeLP(String permName) {
3802        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3803            if (permName.startsWith(bp.name) &&
3804                    permName.length() > bp.name.length() &&
3805                    permName.charAt(bp.name.length()) == '.') {
3806                return bp;
3807            }
3808        }
3809        return null;
3810    }
3811
3812    private BasePermission checkPermissionTreeLP(String permName) {
3813        if (permName != null) {
3814            BasePermission bp = findPermissionTreeLP(permName);
3815            if (bp != null) {
3816                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3817                    return bp;
3818                }
3819                throw new SecurityException("Calling uid "
3820                        + Binder.getCallingUid()
3821                        + " is not allowed to add to permission tree "
3822                        + bp.name + " owned by uid " + bp.uid);
3823            }
3824        }
3825        throw new SecurityException("No permission tree found for " + permName);
3826    }
3827
3828    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3829        if (s1 == null) {
3830            return s2 == null;
3831        }
3832        if (s2 == null) {
3833            return false;
3834        }
3835        if (s1.getClass() != s2.getClass()) {
3836            return false;
3837        }
3838        return s1.equals(s2);
3839    }
3840
3841    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3842        if (pi1.icon != pi2.icon) return false;
3843        if (pi1.logo != pi2.logo) return false;
3844        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3845        if (!compareStrings(pi1.name, pi2.name)) return false;
3846        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3847        // We'll take care of setting this one.
3848        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3849        // These are not currently stored in settings.
3850        //if (!compareStrings(pi1.group, pi2.group)) return false;
3851        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3852        //if (pi1.labelRes != pi2.labelRes) return false;
3853        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3854        return true;
3855    }
3856
3857    int permissionInfoFootprint(PermissionInfo info) {
3858        int size = info.name.length();
3859        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3860        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3861        return size;
3862    }
3863
3864    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3865        int size = 0;
3866        for (BasePermission perm : mSettings.mPermissions.values()) {
3867            if (perm.uid == tree.uid) {
3868                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3869            }
3870        }
3871        return size;
3872    }
3873
3874    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3875        // We calculate the max size of permissions defined by this uid and throw
3876        // if that plus the size of 'info' would exceed our stated maximum.
3877        if (tree.uid != Process.SYSTEM_UID) {
3878            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3879            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3880                throw new SecurityException("Permission tree size cap exceeded");
3881            }
3882        }
3883    }
3884
3885    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3886        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3887            throw new SecurityException("Label must be specified in permission");
3888        }
3889        BasePermission tree = checkPermissionTreeLP(info.name);
3890        BasePermission bp = mSettings.mPermissions.get(info.name);
3891        boolean added = bp == null;
3892        boolean changed = true;
3893        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3894        if (added) {
3895            enforcePermissionCapLocked(info, tree);
3896            bp = new BasePermission(info.name, tree.sourcePackage,
3897                    BasePermission.TYPE_DYNAMIC);
3898        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3899            throw new SecurityException(
3900                    "Not allowed to modify non-dynamic permission "
3901                    + info.name);
3902        } else {
3903            if (bp.protectionLevel == fixedLevel
3904                    && bp.perm.owner.equals(tree.perm.owner)
3905                    && bp.uid == tree.uid
3906                    && comparePermissionInfos(bp.perm.info, info)) {
3907                changed = false;
3908            }
3909        }
3910        bp.protectionLevel = fixedLevel;
3911        info = new PermissionInfo(info);
3912        info.protectionLevel = fixedLevel;
3913        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3914        bp.perm.info.packageName = tree.perm.info.packageName;
3915        bp.uid = tree.uid;
3916        if (added) {
3917            mSettings.mPermissions.put(info.name, bp);
3918        }
3919        if (changed) {
3920            if (!async) {
3921                mSettings.writeLPr();
3922            } else {
3923                scheduleWriteSettingsLocked();
3924            }
3925        }
3926        return added;
3927    }
3928
3929    @Override
3930    public boolean addPermission(PermissionInfo info) {
3931        synchronized (mPackages) {
3932            return addPermissionLocked(info, false);
3933        }
3934    }
3935
3936    @Override
3937    public boolean addPermissionAsync(PermissionInfo info) {
3938        synchronized (mPackages) {
3939            return addPermissionLocked(info, true);
3940        }
3941    }
3942
3943    @Override
3944    public void removePermission(String name) {
3945        synchronized (mPackages) {
3946            checkPermissionTreeLP(name);
3947            BasePermission bp = mSettings.mPermissions.get(name);
3948            if (bp != null) {
3949                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3950                    throw new SecurityException(
3951                            "Not allowed to modify non-dynamic permission "
3952                            + name);
3953                }
3954                mSettings.mPermissions.remove(name);
3955                mSettings.writeLPr();
3956            }
3957        }
3958    }
3959
3960    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3961            BasePermission bp) {
3962        int index = pkg.requestedPermissions.indexOf(bp.name);
3963        if (index == -1) {
3964            throw new SecurityException("Package " + pkg.packageName
3965                    + " has not requested permission " + bp.name);
3966        }
3967        if (!bp.isRuntime() && !bp.isDevelopment()) {
3968            throw new SecurityException("Permission " + bp.name
3969                    + " is not a changeable permission type");
3970        }
3971    }
3972
3973    @Override
3974    public void grantRuntimePermission(String packageName, String name, final int userId) {
3975        if (!sUserManager.exists(userId)) {
3976            Log.e(TAG, "No such user:" + userId);
3977            return;
3978        }
3979
3980        mContext.enforceCallingOrSelfPermission(
3981                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3982                "grantRuntimePermission");
3983
3984        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3985                true /* requireFullPermission */, true /* checkShell */,
3986                "grantRuntimePermission");
3987
3988        final int uid;
3989        final SettingBase sb;
3990
3991        synchronized (mPackages) {
3992            final PackageParser.Package pkg = mPackages.get(packageName);
3993            if (pkg == null) {
3994                throw new IllegalArgumentException("Unknown package: " + packageName);
3995            }
3996
3997            final BasePermission bp = mSettings.mPermissions.get(name);
3998            if (bp == null) {
3999                throw new IllegalArgumentException("Unknown permission: " + name);
4000            }
4001
4002            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4003
4004            // If a permission review is required for legacy apps we represent
4005            // their permissions as always granted runtime ones since we need
4006            // to keep the review required permission flag per user while an
4007            // install permission's state is shared across all users.
4008            if (Build.PERMISSIONS_REVIEW_REQUIRED
4009                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4010                    && bp.isRuntime()) {
4011                return;
4012            }
4013
4014            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4015            sb = (SettingBase) pkg.mExtras;
4016            if (sb == null) {
4017                throw new IllegalArgumentException("Unknown package: " + packageName);
4018            }
4019
4020            final PermissionsState permissionsState = sb.getPermissionsState();
4021
4022            final int flags = permissionsState.getPermissionFlags(name, userId);
4023            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4024                throw new SecurityException("Cannot grant system fixed permission "
4025                        + name + " for package " + packageName);
4026            }
4027
4028            if (bp.isDevelopment()) {
4029                // Development permissions must be handled specially, since they are not
4030                // normal runtime permissions.  For now they apply to all users.
4031                if (permissionsState.grantInstallPermission(bp) !=
4032                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4033                    scheduleWriteSettingsLocked();
4034                }
4035                return;
4036            }
4037
4038            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4039                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4040                return;
4041            }
4042
4043            final int result = permissionsState.grantRuntimePermission(bp, userId);
4044            switch (result) {
4045                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4046                    return;
4047                }
4048
4049                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4050                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4051                    mHandler.post(new Runnable() {
4052                        @Override
4053                        public void run() {
4054                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4055                        }
4056                    });
4057                }
4058                break;
4059            }
4060
4061            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4062
4063            // Not critical if that is lost - app has to request again.
4064            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4065        }
4066
4067        // Only need to do this if user is initialized. Otherwise it's a new user
4068        // and there are no processes running as the user yet and there's no need
4069        // to make an expensive call to remount processes for the changed permissions.
4070        if (READ_EXTERNAL_STORAGE.equals(name)
4071                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4072            final long token = Binder.clearCallingIdentity();
4073            try {
4074                if (sUserManager.isInitialized(userId)) {
4075                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4076                            MountServiceInternal.class);
4077                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4078                }
4079            } finally {
4080                Binder.restoreCallingIdentity(token);
4081            }
4082        }
4083    }
4084
4085    @Override
4086    public void revokeRuntimePermission(String packageName, String name, int userId) {
4087        if (!sUserManager.exists(userId)) {
4088            Log.e(TAG, "No such user:" + userId);
4089            return;
4090        }
4091
4092        mContext.enforceCallingOrSelfPermission(
4093                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4094                "revokeRuntimePermission");
4095
4096        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4097                true /* requireFullPermission */, true /* checkShell */,
4098                "revokeRuntimePermission");
4099
4100        final int appId;
4101
4102        synchronized (mPackages) {
4103            final PackageParser.Package pkg = mPackages.get(packageName);
4104            if (pkg == null) {
4105                throw new IllegalArgumentException("Unknown package: " + packageName);
4106            }
4107
4108            final BasePermission bp = mSettings.mPermissions.get(name);
4109            if (bp == null) {
4110                throw new IllegalArgumentException("Unknown permission: " + name);
4111            }
4112
4113            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4114
4115            // If a permission review is required for legacy apps we represent
4116            // their permissions as always granted runtime ones since we need
4117            // to keep the review required permission flag per user while an
4118            // install permission's state is shared across all users.
4119            if (Build.PERMISSIONS_REVIEW_REQUIRED
4120                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4121                    && bp.isRuntime()) {
4122                return;
4123            }
4124
4125            SettingBase sb = (SettingBase) pkg.mExtras;
4126            if (sb == null) {
4127                throw new IllegalArgumentException("Unknown package: " + packageName);
4128            }
4129
4130            final PermissionsState permissionsState = sb.getPermissionsState();
4131
4132            final int flags = permissionsState.getPermissionFlags(name, userId);
4133            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4134                throw new SecurityException("Cannot revoke system fixed permission "
4135                        + name + " for package " + packageName);
4136            }
4137
4138            if (bp.isDevelopment()) {
4139                // Development permissions must be handled specially, since they are not
4140                // normal runtime permissions.  For now they apply to all users.
4141                if (permissionsState.revokeInstallPermission(bp) !=
4142                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4143                    scheduleWriteSettingsLocked();
4144                }
4145                return;
4146            }
4147
4148            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4149                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4150                return;
4151            }
4152
4153            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4154
4155            // Critical, after this call app should never have the permission.
4156            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4157
4158            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4159        }
4160
4161        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4162    }
4163
4164    @Override
4165    public void resetRuntimePermissions() {
4166        mContext.enforceCallingOrSelfPermission(
4167                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4168                "revokeRuntimePermission");
4169
4170        int callingUid = Binder.getCallingUid();
4171        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4172            mContext.enforceCallingOrSelfPermission(
4173                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4174                    "resetRuntimePermissions");
4175        }
4176
4177        synchronized (mPackages) {
4178            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4179            for (int userId : UserManagerService.getInstance().getUserIds()) {
4180                final int packageCount = mPackages.size();
4181                for (int i = 0; i < packageCount; i++) {
4182                    PackageParser.Package pkg = mPackages.valueAt(i);
4183                    if (!(pkg.mExtras instanceof PackageSetting)) {
4184                        continue;
4185                    }
4186                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4187                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4188                }
4189            }
4190        }
4191    }
4192
4193    @Override
4194    public int getPermissionFlags(String name, String packageName, int userId) {
4195        if (!sUserManager.exists(userId)) {
4196            return 0;
4197        }
4198
4199        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4200
4201        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4202                true /* requireFullPermission */, false /* checkShell */,
4203                "getPermissionFlags");
4204
4205        synchronized (mPackages) {
4206            final PackageParser.Package pkg = mPackages.get(packageName);
4207            if (pkg == null) {
4208                return 0;
4209            }
4210
4211            final BasePermission bp = mSettings.mPermissions.get(name);
4212            if (bp == null) {
4213                return 0;
4214            }
4215
4216            SettingBase sb = (SettingBase) pkg.mExtras;
4217            if (sb == null) {
4218                return 0;
4219            }
4220
4221            PermissionsState permissionsState = sb.getPermissionsState();
4222            return permissionsState.getPermissionFlags(name, userId);
4223        }
4224    }
4225
4226    @Override
4227    public void updatePermissionFlags(String name, String packageName, int flagMask,
4228            int flagValues, int userId) {
4229        if (!sUserManager.exists(userId)) {
4230            return;
4231        }
4232
4233        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4234
4235        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4236                true /* requireFullPermission */, true /* checkShell */,
4237                "updatePermissionFlags");
4238
4239        // Only the system can change these flags and nothing else.
4240        if (getCallingUid() != Process.SYSTEM_UID) {
4241            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4242            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4243            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4244            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4245            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4246        }
4247
4248        synchronized (mPackages) {
4249            final PackageParser.Package pkg = mPackages.get(packageName);
4250            if (pkg == null) {
4251                throw new IllegalArgumentException("Unknown package: " + packageName);
4252            }
4253
4254            final BasePermission bp = mSettings.mPermissions.get(name);
4255            if (bp == null) {
4256                throw new IllegalArgumentException("Unknown permission: " + name);
4257            }
4258
4259            SettingBase sb = (SettingBase) pkg.mExtras;
4260            if (sb == null) {
4261                throw new IllegalArgumentException("Unknown package: " + packageName);
4262            }
4263
4264            PermissionsState permissionsState = sb.getPermissionsState();
4265
4266            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4267
4268            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4269                // Install and runtime permissions are stored in different places,
4270                // so figure out what permission changed and persist the change.
4271                if (permissionsState.getInstallPermissionState(name) != null) {
4272                    scheduleWriteSettingsLocked();
4273                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4274                        || hadState) {
4275                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4276                }
4277            }
4278        }
4279    }
4280
4281    /**
4282     * Update the permission flags for all packages and runtime permissions of a user in order
4283     * to allow device or profile owner to remove POLICY_FIXED.
4284     */
4285    @Override
4286    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4287        if (!sUserManager.exists(userId)) {
4288            return;
4289        }
4290
4291        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4292
4293        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4294                true /* requireFullPermission */, true /* checkShell */,
4295                "updatePermissionFlagsForAllApps");
4296
4297        // Only the system can change system fixed flags.
4298        if (getCallingUid() != Process.SYSTEM_UID) {
4299            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4300            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4301        }
4302
4303        synchronized (mPackages) {
4304            boolean changed = false;
4305            final int packageCount = mPackages.size();
4306            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4307                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4308                SettingBase sb = (SettingBase) pkg.mExtras;
4309                if (sb == null) {
4310                    continue;
4311                }
4312                PermissionsState permissionsState = sb.getPermissionsState();
4313                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4314                        userId, flagMask, flagValues);
4315            }
4316            if (changed) {
4317                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4318            }
4319        }
4320    }
4321
4322    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4323        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4324                != PackageManager.PERMISSION_GRANTED
4325            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4326                != PackageManager.PERMISSION_GRANTED) {
4327            throw new SecurityException(message + " requires "
4328                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4329                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4330        }
4331    }
4332
4333    @Override
4334    public boolean shouldShowRequestPermissionRationale(String permissionName,
4335            String packageName, int userId) {
4336        if (UserHandle.getCallingUserId() != userId) {
4337            mContext.enforceCallingPermission(
4338                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4339                    "canShowRequestPermissionRationale for user " + userId);
4340        }
4341
4342        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4343        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4344            return false;
4345        }
4346
4347        if (checkPermission(permissionName, packageName, userId)
4348                == PackageManager.PERMISSION_GRANTED) {
4349            return false;
4350        }
4351
4352        final int flags;
4353
4354        final long identity = Binder.clearCallingIdentity();
4355        try {
4356            flags = getPermissionFlags(permissionName,
4357                    packageName, userId);
4358        } finally {
4359            Binder.restoreCallingIdentity(identity);
4360        }
4361
4362        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4363                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4364                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4365
4366        if ((flags & fixedFlags) != 0) {
4367            return false;
4368        }
4369
4370        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4371    }
4372
4373    @Override
4374    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4375        mContext.enforceCallingOrSelfPermission(
4376                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4377                "addOnPermissionsChangeListener");
4378
4379        synchronized (mPackages) {
4380            mOnPermissionChangeListeners.addListenerLocked(listener);
4381        }
4382    }
4383
4384    @Override
4385    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4386        synchronized (mPackages) {
4387            mOnPermissionChangeListeners.removeListenerLocked(listener);
4388        }
4389    }
4390
4391    @Override
4392    public boolean isProtectedBroadcast(String actionName) {
4393        synchronized (mPackages) {
4394            if (mProtectedBroadcasts.contains(actionName)) {
4395                return true;
4396            } else if (actionName != null) {
4397                // TODO: remove these terrible hacks
4398                if (actionName.startsWith("android.net.netmon.lingerExpired")
4399                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4400                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4401                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4402                    return true;
4403                }
4404            }
4405        }
4406        return false;
4407    }
4408
4409    @Override
4410    public int checkSignatures(String pkg1, String pkg2) {
4411        synchronized (mPackages) {
4412            final PackageParser.Package p1 = mPackages.get(pkg1);
4413            final PackageParser.Package p2 = mPackages.get(pkg2);
4414            if (p1 == null || p1.mExtras == null
4415                    || p2 == null || p2.mExtras == null) {
4416                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4417            }
4418            return compareSignatures(p1.mSignatures, p2.mSignatures);
4419        }
4420    }
4421
4422    @Override
4423    public int checkUidSignatures(int uid1, int uid2) {
4424        // Map to base uids.
4425        uid1 = UserHandle.getAppId(uid1);
4426        uid2 = UserHandle.getAppId(uid2);
4427        // reader
4428        synchronized (mPackages) {
4429            Signature[] s1;
4430            Signature[] s2;
4431            Object obj = mSettings.getUserIdLPr(uid1);
4432            if (obj != null) {
4433                if (obj instanceof SharedUserSetting) {
4434                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4435                } else if (obj instanceof PackageSetting) {
4436                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4437                } else {
4438                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4439                }
4440            } else {
4441                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4442            }
4443            obj = mSettings.getUserIdLPr(uid2);
4444            if (obj != null) {
4445                if (obj instanceof SharedUserSetting) {
4446                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4447                } else if (obj instanceof PackageSetting) {
4448                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4449                } else {
4450                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4451                }
4452            } else {
4453                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4454            }
4455            return compareSignatures(s1, s2);
4456        }
4457    }
4458
4459    /**
4460     * This method should typically only be used when granting or revoking
4461     * permissions, since the app may immediately restart after this call.
4462     * <p>
4463     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4464     * guard your work against the app being relaunched.
4465     */
4466    private void killUid(int appId, int userId, String reason) {
4467        final long identity = Binder.clearCallingIdentity();
4468        try {
4469            IActivityManager am = ActivityManagerNative.getDefault();
4470            if (am != null) {
4471                try {
4472                    am.killUid(appId, userId, reason);
4473                } catch (RemoteException e) {
4474                    /* ignore - same process */
4475                }
4476            }
4477        } finally {
4478            Binder.restoreCallingIdentity(identity);
4479        }
4480    }
4481
4482    /**
4483     * Compares two sets of signatures. Returns:
4484     * <br />
4485     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4486     * <br />
4487     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4488     * <br />
4489     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4490     * <br />
4491     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4492     * <br />
4493     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4494     */
4495    static int compareSignatures(Signature[] s1, Signature[] s2) {
4496        if (s1 == null) {
4497            return s2 == null
4498                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4499                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4500        }
4501
4502        if (s2 == null) {
4503            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4504        }
4505
4506        if (s1.length != s2.length) {
4507            return PackageManager.SIGNATURE_NO_MATCH;
4508        }
4509
4510        // Since both signature sets are of size 1, we can compare without HashSets.
4511        if (s1.length == 1) {
4512            return s1[0].equals(s2[0]) ?
4513                    PackageManager.SIGNATURE_MATCH :
4514                    PackageManager.SIGNATURE_NO_MATCH;
4515        }
4516
4517        ArraySet<Signature> set1 = new ArraySet<Signature>();
4518        for (Signature sig : s1) {
4519            set1.add(sig);
4520        }
4521        ArraySet<Signature> set2 = new ArraySet<Signature>();
4522        for (Signature sig : s2) {
4523            set2.add(sig);
4524        }
4525        // Make sure s2 contains all signatures in s1.
4526        if (set1.equals(set2)) {
4527            return PackageManager.SIGNATURE_MATCH;
4528        }
4529        return PackageManager.SIGNATURE_NO_MATCH;
4530    }
4531
4532    /**
4533     * If the database version for this type of package (internal storage or
4534     * external storage) is less than the version where package signatures
4535     * were updated, return true.
4536     */
4537    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4538        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4539        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4540    }
4541
4542    /**
4543     * Used for backward compatibility to make sure any packages with
4544     * certificate chains get upgraded to the new style. {@code existingSigs}
4545     * will be in the old format (since they were stored on disk from before the
4546     * system upgrade) and {@code scannedSigs} will be in the newer format.
4547     */
4548    private int compareSignaturesCompat(PackageSignatures existingSigs,
4549            PackageParser.Package scannedPkg) {
4550        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4551            return PackageManager.SIGNATURE_NO_MATCH;
4552        }
4553
4554        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4555        for (Signature sig : existingSigs.mSignatures) {
4556            existingSet.add(sig);
4557        }
4558        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4559        for (Signature sig : scannedPkg.mSignatures) {
4560            try {
4561                Signature[] chainSignatures = sig.getChainSignatures();
4562                for (Signature chainSig : chainSignatures) {
4563                    scannedCompatSet.add(chainSig);
4564                }
4565            } catch (CertificateEncodingException e) {
4566                scannedCompatSet.add(sig);
4567            }
4568        }
4569        /*
4570         * Make sure the expanded scanned set contains all signatures in the
4571         * existing one.
4572         */
4573        if (scannedCompatSet.equals(existingSet)) {
4574            // Migrate the old signatures to the new scheme.
4575            existingSigs.assignSignatures(scannedPkg.mSignatures);
4576            // The new KeySets will be re-added later in the scanning process.
4577            synchronized (mPackages) {
4578                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4579            }
4580            return PackageManager.SIGNATURE_MATCH;
4581        }
4582        return PackageManager.SIGNATURE_NO_MATCH;
4583    }
4584
4585    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4586        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4587        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4588    }
4589
4590    private int compareSignaturesRecover(PackageSignatures existingSigs,
4591            PackageParser.Package scannedPkg) {
4592        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4593            return PackageManager.SIGNATURE_NO_MATCH;
4594        }
4595
4596        String msg = null;
4597        try {
4598            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4599                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4600                        + scannedPkg.packageName);
4601                return PackageManager.SIGNATURE_MATCH;
4602            }
4603        } catch (CertificateException e) {
4604            msg = e.getMessage();
4605        }
4606
4607        logCriticalInfo(Log.INFO,
4608                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4609        return PackageManager.SIGNATURE_NO_MATCH;
4610    }
4611
4612    @Override
4613    public List<String> getAllPackages() {
4614        synchronized (mPackages) {
4615            return new ArrayList<String>(mPackages.keySet());
4616        }
4617    }
4618
4619    @Override
4620    public String[] getPackagesForUid(int uid) {
4621        uid = UserHandle.getAppId(uid);
4622        // reader
4623        synchronized (mPackages) {
4624            Object obj = mSettings.getUserIdLPr(uid);
4625            if (obj instanceof SharedUserSetting) {
4626                final SharedUserSetting sus = (SharedUserSetting) obj;
4627                final int N = sus.packages.size();
4628                final String[] res = new String[N];
4629                for (int i = 0; i < N; i++) {
4630                    res[i] = sus.packages.valueAt(i).name;
4631                }
4632                return res;
4633            } else if (obj instanceof PackageSetting) {
4634                final PackageSetting ps = (PackageSetting) obj;
4635                return new String[] { ps.name };
4636            }
4637        }
4638        return null;
4639    }
4640
4641    @Override
4642    public String getNameForUid(int uid) {
4643        // reader
4644        synchronized (mPackages) {
4645            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4646            if (obj instanceof SharedUserSetting) {
4647                final SharedUserSetting sus = (SharedUserSetting) obj;
4648                return sus.name + ":" + sus.userId;
4649            } else if (obj instanceof PackageSetting) {
4650                final PackageSetting ps = (PackageSetting) obj;
4651                return ps.name;
4652            }
4653        }
4654        return null;
4655    }
4656
4657    @Override
4658    public int getUidForSharedUser(String sharedUserName) {
4659        if(sharedUserName == null) {
4660            return -1;
4661        }
4662        // reader
4663        synchronized (mPackages) {
4664            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4665            if (suid == null) {
4666                return -1;
4667            }
4668            return suid.userId;
4669        }
4670    }
4671
4672    @Override
4673    public int getFlagsForUid(int uid) {
4674        synchronized (mPackages) {
4675            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4676            if (obj instanceof SharedUserSetting) {
4677                final SharedUserSetting sus = (SharedUserSetting) obj;
4678                return sus.pkgFlags;
4679            } else if (obj instanceof PackageSetting) {
4680                final PackageSetting ps = (PackageSetting) obj;
4681                return ps.pkgFlags;
4682            }
4683        }
4684        return 0;
4685    }
4686
4687    @Override
4688    public int getPrivateFlagsForUid(int uid) {
4689        synchronized (mPackages) {
4690            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4691            if (obj instanceof SharedUserSetting) {
4692                final SharedUserSetting sus = (SharedUserSetting) obj;
4693                return sus.pkgPrivateFlags;
4694            } else if (obj instanceof PackageSetting) {
4695                final PackageSetting ps = (PackageSetting) obj;
4696                return ps.pkgPrivateFlags;
4697            }
4698        }
4699        return 0;
4700    }
4701
4702    @Override
4703    public boolean isUidPrivileged(int uid) {
4704        uid = UserHandle.getAppId(uid);
4705        // reader
4706        synchronized (mPackages) {
4707            Object obj = mSettings.getUserIdLPr(uid);
4708            if (obj instanceof SharedUserSetting) {
4709                final SharedUserSetting sus = (SharedUserSetting) obj;
4710                final Iterator<PackageSetting> it = sus.packages.iterator();
4711                while (it.hasNext()) {
4712                    if (it.next().isPrivileged()) {
4713                        return true;
4714                    }
4715                }
4716            } else if (obj instanceof PackageSetting) {
4717                final PackageSetting ps = (PackageSetting) obj;
4718                return ps.isPrivileged();
4719            }
4720        }
4721        return false;
4722    }
4723
4724    @Override
4725    public String[] getAppOpPermissionPackages(String permissionName) {
4726        synchronized (mPackages) {
4727            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4728            if (pkgs == null) {
4729                return null;
4730            }
4731            return pkgs.toArray(new String[pkgs.size()]);
4732        }
4733    }
4734
4735    @Override
4736    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4737            int flags, int userId) {
4738        try {
4739            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4740
4741            if (!sUserManager.exists(userId)) return null;
4742            flags = updateFlagsForResolve(flags, userId, intent);
4743            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4744                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4745
4746            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4747            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4748                    flags, userId);
4749            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4750
4751            final ResolveInfo bestChoice =
4752                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4753            return bestChoice;
4754        } finally {
4755            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4756        }
4757    }
4758
4759    @Override
4760    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4761            IntentFilter filter, int match, ComponentName activity) {
4762        final int userId = UserHandle.getCallingUserId();
4763        if (DEBUG_PREFERRED) {
4764            Log.v(TAG, "setLastChosenActivity intent=" + intent
4765                + " resolvedType=" + resolvedType
4766                + " flags=" + flags
4767                + " filter=" + filter
4768                + " match=" + match
4769                + " activity=" + activity);
4770            filter.dump(new PrintStreamPrinter(System.out), "    ");
4771        }
4772        intent.setComponent(null);
4773        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4774                userId);
4775        // Find any earlier preferred or last chosen entries and nuke them
4776        findPreferredActivity(intent, resolvedType,
4777                flags, query, 0, false, true, false, userId);
4778        // Add the new activity as the last chosen for this filter
4779        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4780                "Setting last chosen");
4781    }
4782
4783    @Override
4784    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4785        final int userId = UserHandle.getCallingUserId();
4786        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4787        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4788                userId);
4789        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4790                false, false, false, userId);
4791    }
4792
4793    private boolean isEphemeralDisabled() {
4794        // ephemeral apps have been disabled across the board
4795        if (DISABLE_EPHEMERAL_APPS) {
4796            return true;
4797        }
4798        // system isn't up yet; can't read settings, so, assume no ephemeral apps
4799        if (!mSystemReady) {
4800            return true;
4801        }
4802        return Secure.getInt(mContext.getContentResolver(), Secure.WEB_ACTION_ENABLED, 1) == 0;
4803    }
4804
4805    private boolean isEphemeralAllowed(
4806            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4807            boolean skipPackageCheck) {
4808        // Short circuit and return early if possible.
4809        if (isEphemeralDisabled()) {
4810            return false;
4811        }
4812        final int callingUser = UserHandle.getCallingUserId();
4813        if (callingUser != UserHandle.USER_SYSTEM) {
4814            return false;
4815        }
4816        if (mEphemeralResolverConnection == null) {
4817            return false;
4818        }
4819        if (intent.getComponent() != null) {
4820            return false;
4821        }
4822        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4823            return false;
4824        }
4825        if (!skipPackageCheck && intent.getPackage() != null) {
4826            return false;
4827        }
4828        final boolean isWebUri = hasWebURI(intent);
4829        if (!isWebUri || intent.getData().getHost() == null) {
4830            return false;
4831        }
4832        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4833        synchronized (mPackages) {
4834            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4835            for (int n = 0; n < count; n++) {
4836                ResolveInfo info = resolvedActivities.get(n);
4837                String packageName = info.activityInfo.packageName;
4838                PackageSetting ps = mSettings.mPackages.get(packageName);
4839                if (ps != null) {
4840                    // Try to get the status from User settings first
4841                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4842                    int status = (int) (packedStatus >> 32);
4843                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4844                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4845                        if (DEBUG_EPHEMERAL) {
4846                            Slog.v(TAG, "DENY ephemeral apps;"
4847                                + " pkg: " + packageName + ", status: " + status);
4848                        }
4849                        return false;
4850                    }
4851                }
4852            }
4853        }
4854        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4855        return true;
4856    }
4857
4858    private static EphemeralResolveInfo getEphemeralResolveInfo(
4859            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4860            String resolvedType, int userId, String packageName) {
4861        final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4862                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4863        final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4864                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4865        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4866                ephemeralPrefixCount);
4867        final int[] shaPrefix = digest.getDigestPrefix();
4868        final byte[][] digestBytes = digest.getDigestBytes();
4869        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4870                resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4871        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4872            // No hash prefix match; there are no ephemeral apps for this domain.
4873            return null;
4874        }
4875
4876        // Go in reverse order so we match the narrowest scope first.
4877        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4878            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4879                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4880                    continue;
4881                }
4882                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4883                // No filters; this should never happen.
4884                if (filters.isEmpty()) {
4885                    continue;
4886                }
4887                if (packageName != null
4888                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4889                    continue;
4890                }
4891                // We have a domain match; resolve the filters to see if anything matches.
4892                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4893                for (int j = filters.size() - 1; j >= 0; --j) {
4894                    final EphemeralResolveIntentInfo intentInfo =
4895                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4896                    ephemeralResolver.addFilter(intentInfo);
4897                }
4898                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4899                        intent, resolvedType, false /*defaultOnly*/, userId);
4900                if (!matchedResolveInfoList.isEmpty()) {
4901                    return matchedResolveInfoList.get(0);
4902                }
4903            }
4904        }
4905        // Hash or filter mis-match; no ephemeral apps for this domain.
4906        return null;
4907    }
4908
4909    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4910            int flags, List<ResolveInfo> query, int userId) {
4911        if (query != null) {
4912            final int N = query.size();
4913            if (N == 1) {
4914                return query.get(0);
4915            } else if (N > 1) {
4916                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4917                // If there is more than one activity with the same priority,
4918                // then let the user decide between them.
4919                ResolveInfo r0 = query.get(0);
4920                ResolveInfo r1 = query.get(1);
4921                if (DEBUG_INTENT_MATCHING || debug) {
4922                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4923                            + r1.activityInfo.name + "=" + r1.priority);
4924                }
4925                // If the first activity has a higher priority, or a different
4926                // default, then it is always desirable to pick it.
4927                if (r0.priority != r1.priority
4928                        || r0.preferredOrder != r1.preferredOrder
4929                        || r0.isDefault != r1.isDefault) {
4930                    return query.get(0);
4931                }
4932                // If we have saved a preference for a preferred activity for
4933                // this Intent, use that.
4934                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4935                        flags, query, r0.priority, true, false, debug, userId);
4936                if (ri != null) {
4937                    return ri;
4938                }
4939                ri = new ResolveInfo(mResolveInfo);
4940                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4941                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4942                // If all of the options come from the same package, show the application's
4943                // label and icon instead of the generic resolver's.
4944                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
4945                // and then throw away the ResolveInfo itself, meaning that the caller loses
4946                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
4947                // a fallback for this case; we only set the target package's resources on
4948                // the ResolveInfo, not the ActivityInfo.
4949                final String intentPackage = intent.getPackage();
4950                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
4951                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
4952                    ri.resolvePackageName = intentPackage;
4953                    if (userNeedsBadging(userId)) {
4954                        ri.noResourceId = true;
4955                    } else {
4956                        ri.icon = appi.icon;
4957                    }
4958                    ri.iconResourceId = appi.icon;
4959                    ri.labelRes = appi.labelRes;
4960                }
4961                ri.activityInfo.applicationInfo = new ApplicationInfo(
4962                        ri.activityInfo.applicationInfo);
4963                if (userId != 0) {
4964                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4965                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4966                }
4967                // Make sure that the resolver is displayable in car mode
4968                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4969                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4970                return ri;
4971            }
4972        }
4973        return null;
4974    }
4975
4976    /**
4977     * Return true if the given list is not empty and all of its contents have
4978     * an activityInfo with the given package name.
4979     */
4980    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
4981        if (ArrayUtils.isEmpty(list)) {
4982            return false;
4983        }
4984        for (int i = 0, N = list.size(); i < N; i++) {
4985            final ResolveInfo ri = list.get(i);
4986            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
4987            if (ai == null || !packageName.equals(ai.packageName)) {
4988                return false;
4989            }
4990        }
4991        return true;
4992    }
4993
4994    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4995            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4996        final int N = query.size();
4997        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4998                .get(userId);
4999        // Get the list of persistent preferred activities that handle the intent
5000        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5001        List<PersistentPreferredActivity> pprefs = ppir != null
5002                ? ppir.queryIntent(intent, resolvedType,
5003                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5004                : null;
5005        if (pprefs != null && pprefs.size() > 0) {
5006            final int M = pprefs.size();
5007            for (int i=0; i<M; i++) {
5008                final PersistentPreferredActivity ppa = pprefs.get(i);
5009                if (DEBUG_PREFERRED || debug) {
5010                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5011                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5012                            + "\n  component=" + ppa.mComponent);
5013                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5014                }
5015                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5016                        flags | MATCH_DISABLED_COMPONENTS, userId);
5017                if (DEBUG_PREFERRED || debug) {
5018                    Slog.v(TAG, "Found persistent preferred activity:");
5019                    if (ai != null) {
5020                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5021                    } else {
5022                        Slog.v(TAG, "  null");
5023                    }
5024                }
5025                if (ai == null) {
5026                    // This previously registered persistent preferred activity
5027                    // component is no longer known. Ignore it and do NOT remove it.
5028                    continue;
5029                }
5030                for (int j=0; j<N; j++) {
5031                    final ResolveInfo ri = query.get(j);
5032                    if (!ri.activityInfo.applicationInfo.packageName
5033                            .equals(ai.applicationInfo.packageName)) {
5034                        continue;
5035                    }
5036                    if (!ri.activityInfo.name.equals(ai.name)) {
5037                        continue;
5038                    }
5039                    //  Found a persistent preference that can handle the intent.
5040                    if (DEBUG_PREFERRED || debug) {
5041                        Slog.v(TAG, "Returning persistent preferred activity: " +
5042                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5043                    }
5044                    return ri;
5045                }
5046            }
5047        }
5048        return null;
5049    }
5050
5051    // TODO: handle preferred activities missing while user has amnesia
5052    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5053            List<ResolveInfo> query, int priority, boolean always,
5054            boolean removeMatches, boolean debug, int userId) {
5055        if (!sUserManager.exists(userId)) return null;
5056        flags = updateFlagsForResolve(flags, userId, intent);
5057        // writer
5058        synchronized (mPackages) {
5059            if (intent.getSelector() != null) {
5060                intent = intent.getSelector();
5061            }
5062            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5063
5064            // Try to find a matching persistent preferred activity.
5065            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5066                    debug, userId);
5067
5068            // If a persistent preferred activity matched, use it.
5069            if (pri != null) {
5070                return pri;
5071            }
5072
5073            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5074            // Get the list of preferred activities that handle the intent
5075            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5076            List<PreferredActivity> prefs = pir != null
5077                    ? pir.queryIntent(intent, resolvedType,
5078                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5079                    : null;
5080            if (prefs != null && prefs.size() > 0) {
5081                boolean changed = false;
5082                try {
5083                    // First figure out how good the original match set is.
5084                    // We will only allow preferred activities that came
5085                    // from the same match quality.
5086                    int match = 0;
5087
5088                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5089
5090                    final int N = query.size();
5091                    for (int j=0; j<N; j++) {
5092                        final ResolveInfo ri = query.get(j);
5093                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5094                                + ": 0x" + Integer.toHexString(match));
5095                        if (ri.match > match) {
5096                            match = ri.match;
5097                        }
5098                    }
5099
5100                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5101                            + Integer.toHexString(match));
5102
5103                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5104                    final int M = prefs.size();
5105                    for (int i=0; i<M; i++) {
5106                        final PreferredActivity pa = prefs.get(i);
5107                        if (DEBUG_PREFERRED || debug) {
5108                            Slog.v(TAG, "Checking PreferredActivity ds="
5109                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5110                                    + "\n  component=" + pa.mPref.mComponent);
5111                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5112                        }
5113                        if (pa.mPref.mMatch != match) {
5114                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5115                                    + Integer.toHexString(pa.mPref.mMatch));
5116                            continue;
5117                        }
5118                        // If it's not an "always" type preferred activity and that's what we're
5119                        // looking for, skip it.
5120                        if (always && !pa.mPref.mAlways) {
5121                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5122                            continue;
5123                        }
5124                        final ActivityInfo ai = getActivityInfo(
5125                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5126                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5127                                userId);
5128                        if (DEBUG_PREFERRED || debug) {
5129                            Slog.v(TAG, "Found preferred activity:");
5130                            if (ai != null) {
5131                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5132                            } else {
5133                                Slog.v(TAG, "  null");
5134                            }
5135                        }
5136                        if (ai == null) {
5137                            // This previously registered preferred activity
5138                            // component is no longer known.  Most likely an update
5139                            // to the app was installed and in the new version this
5140                            // component no longer exists.  Clean it up by removing
5141                            // it from the preferred activities list, and skip it.
5142                            Slog.w(TAG, "Removing dangling preferred activity: "
5143                                    + pa.mPref.mComponent);
5144                            pir.removeFilter(pa);
5145                            changed = true;
5146                            continue;
5147                        }
5148                        for (int j=0; j<N; j++) {
5149                            final ResolveInfo ri = query.get(j);
5150                            if (!ri.activityInfo.applicationInfo.packageName
5151                                    .equals(ai.applicationInfo.packageName)) {
5152                                continue;
5153                            }
5154                            if (!ri.activityInfo.name.equals(ai.name)) {
5155                                continue;
5156                            }
5157
5158                            if (removeMatches) {
5159                                pir.removeFilter(pa);
5160                                changed = true;
5161                                if (DEBUG_PREFERRED) {
5162                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5163                                }
5164                                break;
5165                            }
5166
5167                            // Okay we found a previously set preferred or last chosen app.
5168                            // If the result set is different from when this
5169                            // was created, we need to clear it and re-ask the
5170                            // user their preference, if we're looking for an "always" type entry.
5171                            if (always && !pa.mPref.sameSet(query)) {
5172                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5173                                        + intent + " type " + resolvedType);
5174                                if (DEBUG_PREFERRED) {
5175                                    Slog.v(TAG, "Removing preferred activity since set changed "
5176                                            + pa.mPref.mComponent);
5177                                }
5178                                pir.removeFilter(pa);
5179                                // Re-add the filter as a "last chosen" entry (!always)
5180                                PreferredActivity lastChosen = new PreferredActivity(
5181                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5182                                pir.addFilter(lastChosen);
5183                                changed = true;
5184                                return null;
5185                            }
5186
5187                            // Yay! Either the set matched or we're looking for the last chosen
5188                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5189                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5190                            return ri;
5191                        }
5192                    }
5193                } finally {
5194                    if (changed) {
5195                        if (DEBUG_PREFERRED) {
5196                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5197                        }
5198                        scheduleWritePackageRestrictionsLocked(userId);
5199                    }
5200                }
5201            }
5202        }
5203        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5204        return null;
5205    }
5206
5207    /*
5208     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5209     */
5210    @Override
5211    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5212            int targetUserId) {
5213        mContext.enforceCallingOrSelfPermission(
5214                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5215        List<CrossProfileIntentFilter> matches =
5216                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5217        if (matches != null) {
5218            int size = matches.size();
5219            for (int i = 0; i < size; i++) {
5220                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5221            }
5222        }
5223        if (hasWebURI(intent)) {
5224            // cross-profile app linking works only towards the parent.
5225            final UserInfo parent = getProfileParent(sourceUserId);
5226            synchronized(mPackages) {
5227                int flags = updateFlagsForResolve(0, parent.id, intent);
5228                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5229                        intent, resolvedType, flags, sourceUserId, parent.id);
5230                return xpDomainInfo != null;
5231            }
5232        }
5233        return false;
5234    }
5235
5236    private UserInfo getProfileParent(int userId) {
5237        final long identity = Binder.clearCallingIdentity();
5238        try {
5239            return sUserManager.getProfileParent(userId);
5240        } finally {
5241            Binder.restoreCallingIdentity(identity);
5242        }
5243    }
5244
5245    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5246            String resolvedType, int userId) {
5247        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5248        if (resolver != null) {
5249            return resolver.queryIntent(intent, resolvedType, false, userId);
5250        }
5251        return null;
5252    }
5253
5254    @Override
5255    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5256            String resolvedType, int flags, int userId) {
5257        try {
5258            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5259
5260            return new ParceledListSlice<>(
5261                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5262        } finally {
5263            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5264        }
5265    }
5266
5267    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5268            String resolvedType, int flags, int userId) {
5269        if (!sUserManager.exists(userId)) return Collections.emptyList();
5270        flags = updateFlagsForResolve(flags, userId, intent);
5271        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5272                false /* requireFullPermission */, false /* checkShell */,
5273                "query intent activities");
5274        ComponentName comp = intent.getComponent();
5275        if (comp == null) {
5276            if (intent.getSelector() != null) {
5277                intent = intent.getSelector();
5278                comp = intent.getComponent();
5279            }
5280        }
5281
5282        if (comp != null) {
5283            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5284            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5285            if (ai != null) {
5286                final ResolveInfo ri = new ResolveInfo();
5287                ri.activityInfo = ai;
5288                list.add(ri);
5289            }
5290            return list;
5291        }
5292
5293        // reader
5294        boolean sortResult = false;
5295        boolean addEphemeral = false;
5296        boolean matchEphemeralPackage = false;
5297        List<ResolveInfo> result;
5298        final String pkgName = intent.getPackage();
5299        synchronized (mPackages) {
5300            if (pkgName == null) {
5301                List<CrossProfileIntentFilter> matchingFilters =
5302                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5303                // Check for results that need to skip the current profile.
5304                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5305                        resolvedType, flags, userId);
5306                if (xpResolveInfo != null) {
5307                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5308                    xpResult.add(xpResolveInfo);
5309                    return filterIfNotSystemUser(xpResult, userId);
5310                }
5311
5312                // Check for results in the current profile.
5313                result = filterIfNotSystemUser(mActivities.queryIntent(
5314                        intent, resolvedType, flags, userId), userId);
5315                addEphemeral =
5316                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5317
5318                // Check for cross profile results.
5319                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5320                xpResolveInfo = queryCrossProfileIntents(
5321                        matchingFilters, intent, resolvedType, flags, userId,
5322                        hasNonNegativePriorityResult);
5323                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5324                    boolean isVisibleToUser = filterIfNotSystemUser(
5325                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5326                    if (isVisibleToUser) {
5327                        result.add(xpResolveInfo);
5328                        sortResult = true;
5329                    }
5330                }
5331                if (hasWebURI(intent)) {
5332                    CrossProfileDomainInfo xpDomainInfo = null;
5333                    final UserInfo parent = getProfileParent(userId);
5334                    if (parent != null) {
5335                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5336                                flags, userId, parent.id);
5337                    }
5338                    if (xpDomainInfo != null) {
5339                        if (xpResolveInfo != null) {
5340                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5341                            // in the result.
5342                            result.remove(xpResolveInfo);
5343                        }
5344                        if (result.size() == 0 && !addEphemeral) {
5345                            result.add(xpDomainInfo.resolveInfo);
5346                            return result;
5347                        }
5348                    }
5349                    if (result.size() > 1 || addEphemeral) {
5350                        result = filterCandidatesWithDomainPreferredActivitiesLPr(
5351                                intent, flags, result, xpDomainInfo, userId);
5352                        sortResult = true;
5353                    }
5354                }
5355            } else {
5356                final PackageParser.Package pkg = mPackages.get(pkgName);
5357                if (pkg != null) {
5358                    result = filterIfNotSystemUser(
5359                            mActivities.queryIntentForPackage(
5360                                    intent, resolvedType, flags, pkg.activities, userId),
5361                            userId);
5362                } else {
5363                    // the caller wants to resolve for a particular package; however, there
5364                    // were no installed results, so, try to find an ephemeral result
5365                    addEphemeral = isEphemeralAllowed(
5366                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5367                    matchEphemeralPackage = true;
5368                    result = new ArrayList<ResolveInfo>();
5369                }
5370            }
5371        }
5372        if (addEphemeral) {
5373            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5374            final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5375                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5376                    matchEphemeralPackage ? pkgName : null);
5377            if (ai != null) {
5378                if (DEBUG_EPHEMERAL) {
5379                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5380                }
5381                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5382                ephemeralInstaller.ephemeralResolveInfo = ai;
5383                // make sure this resolver is the default
5384                ephemeralInstaller.isDefault = true;
5385                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5386                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5387                // add a non-generic filter
5388                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5389                ephemeralInstaller.filter.addDataPath(
5390                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5391                result.add(ephemeralInstaller);
5392            }
5393            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5394        }
5395        if (sortResult) {
5396            Collections.sort(result, mResolvePrioritySorter);
5397        }
5398        return result;
5399    }
5400
5401    private static class CrossProfileDomainInfo {
5402        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5403        ResolveInfo resolveInfo;
5404        /* Best domain verification status of the activities found in the other profile */
5405        int bestDomainVerificationStatus;
5406    }
5407
5408    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5409            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5410        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5411                sourceUserId)) {
5412            return null;
5413        }
5414        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5415                resolvedType, flags, parentUserId);
5416
5417        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5418            return null;
5419        }
5420        CrossProfileDomainInfo result = null;
5421        int size = resultTargetUser.size();
5422        for (int i = 0; i < size; i++) {
5423            ResolveInfo riTargetUser = resultTargetUser.get(i);
5424            // Intent filter verification is only for filters that specify a host. So don't return
5425            // those that handle all web uris.
5426            if (riTargetUser.handleAllWebDataURI) {
5427                continue;
5428            }
5429            String packageName = riTargetUser.activityInfo.packageName;
5430            PackageSetting ps = mSettings.mPackages.get(packageName);
5431            if (ps == null) {
5432                continue;
5433            }
5434            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5435            int status = (int)(verificationState >> 32);
5436            if (result == null) {
5437                result = new CrossProfileDomainInfo();
5438                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5439                        sourceUserId, parentUserId);
5440                result.bestDomainVerificationStatus = status;
5441            } else {
5442                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5443                        result.bestDomainVerificationStatus);
5444            }
5445        }
5446        // Don't consider matches with status NEVER across profiles.
5447        if (result != null && result.bestDomainVerificationStatus
5448                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5449            return null;
5450        }
5451        return result;
5452    }
5453
5454    /**
5455     * Verification statuses are ordered from the worse to the best, except for
5456     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5457     */
5458    private int bestDomainVerificationStatus(int status1, int status2) {
5459        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5460            return status2;
5461        }
5462        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5463            return status1;
5464        }
5465        return (int) MathUtils.max(status1, status2);
5466    }
5467
5468    private boolean isUserEnabled(int userId) {
5469        long callingId = Binder.clearCallingIdentity();
5470        try {
5471            UserInfo userInfo = sUserManager.getUserInfo(userId);
5472            return userInfo != null && userInfo.isEnabled();
5473        } finally {
5474            Binder.restoreCallingIdentity(callingId);
5475        }
5476    }
5477
5478    /**
5479     * Filter out activities with systemUserOnly flag set, when current user is not System.
5480     *
5481     * @return filtered list
5482     */
5483    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5484        if (userId == UserHandle.USER_SYSTEM) {
5485            return resolveInfos;
5486        }
5487        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5488            ResolveInfo info = resolveInfos.get(i);
5489            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5490                resolveInfos.remove(i);
5491            }
5492        }
5493        return resolveInfos;
5494    }
5495
5496    /**
5497     * @param resolveInfos list of resolve infos in descending priority order
5498     * @return if the list contains a resolve info with non-negative priority
5499     */
5500    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5501        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5502    }
5503
5504    private static boolean hasWebURI(Intent intent) {
5505        if (intent.getData() == null) {
5506            return false;
5507        }
5508        final String scheme = intent.getScheme();
5509        if (TextUtils.isEmpty(scheme)) {
5510            return false;
5511        }
5512        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5513    }
5514
5515    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5516            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5517            int userId) {
5518        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5519
5520        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5521            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5522                    candidates.size());
5523        }
5524
5525        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5526        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5527        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5528        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5529        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5530        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5531
5532        synchronized (mPackages) {
5533            final int count = candidates.size();
5534            // First, try to use linked apps. Partition the candidates into four lists:
5535            // one for the final results, one for the "do not use ever", one for "undefined status"
5536            // and finally one for "browser app type".
5537            for (int n=0; n<count; n++) {
5538                ResolveInfo info = candidates.get(n);
5539                String packageName = info.activityInfo.packageName;
5540                PackageSetting ps = mSettings.mPackages.get(packageName);
5541                if (ps != null) {
5542                    // Add to the special match all list (Browser use case)
5543                    if (info.handleAllWebDataURI) {
5544                        matchAllList.add(info);
5545                        continue;
5546                    }
5547                    // Try to get the status from User settings first
5548                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5549                    int status = (int)(packedStatus >> 32);
5550                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5551                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5552                        if (DEBUG_DOMAIN_VERIFICATION) {
5553                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5554                                    + " : linkgen=" + linkGeneration);
5555                        }
5556                        // Use link-enabled generation as preferredOrder, i.e.
5557                        // prefer newly-enabled over earlier-enabled.
5558                        info.preferredOrder = linkGeneration;
5559                        alwaysList.add(info);
5560                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5561                        if (DEBUG_DOMAIN_VERIFICATION) {
5562                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5563                        }
5564                        neverList.add(info);
5565                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5566                        if (DEBUG_DOMAIN_VERIFICATION) {
5567                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5568                        }
5569                        alwaysAskList.add(info);
5570                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5571                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5572                        if (DEBUG_DOMAIN_VERIFICATION) {
5573                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5574                        }
5575                        undefinedList.add(info);
5576                    }
5577                }
5578            }
5579
5580            // We'll want to include browser possibilities in a few cases
5581            boolean includeBrowser = false;
5582
5583            // First try to add the "always" resolution(s) for the current user, if any
5584            if (alwaysList.size() > 0) {
5585                result.addAll(alwaysList);
5586            } else {
5587                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5588                result.addAll(undefinedList);
5589                // Maybe add one for the other profile.
5590                if (xpDomainInfo != null && (
5591                        xpDomainInfo.bestDomainVerificationStatus
5592                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5593                    result.add(xpDomainInfo.resolveInfo);
5594                }
5595                includeBrowser = true;
5596            }
5597
5598            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5599            // If there were 'always' entries their preferred order has been set, so we also
5600            // back that off to make the alternatives equivalent
5601            if (alwaysAskList.size() > 0) {
5602                for (ResolveInfo i : result) {
5603                    i.preferredOrder = 0;
5604                }
5605                result.addAll(alwaysAskList);
5606                includeBrowser = true;
5607            }
5608
5609            if (includeBrowser) {
5610                // Also add browsers (all of them or only the default one)
5611                if (DEBUG_DOMAIN_VERIFICATION) {
5612                    Slog.v(TAG, "   ...including browsers in candidate set");
5613                }
5614                if ((matchFlags & MATCH_ALL) != 0) {
5615                    result.addAll(matchAllList);
5616                } else {
5617                    // Browser/generic handling case.  If there's a default browser, go straight
5618                    // to that (but only if there is no other higher-priority match).
5619                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5620                    int maxMatchPrio = 0;
5621                    ResolveInfo defaultBrowserMatch = null;
5622                    final int numCandidates = matchAllList.size();
5623                    for (int n = 0; n < numCandidates; n++) {
5624                        ResolveInfo info = matchAllList.get(n);
5625                        // track the highest overall match priority...
5626                        if (info.priority > maxMatchPrio) {
5627                            maxMatchPrio = info.priority;
5628                        }
5629                        // ...and the highest-priority default browser match
5630                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5631                            if (defaultBrowserMatch == null
5632                                    || (defaultBrowserMatch.priority < info.priority)) {
5633                                if (debug) {
5634                                    Slog.v(TAG, "Considering default browser match " + info);
5635                                }
5636                                defaultBrowserMatch = info;
5637                            }
5638                        }
5639                    }
5640                    if (defaultBrowserMatch != null
5641                            && defaultBrowserMatch.priority >= maxMatchPrio
5642                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5643                    {
5644                        if (debug) {
5645                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5646                        }
5647                        result.add(defaultBrowserMatch);
5648                    } else {
5649                        result.addAll(matchAllList);
5650                    }
5651                }
5652
5653                // If there is nothing selected, add all candidates and remove the ones that the user
5654                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5655                if (result.size() == 0) {
5656                    result.addAll(candidates);
5657                    result.removeAll(neverList);
5658                }
5659            }
5660        }
5661        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5662            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5663                    result.size());
5664            for (ResolveInfo info : result) {
5665                Slog.v(TAG, "  + " + info.activityInfo);
5666            }
5667        }
5668        return result;
5669    }
5670
5671    // Returns a packed value as a long:
5672    //
5673    // high 'int'-sized word: link status: undefined/ask/never/always.
5674    // low 'int'-sized word: relative priority among 'always' results.
5675    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5676        long result = ps.getDomainVerificationStatusForUser(userId);
5677        // if none available, get the master status
5678        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5679            if (ps.getIntentFilterVerificationInfo() != null) {
5680                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5681            }
5682        }
5683        return result;
5684    }
5685
5686    private ResolveInfo querySkipCurrentProfileIntents(
5687            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5688            int flags, int sourceUserId) {
5689        if (matchingFilters != null) {
5690            int size = matchingFilters.size();
5691            for (int i = 0; i < size; i ++) {
5692                CrossProfileIntentFilter filter = matchingFilters.get(i);
5693                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5694                    // Checking if there are activities in the target user that can handle the
5695                    // intent.
5696                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5697                            resolvedType, flags, sourceUserId);
5698                    if (resolveInfo != null) {
5699                        return resolveInfo;
5700                    }
5701                }
5702            }
5703        }
5704        return null;
5705    }
5706
5707    // Return matching ResolveInfo in target user if any.
5708    private ResolveInfo queryCrossProfileIntents(
5709            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5710            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5711        if (matchingFilters != null) {
5712            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5713            // match the same intent. For performance reasons, it is better not to
5714            // run queryIntent twice for the same userId
5715            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5716            int size = matchingFilters.size();
5717            for (int i = 0; i < size; i++) {
5718                CrossProfileIntentFilter filter = matchingFilters.get(i);
5719                int targetUserId = filter.getTargetUserId();
5720                boolean skipCurrentProfile =
5721                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5722                boolean skipCurrentProfileIfNoMatchFound =
5723                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5724                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5725                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5726                    // Checking if there are activities in the target user that can handle the
5727                    // intent.
5728                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5729                            resolvedType, flags, sourceUserId);
5730                    if (resolveInfo != null) return resolveInfo;
5731                    alreadyTriedUserIds.put(targetUserId, true);
5732                }
5733            }
5734        }
5735        return null;
5736    }
5737
5738    /**
5739     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5740     * will forward the intent to the filter's target user.
5741     * Otherwise, returns null.
5742     */
5743    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5744            String resolvedType, int flags, int sourceUserId) {
5745        int targetUserId = filter.getTargetUserId();
5746        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5747                resolvedType, flags, targetUserId);
5748        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5749            // If all the matches in the target profile are suspended, return null.
5750            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5751                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5752                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5753                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5754                            targetUserId);
5755                }
5756            }
5757        }
5758        return null;
5759    }
5760
5761    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5762            int sourceUserId, int targetUserId) {
5763        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5764        long ident = Binder.clearCallingIdentity();
5765        boolean targetIsProfile;
5766        try {
5767            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5768        } finally {
5769            Binder.restoreCallingIdentity(ident);
5770        }
5771        String className;
5772        if (targetIsProfile) {
5773            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5774        } else {
5775            className = FORWARD_INTENT_TO_PARENT;
5776        }
5777        ComponentName forwardingActivityComponentName = new ComponentName(
5778                mAndroidApplication.packageName, className);
5779        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5780                sourceUserId);
5781        if (!targetIsProfile) {
5782            forwardingActivityInfo.showUserIcon = targetUserId;
5783            forwardingResolveInfo.noResourceId = true;
5784        }
5785        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5786        forwardingResolveInfo.priority = 0;
5787        forwardingResolveInfo.preferredOrder = 0;
5788        forwardingResolveInfo.match = 0;
5789        forwardingResolveInfo.isDefault = true;
5790        forwardingResolveInfo.filter = filter;
5791        forwardingResolveInfo.targetUserId = targetUserId;
5792        return forwardingResolveInfo;
5793    }
5794
5795    @Override
5796    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5797            Intent[] specifics, String[] specificTypes, Intent intent,
5798            String resolvedType, int flags, int userId) {
5799        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5800                specificTypes, intent, resolvedType, flags, userId));
5801    }
5802
5803    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5804            Intent[] specifics, String[] specificTypes, Intent intent,
5805            String resolvedType, int flags, int userId) {
5806        if (!sUserManager.exists(userId)) return Collections.emptyList();
5807        flags = updateFlagsForResolve(flags, userId, intent);
5808        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5809                false /* requireFullPermission */, false /* checkShell */,
5810                "query intent activity options");
5811        final String resultsAction = intent.getAction();
5812
5813        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5814                | PackageManager.GET_RESOLVED_FILTER, userId);
5815
5816        if (DEBUG_INTENT_MATCHING) {
5817            Log.v(TAG, "Query " + intent + ": " + results);
5818        }
5819
5820        int specificsPos = 0;
5821        int N;
5822
5823        // todo: note that the algorithm used here is O(N^2).  This
5824        // isn't a problem in our current environment, but if we start running
5825        // into situations where we have more than 5 or 10 matches then this
5826        // should probably be changed to something smarter...
5827
5828        // First we go through and resolve each of the specific items
5829        // that were supplied, taking care of removing any corresponding
5830        // duplicate items in the generic resolve list.
5831        if (specifics != null) {
5832            for (int i=0; i<specifics.length; i++) {
5833                final Intent sintent = specifics[i];
5834                if (sintent == null) {
5835                    continue;
5836                }
5837
5838                if (DEBUG_INTENT_MATCHING) {
5839                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5840                }
5841
5842                String action = sintent.getAction();
5843                if (resultsAction != null && resultsAction.equals(action)) {
5844                    // If this action was explicitly requested, then don't
5845                    // remove things that have it.
5846                    action = null;
5847                }
5848
5849                ResolveInfo ri = null;
5850                ActivityInfo ai = null;
5851
5852                ComponentName comp = sintent.getComponent();
5853                if (comp == null) {
5854                    ri = resolveIntent(
5855                        sintent,
5856                        specificTypes != null ? specificTypes[i] : null,
5857                            flags, userId);
5858                    if (ri == null) {
5859                        continue;
5860                    }
5861                    if (ri == mResolveInfo) {
5862                        // ACK!  Must do something better with this.
5863                    }
5864                    ai = ri.activityInfo;
5865                    comp = new ComponentName(ai.applicationInfo.packageName,
5866                            ai.name);
5867                } else {
5868                    ai = getActivityInfo(comp, flags, userId);
5869                    if (ai == null) {
5870                        continue;
5871                    }
5872                }
5873
5874                // Look for any generic query activities that are duplicates
5875                // of this specific one, and remove them from the results.
5876                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5877                N = results.size();
5878                int j;
5879                for (j=specificsPos; j<N; j++) {
5880                    ResolveInfo sri = results.get(j);
5881                    if ((sri.activityInfo.name.equals(comp.getClassName())
5882                            && sri.activityInfo.applicationInfo.packageName.equals(
5883                                    comp.getPackageName()))
5884                        || (action != null && sri.filter.matchAction(action))) {
5885                        results.remove(j);
5886                        if (DEBUG_INTENT_MATCHING) Log.v(
5887                            TAG, "Removing duplicate item from " + j
5888                            + " due to specific " + specificsPos);
5889                        if (ri == null) {
5890                            ri = sri;
5891                        }
5892                        j--;
5893                        N--;
5894                    }
5895                }
5896
5897                // Add this specific item to its proper place.
5898                if (ri == null) {
5899                    ri = new ResolveInfo();
5900                    ri.activityInfo = ai;
5901                }
5902                results.add(specificsPos, ri);
5903                ri.specificIndex = i;
5904                specificsPos++;
5905            }
5906        }
5907
5908        // Now we go through the remaining generic results and remove any
5909        // duplicate actions that are found here.
5910        N = results.size();
5911        for (int i=specificsPos; i<N-1; i++) {
5912            final ResolveInfo rii = results.get(i);
5913            if (rii.filter == null) {
5914                continue;
5915            }
5916
5917            // Iterate over all of the actions of this result's intent
5918            // filter...  typically this should be just one.
5919            final Iterator<String> it = rii.filter.actionsIterator();
5920            if (it == null) {
5921                continue;
5922            }
5923            while (it.hasNext()) {
5924                final String action = it.next();
5925                if (resultsAction != null && resultsAction.equals(action)) {
5926                    // If this action was explicitly requested, then don't
5927                    // remove things that have it.
5928                    continue;
5929                }
5930                for (int j=i+1; j<N; j++) {
5931                    final ResolveInfo rij = results.get(j);
5932                    if (rij.filter != null && rij.filter.hasAction(action)) {
5933                        results.remove(j);
5934                        if (DEBUG_INTENT_MATCHING) Log.v(
5935                            TAG, "Removing duplicate item from " + j
5936                            + " due to action " + action + " at " + i);
5937                        j--;
5938                        N--;
5939                    }
5940                }
5941            }
5942
5943            // If the caller didn't request filter information, drop it now
5944            // so we don't have to marshall/unmarshall it.
5945            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5946                rii.filter = null;
5947            }
5948        }
5949
5950        // Filter out the caller activity if so requested.
5951        if (caller != null) {
5952            N = results.size();
5953            for (int i=0; i<N; i++) {
5954                ActivityInfo ainfo = results.get(i).activityInfo;
5955                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5956                        && caller.getClassName().equals(ainfo.name)) {
5957                    results.remove(i);
5958                    break;
5959                }
5960            }
5961        }
5962
5963        // If the caller didn't request filter information,
5964        // drop them now so we don't have to
5965        // marshall/unmarshall it.
5966        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5967            N = results.size();
5968            for (int i=0; i<N; i++) {
5969                results.get(i).filter = null;
5970            }
5971        }
5972
5973        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5974        return results;
5975    }
5976
5977    @Override
5978    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5979            String resolvedType, int flags, int userId) {
5980        return new ParceledListSlice<>(
5981                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5982    }
5983
5984    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5985            String resolvedType, int flags, int userId) {
5986        if (!sUserManager.exists(userId)) return Collections.emptyList();
5987        flags = updateFlagsForResolve(flags, userId, intent);
5988        ComponentName comp = intent.getComponent();
5989        if (comp == null) {
5990            if (intent.getSelector() != null) {
5991                intent = intent.getSelector();
5992                comp = intent.getComponent();
5993            }
5994        }
5995        if (comp != null) {
5996            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5997            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5998            if (ai != null) {
5999                ResolveInfo ri = new ResolveInfo();
6000                ri.activityInfo = ai;
6001                list.add(ri);
6002            }
6003            return list;
6004        }
6005
6006        // reader
6007        synchronized (mPackages) {
6008            String pkgName = intent.getPackage();
6009            if (pkgName == null) {
6010                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6011            }
6012            final PackageParser.Package pkg = mPackages.get(pkgName);
6013            if (pkg != null) {
6014                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6015                        userId);
6016            }
6017            return Collections.emptyList();
6018        }
6019    }
6020
6021    @Override
6022    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6023        if (!sUserManager.exists(userId)) return null;
6024        flags = updateFlagsForResolve(flags, userId, intent);
6025        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6026        if (query != null) {
6027            if (query.size() >= 1) {
6028                // If there is more than one service with the same priority,
6029                // just arbitrarily pick the first one.
6030                return query.get(0);
6031            }
6032        }
6033        return null;
6034    }
6035
6036    @Override
6037    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6038            String resolvedType, int flags, int userId) {
6039        return new ParceledListSlice<>(
6040                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6041    }
6042
6043    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6044            String resolvedType, int flags, int userId) {
6045        if (!sUserManager.exists(userId)) return Collections.emptyList();
6046        flags = updateFlagsForResolve(flags, userId, intent);
6047        ComponentName comp = intent.getComponent();
6048        if (comp == null) {
6049            if (intent.getSelector() != null) {
6050                intent = intent.getSelector();
6051                comp = intent.getComponent();
6052            }
6053        }
6054        if (comp != null) {
6055            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6056            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6057            if (si != null) {
6058                final ResolveInfo ri = new ResolveInfo();
6059                ri.serviceInfo = si;
6060                list.add(ri);
6061            }
6062            return list;
6063        }
6064
6065        // reader
6066        synchronized (mPackages) {
6067            String pkgName = intent.getPackage();
6068            if (pkgName == null) {
6069                return mServices.queryIntent(intent, resolvedType, flags, userId);
6070            }
6071            final PackageParser.Package pkg = mPackages.get(pkgName);
6072            if (pkg != null) {
6073                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6074                        userId);
6075            }
6076            return Collections.emptyList();
6077        }
6078    }
6079
6080    @Override
6081    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6082            String resolvedType, int flags, int userId) {
6083        return new ParceledListSlice<>(
6084                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6085    }
6086
6087    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6088            Intent intent, String resolvedType, int flags, int userId) {
6089        if (!sUserManager.exists(userId)) return Collections.emptyList();
6090        flags = updateFlagsForResolve(flags, userId, intent);
6091        ComponentName comp = intent.getComponent();
6092        if (comp == null) {
6093            if (intent.getSelector() != null) {
6094                intent = intent.getSelector();
6095                comp = intent.getComponent();
6096            }
6097        }
6098        if (comp != null) {
6099            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6100            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6101            if (pi != null) {
6102                final ResolveInfo ri = new ResolveInfo();
6103                ri.providerInfo = pi;
6104                list.add(ri);
6105            }
6106            return list;
6107        }
6108
6109        // reader
6110        synchronized (mPackages) {
6111            String pkgName = intent.getPackage();
6112            if (pkgName == null) {
6113                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6114            }
6115            final PackageParser.Package pkg = mPackages.get(pkgName);
6116            if (pkg != null) {
6117                return mProviders.queryIntentForPackage(
6118                        intent, resolvedType, flags, pkg.providers, userId);
6119            }
6120            return Collections.emptyList();
6121        }
6122    }
6123
6124    @Override
6125    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6126        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6127        flags = updateFlagsForPackage(flags, userId, null);
6128        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6129        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6130                true /* requireFullPermission */, false /* checkShell */,
6131                "get installed packages");
6132
6133        // writer
6134        synchronized (mPackages) {
6135            ArrayList<PackageInfo> list;
6136            if (listUninstalled) {
6137                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6138                for (PackageSetting ps : mSettings.mPackages.values()) {
6139                    final PackageInfo pi;
6140                    if (ps.pkg != null) {
6141                        pi = generatePackageInfo(ps, flags, userId);
6142                    } else {
6143                        pi = generatePackageInfo(ps, flags, userId);
6144                    }
6145                    if (pi != null) {
6146                        list.add(pi);
6147                    }
6148                }
6149            } else {
6150                list = new ArrayList<PackageInfo>(mPackages.size());
6151                for (PackageParser.Package p : mPackages.values()) {
6152                    final PackageInfo pi =
6153                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6154                    if (pi != null) {
6155                        list.add(pi);
6156                    }
6157                }
6158            }
6159
6160            return new ParceledListSlice<PackageInfo>(list);
6161        }
6162    }
6163
6164    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6165            String[] permissions, boolean[] tmp, int flags, int userId) {
6166        int numMatch = 0;
6167        final PermissionsState permissionsState = ps.getPermissionsState();
6168        for (int i=0; i<permissions.length; i++) {
6169            final String permission = permissions[i];
6170            if (permissionsState.hasPermission(permission, userId)) {
6171                tmp[i] = true;
6172                numMatch++;
6173            } else {
6174                tmp[i] = false;
6175            }
6176        }
6177        if (numMatch == 0) {
6178            return;
6179        }
6180        final PackageInfo pi;
6181        if (ps.pkg != null) {
6182            pi = generatePackageInfo(ps, flags, userId);
6183        } else {
6184            pi = generatePackageInfo(ps, flags, userId);
6185        }
6186        // The above might return null in cases of uninstalled apps or install-state
6187        // skew across users/profiles.
6188        if (pi != null) {
6189            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6190                if (numMatch == permissions.length) {
6191                    pi.requestedPermissions = permissions;
6192                } else {
6193                    pi.requestedPermissions = new String[numMatch];
6194                    numMatch = 0;
6195                    for (int i=0; i<permissions.length; i++) {
6196                        if (tmp[i]) {
6197                            pi.requestedPermissions[numMatch] = permissions[i];
6198                            numMatch++;
6199                        }
6200                    }
6201                }
6202            }
6203            list.add(pi);
6204        }
6205    }
6206
6207    @Override
6208    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6209            String[] permissions, int flags, int userId) {
6210        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6211        flags = updateFlagsForPackage(flags, userId, permissions);
6212        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6213
6214        // writer
6215        synchronized (mPackages) {
6216            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6217            boolean[] tmpBools = new boolean[permissions.length];
6218            if (listUninstalled) {
6219                for (PackageSetting ps : mSettings.mPackages.values()) {
6220                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6221                }
6222            } else {
6223                for (PackageParser.Package pkg : mPackages.values()) {
6224                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6225                    if (ps != null) {
6226                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6227                                userId);
6228                    }
6229                }
6230            }
6231
6232            return new ParceledListSlice<PackageInfo>(list);
6233        }
6234    }
6235
6236    @Override
6237    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6238        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6239        flags = updateFlagsForApplication(flags, userId, null);
6240        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6241
6242        // writer
6243        synchronized (mPackages) {
6244            ArrayList<ApplicationInfo> list;
6245            if (listUninstalled) {
6246                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6247                for (PackageSetting ps : mSettings.mPackages.values()) {
6248                    ApplicationInfo ai;
6249                    if (ps.pkg != null) {
6250                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6251                                ps.readUserState(userId), userId);
6252                    } else {
6253                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6254                    }
6255                    if (ai != null) {
6256                        list.add(ai);
6257                    }
6258                }
6259            } else {
6260                list = new ArrayList<ApplicationInfo>(mPackages.size());
6261                for (PackageParser.Package p : mPackages.values()) {
6262                    if (p.mExtras != null) {
6263                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6264                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6265                        if (ai != null) {
6266                            list.add(ai);
6267                        }
6268                    }
6269                }
6270            }
6271
6272            return new ParceledListSlice<ApplicationInfo>(list);
6273        }
6274    }
6275
6276    @Override
6277    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6278        if (isEphemeralDisabled()) {
6279            return null;
6280        }
6281
6282        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6283                "getEphemeralApplications");
6284        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6285                true /* requireFullPermission */, false /* checkShell */,
6286                "getEphemeralApplications");
6287        synchronized (mPackages) {
6288            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6289                    .getEphemeralApplicationsLPw(userId);
6290            if (ephemeralApps != null) {
6291                return new ParceledListSlice<>(ephemeralApps);
6292            }
6293        }
6294        return null;
6295    }
6296
6297    @Override
6298    public boolean isEphemeralApplication(String packageName, int userId) {
6299        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6300                true /* requireFullPermission */, false /* checkShell */,
6301                "isEphemeral");
6302        if (isEphemeralDisabled()) {
6303            return false;
6304        }
6305
6306        if (!isCallerSameApp(packageName)) {
6307            return false;
6308        }
6309        synchronized (mPackages) {
6310            PackageParser.Package pkg = mPackages.get(packageName);
6311            if (pkg != null) {
6312                return pkg.applicationInfo.isEphemeralApp();
6313            }
6314        }
6315        return false;
6316    }
6317
6318    @Override
6319    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6320        if (isEphemeralDisabled()) {
6321            return null;
6322        }
6323
6324        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6325                true /* requireFullPermission */, false /* checkShell */,
6326                "getCookie");
6327        if (!isCallerSameApp(packageName)) {
6328            return null;
6329        }
6330        synchronized (mPackages) {
6331            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6332                    packageName, userId);
6333        }
6334    }
6335
6336    @Override
6337    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6338        if (isEphemeralDisabled()) {
6339            return true;
6340        }
6341
6342        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6343                true /* requireFullPermission */, true /* checkShell */,
6344                "setCookie");
6345        if (!isCallerSameApp(packageName)) {
6346            return false;
6347        }
6348        synchronized (mPackages) {
6349            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6350                    packageName, cookie, userId);
6351        }
6352    }
6353
6354    @Override
6355    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6356        if (isEphemeralDisabled()) {
6357            return null;
6358        }
6359
6360        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6361                "getEphemeralApplicationIcon");
6362        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6363                true /* requireFullPermission */, false /* checkShell */,
6364                "getEphemeralApplicationIcon");
6365        synchronized (mPackages) {
6366            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6367                    packageName, userId);
6368        }
6369    }
6370
6371    private boolean isCallerSameApp(String packageName) {
6372        PackageParser.Package pkg = mPackages.get(packageName);
6373        return pkg != null
6374                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6375    }
6376
6377    @Override
6378    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6379        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6380    }
6381
6382    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6383        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6384
6385        // reader
6386        synchronized (mPackages) {
6387            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6388            final int userId = UserHandle.getCallingUserId();
6389            while (i.hasNext()) {
6390                final PackageParser.Package p = i.next();
6391                if (p.applicationInfo == null) continue;
6392
6393                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6394                        && !p.applicationInfo.isDirectBootAware();
6395                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6396                        && p.applicationInfo.isDirectBootAware();
6397
6398                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6399                        && (!mSafeMode || isSystemApp(p))
6400                        && (matchesUnaware || matchesAware)) {
6401                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6402                    if (ps != null) {
6403                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6404                                ps.readUserState(userId), userId);
6405                        if (ai != null) {
6406                            finalList.add(ai);
6407                        }
6408                    }
6409                }
6410            }
6411        }
6412
6413        return finalList;
6414    }
6415
6416    @Override
6417    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6418        if (!sUserManager.exists(userId)) return null;
6419        flags = updateFlagsForComponent(flags, userId, name);
6420        // reader
6421        synchronized (mPackages) {
6422            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6423            PackageSetting ps = provider != null
6424                    ? mSettings.mPackages.get(provider.owner.packageName)
6425                    : null;
6426            return ps != null
6427                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6428                    ? PackageParser.generateProviderInfo(provider, flags,
6429                            ps.readUserState(userId), userId)
6430                    : null;
6431        }
6432    }
6433
6434    /**
6435     * @deprecated
6436     */
6437    @Deprecated
6438    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6439        // reader
6440        synchronized (mPackages) {
6441            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6442                    .entrySet().iterator();
6443            final int userId = UserHandle.getCallingUserId();
6444            while (i.hasNext()) {
6445                Map.Entry<String, PackageParser.Provider> entry = i.next();
6446                PackageParser.Provider p = entry.getValue();
6447                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6448
6449                if (ps != null && p.syncable
6450                        && (!mSafeMode || (p.info.applicationInfo.flags
6451                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6452                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6453                            ps.readUserState(userId), userId);
6454                    if (info != null) {
6455                        outNames.add(entry.getKey());
6456                        outInfo.add(info);
6457                    }
6458                }
6459            }
6460        }
6461    }
6462
6463    @Override
6464    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6465            int uid, int flags) {
6466        final int userId = processName != null ? UserHandle.getUserId(uid)
6467                : UserHandle.getCallingUserId();
6468        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6469        flags = updateFlagsForComponent(flags, userId, processName);
6470
6471        ArrayList<ProviderInfo> finalList = null;
6472        // reader
6473        synchronized (mPackages) {
6474            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6475            while (i.hasNext()) {
6476                final PackageParser.Provider p = i.next();
6477                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6478                if (ps != null && p.info.authority != null
6479                        && (processName == null
6480                                || (p.info.processName.equals(processName)
6481                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6482                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6483                    if (finalList == null) {
6484                        finalList = new ArrayList<ProviderInfo>(3);
6485                    }
6486                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6487                            ps.readUserState(userId), userId);
6488                    if (info != null) {
6489                        finalList.add(info);
6490                    }
6491                }
6492            }
6493        }
6494
6495        if (finalList != null) {
6496            Collections.sort(finalList, mProviderInitOrderSorter);
6497            return new ParceledListSlice<ProviderInfo>(finalList);
6498        }
6499
6500        return ParceledListSlice.emptyList();
6501    }
6502
6503    @Override
6504    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6505        // reader
6506        synchronized (mPackages) {
6507            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6508            return PackageParser.generateInstrumentationInfo(i, flags);
6509        }
6510    }
6511
6512    @Override
6513    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6514            String targetPackage, int flags) {
6515        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6516    }
6517
6518    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6519            int flags) {
6520        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6521
6522        // reader
6523        synchronized (mPackages) {
6524            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6525            while (i.hasNext()) {
6526                final PackageParser.Instrumentation p = i.next();
6527                if (targetPackage == null
6528                        || targetPackage.equals(p.info.targetPackage)) {
6529                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6530                            flags);
6531                    if (ii != null) {
6532                        finalList.add(ii);
6533                    }
6534                }
6535            }
6536        }
6537
6538        return finalList;
6539    }
6540
6541    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6542        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6543        if (overlays == null) {
6544            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6545            return;
6546        }
6547        for (PackageParser.Package opkg : overlays.values()) {
6548            // Not much to do if idmap fails: we already logged the error
6549            // and we certainly don't want to abort installation of pkg simply
6550            // because an overlay didn't fit properly. For these reasons,
6551            // ignore the return value of createIdmapForPackagePairLI.
6552            createIdmapForPackagePairLI(pkg, opkg);
6553        }
6554    }
6555
6556    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6557            PackageParser.Package opkg) {
6558        if (!opkg.mTrustedOverlay) {
6559            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6560                    opkg.baseCodePath + ": overlay not trusted");
6561            return false;
6562        }
6563        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6564        if (overlaySet == null) {
6565            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6566                    opkg.baseCodePath + " but target package has no known overlays");
6567            return false;
6568        }
6569        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6570        // TODO: generate idmap for split APKs
6571        try {
6572            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6573        } catch (InstallerException e) {
6574            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6575                    + opkg.baseCodePath);
6576            return false;
6577        }
6578        PackageParser.Package[] overlayArray =
6579            overlaySet.values().toArray(new PackageParser.Package[0]);
6580        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6581            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6582                return p1.mOverlayPriority - p2.mOverlayPriority;
6583            }
6584        };
6585        Arrays.sort(overlayArray, cmp);
6586
6587        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6588        int i = 0;
6589        for (PackageParser.Package p : overlayArray) {
6590            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6591        }
6592        return true;
6593    }
6594
6595    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6596        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6597        try {
6598            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6599        } finally {
6600            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6601        }
6602    }
6603
6604    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6605        final File[] files = dir.listFiles();
6606        if (ArrayUtils.isEmpty(files)) {
6607            Log.d(TAG, "No files in app dir " + dir);
6608            return;
6609        }
6610
6611        if (DEBUG_PACKAGE_SCANNING) {
6612            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6613                    + " flags=0x" + Integer.toHexString(parseFlags));
6614        }
6615
6616        for (File file : files) {
6617            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6618                    && !PackageInstallerService.isStageName(file.getName());
6619            if (!isPackage) {
6620                // Ignore entries which are not packages
6621                continue;
6622            }
6623            try {
6624                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6625                        scanFlags, currentTime, null);
6626            } catch (PackageManagerException e) {
6627                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6628
6629                // Delete invalid userdata apps
6630                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6631                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6632                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6633                    removeCodePathLI(file);
6634                }
6635            }
6636        }
6637    }
6638
6639    private static File getSettingsProblemFile() {
6640        File dataDir = Environment.getDataDirectory();
6641        File systemDir = new File(dataDir, "system");
6642        File fname = new File(systemDir, "uiderrors.txt");
6643        return fname;
6644    }
6645
6646    static void reportSettingsProblem(int priority, String msg) {
6647        logCriticalInfo(priority, msg);
6648    }
6649
6650    static void logCriticalInfo(int priority, String msg) {
6651        Slog.println(priority, TAG, msg);
6652        EventLogTags.writePmCriticalInfo(msg);
6653        try {
6654            File fname = getSettingsProblemFile();
6655            FileOutputStream out = new FileOutputStream(fname, true);
6656            PrintWriter pw = new FastPrintWriter(out);
6657            SimpleDateFormat formatter = new SimpleDateFormat();
6658            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6659            pw.println(dateString + ": " + msg);
6660            pw.close();
6661            FileUtils.setPermissions(
6662                    fname.toString(),
6663                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6664                    -1, -1);
6665        } catch (java.io.IOException e) {
6666        }
6667    }
6668
6669    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6670        if (srcFile.isDirectory()) {
6671            final File baseFile = new File(pkg.baseCodePath);
6672            long maxModifiedTime = baseFile.lastModified();
6673            if (pkg.splitCodePaths != null) {
6674                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6675                    final File splitFile = new File(pkg.splitCodePaths[i]);
6676                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6677                }
6678            }
6679            return maxModifiedTime;
6680        }
6681        return srcFile.lastModified();
6682    }
6683
6684    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6685            final int policyFlags) throws PackageManagerException {
6686        // When upgrading from pre-N MR1, verify the package time stamp using the package
6687        // directory and not the APK file.
6688        final long lastModifiedTime = mIsPreNMR1Upgrade
6689                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6690        if (ps != null
6691                && ps.codePath.equals(srcFile)
6692                && ps.timeStamp == lastModifiedTime
6693                && !isCompatSignatureUpdateNeeded(pkg)
6694                && !isRecoverSignatureUpdateNeeded(pkg)) {
6695            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6696            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6697            ArraySet<PublicKey> signingKs;
6698            synchronized (mPackages) {
6699                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6700            }
6701            if (ps.signatures.mSignatures != null
6702                    && ps.signatures.mSignatures.length != 0
6703                    && signingKs != null) {
6704                // Optimization: reuse the existing cached certificates
6705                // if the package appears to be unchanged.
6706                pkg.mSignatures = ps.signatures.mSignatures;
6707                pkg.mSigningKeys = signingKs;
6708                return;
6709            }
6710
6711            Slog.w(TAG, "PackageSetting for " + ps.name
6712                    + " is missing signatures.  Collecting certs again to recover them.");
6713        } else {
6714            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6715        }
6716
6717        try {
6718            PackageParser.collectCertificates(pkg, policyFlags);
6719        } catch (PackageParserException e) {
6720            throw PackageManagerException.from(e);
6721        }
6722    }
6723
6724    /**
6725     *  Traces a package scan.
6726     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6727     */
6728    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6729            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6730        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6731        try {
6732            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6733        } finally {
6734            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6735        }
6736    }
6737
6738    /**
6739     *  Scans a package and returns the newly parsed package.
6740     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6741     */
6742    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6743            long currentTime, UserHandle user) throws PackageManagerException {
6744        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6745        PackageParser pp = new PackageParser();
6746        pp.setSeparateProcesses(mSeparateProcesses);
6747        pp.setOnlyCoreApps(mOnlyCore);
6748        pp.setDisplayMetrics(mMetrics);
6749
6750        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6751            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6752        }
6753
6754        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6755        final PackageParser.Package pkg;
6756        try {
6757            pkg = pp.parsePackage(scanFile, parseFlags);
6758        } catch (PackageParserException e) {
6759            throw PackageManagerException.from(e);
6760        } finally {
6761            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6762        }
6763
6764        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6765    }
6766
6767    /**
6768     *  Scans a package and returns the newly parsed package.
6769     *  @throws PackageManagerException on a parse error.
6770     */
6771    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6772            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6773            throws PackageManagerException {
6774        // If the package has children and this is the first dive in the function
6775        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6776        // packages (parent and children) would be successfully scanned before the
6777        // actual scan since scanning mutates internal state and we want to atomically
6778        // install the package and its children.
6779        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6780            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6781                scanFlags |= SCAN_CHECK_ONLY;
6782            }
6783        } else {
6784            scanFlags &= ~SCAN_CHECK_ONLY;
6785        }
6786
6787        // Scan the parent
6788        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6789                scanFlags, currentTime, user);
6790
6791        // Scan the children
6792        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6793        for (int i = 0; i < childCount; i++) {
6794            PackageParser.Package childPackage = pkg.childPackages.get(i);
6795            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6796                    currentTime, user);
6797        }
6798
6799
6800        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6801            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6802        }
6803
6804        return scannedPkg;
6805    }
6806
6807    /**
6808     *  Scans a package and returns the newly parsed package.
6809     *  @throws PackageManagerException on a parse error.
6810     */
6811    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6812            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6813            throws PackageManagerException {
6814        PackageSetting ps = null;
6815        PackageSetting updatedPkg;
6816        // reader
6817        synchronized (mPackages) {
6818            // Look to see if we already know about this package.
6819            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6820            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6821                // This package has been renamed to its original name.  Let's
6822                // use that.
6823                ps = mSettings.peekPackageLPr(oldName);
6824            }
6825            // If there was no original package, see one for the real package name.
6826            if (ps == null) {
6827                ps = mSettings.peekPackageLPr(pkg.packageName);
6828            }
6829            // Check to see if this package could be hiding/updating a system
6830            // package.  Must look for it either under the original or real
6831            // package name depending on our state.
6832            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6833            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6834
6835            // If this is a package we don't know about on the system partition, we
6836            // may need to remove disabled child packages on the system partition
6837            // or may need to not add child packages if the parent apk is updated
6838            // on the data partition and no longer defines this child package.
6839            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6840                // If this is a parent package for an updated system app and this system
6841                // app got an OTA update which no longer defines some of the child packages
6842                // we have to prune them from the disabled system packages.
6843                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6844                if (disabledPs != null) {
6845                    final int scannedChildCount = (pkg.childPackages != null)
6846                            ? pkg.childPackages.size() : 0;
6847                    final int disabledChildCount = disabledPs.childPackageNames != null
6848                            ? disabledPs.childPackageNames.size() : 0;
6849                    for (int i = 0; i < disabledChildCount; i++) {
6850                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6851                        boolean disabledPackageAvailable = false;
6852                        for (int j = 0; j < scannedChildCount; j++) {
6853                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6854                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6855                                disabledPackageAvailable = true;
6856                                break;
6857                            }
6858                         }
6859                         if (!disabledPackageAvailable) {
6860                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6861                         }
6862                    }
6863                }
6864            }
6865        }
6866
6867        boolean updatedPkgBetter = false;
6868        // First check if this is a system package that may involve an update
6869        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6870            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6871            // it needs to drop FLAG_PRIVILEGED.
6872            if (locationIsPrivileged(scanFile)) {
6873                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6874            } else {
6875                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6876            }
6877
6878            if (ps != null && !ps.codePath.equals(scanFile)) {
6879                // The path has changed from what was last scanned...  check the
6880                // version of the new path against what we have stored to determine
6881                // what to do.
6882                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6883                if (pkg.mVersionCode <= ps.versionCode) {
6884                    // The system package has been updated and the code path does not match
6885                    // Ignore entry. Skip it.
6886                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6887                            + " ignored: updated version " + ps.versionCode
6888                            + " better than this " + pkg.mVersionCode);
6889                    if (!updatedPkg.codePath.equals(scanFile)) {
6890                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6891                                + ps.name + " changing from " + updatedPkg.codePathString
6892                                + " to " + scanFile);
6893                        updatedPkg.codePath = scanFile;
6894                        updatedPkg.codePathString = scanFile.toString();
6895                        updatedPkg.resourcePath = scanFile;
6896                        updatedPkg.resourcePathString = scanFile.toString();
6897                    }
6898                    updatedPkg.pkg = pkg;
6899                    updatedPkg.versionCode = pkg.mVersionCode;
6900
6901                    // Update the disabled system child packages to point to the package too.
6902                    final int childCount = updatedPkg.childPackageNames != null
6903                            ? updatedPkg.childPackageNames.size() : 0;
6904                    for (int i = 0; i < childCount; i++) {
6905                        String childPackageName = updatedPkg.childPackageNames.get(i);
6906                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6907                                childPackageName);
6908                        if (updatedChildPkg != null) {
6909                            updatedChildPkg.pkg = pkg;
6910                            updatedChildPkg.versionCode = pkg.mVersionCode;
6911                        }
6912                    }
6913
6914                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6915                            + scanFile + " ignored: updated version " + ps.versionCode
6916                            + " better than this " + pkg.mVersionCode);
6917                } else {
6918                    // The current app on the system partition is better than
6919                    // what we have updated to on the data partition; switch
6920                    // back to the system partition version.
6921                    // At this point, its safely assumed that package installation for
6922                    // apps in system partition will go through. If not there won't be a working
6923                    // version of the app
6924                    // writer
6925                    synchronized (mPackages) {
6926                        // Just remove the loaded entries from package lists.
6927                        mPackages.remove(ps.name);
6928                    }
6929
6930                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6931                            + " reverting from " + ps.codePathString
6932                            + ": new version " + pkg.mVersionCode
6933                            + " better than installed " + ps.versionCode);
6934
6935                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6936                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6937                    synchronized (mInstallLock) {
6938                        args.cleanUpResourcesLI();
6939                    }
6940                    synchronized (mPackages) {
6941                        mSettings.enableSystemPackageLPw(ps.name);
6942                    }
6943                    updatedPkgBetter = true;
6944                }
6945            }
6946        }
6947
6948        if (updatedPkg != null) {
6949            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6950            // initially
6951            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6952
6953            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6954            // flag set initially
6955            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6956                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6957            }
6958        }
6959
6960        // Verify certificates against what was last scanned
6961        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6962
6963        /*
6964         * A new system app appeared, but we already had a non-system one of the
6965         * same name installed earlier.
6966         */
6967        boolean shouldHideSystemApp = false;
6968        if (updatedPkg == null && ps != null
6969                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6970            /*
6971             * Check to make sure the signatures match first. If they don't,
6972             * wipe the installed application and its data.
6973             */
6974            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6975                    != PackageManager.SIGNATURE_MATCH) {
6976                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6977                        + " signatures don't match existing userdata copy; removing");
6978                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6979                        "scanPackageInternalLI")) {
6980                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6981                }
6982                ps = null;
6983            } else {
6984                /*
6985                 * If the newly-added system app is an older version than the
6986                 * already installed version, hide it. It will be scanned later
6987                 * and re-added like an update.
6988                 */
6989                if (pkg.mVersionCode <= ps.versionCode) {
6990                    shouldHideSystemApp = true;
6991                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6992                            + " but new version " + pkg.mVersionCode + " better than installed "
6993                            + ps.versionCode + "; hiding system");
6994                } else {
6995                    /*
6996                     * The newly found system app is a newer version that the
6997                     * one previously installed. Simply remove the
6998                     * already-installed application and replace it with our own
6999                     * while keeping the application data.
7000                     */
7001                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7002                            + " reverting from " + ps.codePathString + ": new version "
7003                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7004                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7005                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7006                    synchronized (mInstallLock) {
7007                        args.cleanUpResourcesLI();
7008                    }
7009                }
7010            }
7011        }
7012
7013        // The apk is forward locked (not public) if its code and resources
7014        // are kept in different files. (except for app in either system or
7015        // vendor path).
7016        // TODO grab this value from PackageSettings
7017        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7018            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7019                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7020            }
7021        }
7022
7023        // TODO: extend to support forward-locked splits
7024        String resourcePath = null;
7025        String baseResourcePath = null;
7026        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7027            if (ps != null && ps.resourcePathString != null) {
7028                resourcePath = ps.resourcePathString;
7029                baseResourcePath = ps.resourcePathString;
7030            } else {
7031                // Should not happen at all. Just log an error.
7032                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7033            }
7034        } else {
7035            resourcePath = pkg.codePath;
7036            baseResourcePath = pkg.baseCodePath;
7037        }
7038
7039        // Set application objects path explicitly.
7040        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7041        pkg.setApplicationInfoCodePath(pkg.codePath);
7042        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7043        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7044        pkg.setApplicationInfoResourcePath(resourcePath);
7045        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7046        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7047
7048        // Note that we invoke the following method only if we are about to unpack an application
7049        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7050                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7051
7052        /*
7053         * If the system app should be overridden by a previously installed
7054         * data, hide the system app now and let the /data/app scan pick it up
7055         * again.
7056         */
7057        if (shouldHideSystemApp) {
7058            synchronized (mPackages) {
7059                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7060            }
7061        }
7062
7063        return scannedPkg;
7064    }
7065
7066    private static String fixProcessName(String defProcessName,
7067            String processName, int uid) {
7068        if (processName == null) {
7069            return defProcessName;
7070        }
7071        return processName;
7072    }
7073
7074    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7075            throws PackageManagerException {
7076        if (pkgSetting.signatures.mSignatures != null) {
7077            // Already existing package. Make sure signatures match
7078            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7079                    == PackageManager.SIGNATURE_MATCH;
7080            if (!match) {
7081                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7082                        == PackageManager.SIGNATURE_MATCH;
7083            }
7084            if (!match) {
7085                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7086                        == PackageManager.SIGNATURE_MATCH;
7087            }
7088            if (!match) {
7089                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7090                        + pkg.packageName + " signatures do not match the "
7091                        + "previously installed version; ignoring!");
7092            }
7093        }
7094
7095        // Check for shared user signatures
7096        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7097            // Already existing package. Make sure signatures match
7098            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7099                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7100            if (!match) {
7101                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7102                        == PackageManager.SIGNATURE_MATCH;
7103            }
7104            if (!match) {
7105                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7106                        == PackageManager.SIGNATURE_MATCH;
7107            }
7108            if (!match) {
7109                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7110                        "Package " + pkg.packageName
7111                        + " has no signatures that match those in shared user "
7112                        + pkgSetting.sharedUser.name + "; ignoring!");
7113            }
7114        }
7115    }
7116
7117    /**
7118     * Enforces that only the system UID or root's UID can call a method exposed
7119     * via Binder.
7120     *
7121     * @param message used as message if SecurityException is thrown
7122     * @throws SecurityException if the caller is not system or root
7123     */
7124    private static final void enforceSystemOrRoot(String message) {
7125        final int uid = Binder.getCallingUid();
7126        if (uid != Process.SYSTEM_UID && uid != 0) {
7127            throw new SecurityException(message);
7128        }
7129    }
7130
7131    @Override
7132    public void performFstrimIfNeeded() {
7133        enforceSystemOrRoot("Only the system can request fstrim");
7134
7135        // Before everything else, see whether we need to fstrim.
7136        try {
7137            IMountService ms = PackageHelper.getMountService();
7138            if (ms != null) {
7139                boolean doTrim = false;
7140                final long interval = android.provider.Settings.Global.getLong(
7141                        mContext.getContentResolver(),
7142                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7143                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7144                if (interval > 0) {
7145                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7146                    if (timeSinceLast > interval) {
7147                        doTrim = true;
7148                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7149                                + "; running immediately");
7150                    }
7151                }
7152                if (doTrim) {
7153                    if (!isFirstBoot()) {
7154                        try {
7155                            ActivityManagerNative.getDefault().showBootMessage(
7156                                    mContext.getResources().getString(
7157                                            R.string.android_upgrading_fstrim), true);
7158                        } catch (RemoteException e) {
7159                        }
7160                    }
7161                    ms.runMaintenance();
7162                }
7163            } else {
7164                Slog.e(TAG, "Mount service unavailable!");
7165            }
7166        } catch (RemoteException e) {
7167            // Can't happen; MountService is local
7168        }
7169    }
7170
7171    @Override
7172    public void updatePackagesIfNeeded() {
7173        enforceSystemOrRoot("Only the system can request package update");
7174
7175        // We need to re-extract after an OTA.
7176        boolean causeUpgrade = isUpgrade();
7177
7178        // First boot or factory reset.
7179        // Note: we also handle devices that are upgrading to N right now as if it is their
7180        //       first boot, as they do not have profile data.
7181        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7182
7183        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7184        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7185
7186        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7187            return;
7188        }
7189
7190        List<PackageParser.Package> pkgs;
7191        synchronized (mPackages) {
7192            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7193        }
7194
7195        final long startTime = System.nanoTime();
7196        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7197                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7198
7199        final int elapsedTimeSeconds =
7200                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7201
7202        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7203        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7204        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7205        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7206        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7207    }
7208
7209    /**
7210     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7211     * containing statistics about the invocation. The array consists of three elements,
7212     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7213     * and {@code numberOfPackagesFailed}.
7214     */
7215    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7216            String compilerFilter) {
7217
7218        int numberOfPackagesVisited = 0;
7219        int numberOfPackagesOptimized = 0;
7220        int numberOfPackagesSkipped = 0;
7221        int numberOfPackagesFailed = 0;
7222        final int numberOfPackagesToDexopt = pkgs.size();
7223
7224        for (PackageParser.Package pkg : pkgs) {
7225            numberOfPackagesVisited++;
7226
7227            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7228                if (DEBUG_DEXOPT) {
7229                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7230                }
7231                numberOfPackagesSkipped++;
7232                continue;
7233            }
7234
7235            if (DEBUG_DEXOPT) {
7236                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7237                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7238            }
7239
7240            if (showDialog) {
7241                try {
7242                    ActivityManagerNative.getDefault().showBootMessage(
7243                            mContext.getResources().getString(R.string.android_upgrading_apk,
7244                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7245                } catch (RemoteException e) {
7246                }
7247            }
7248
7249            // If the OTA updates a system app which was previously preopted to a non-preopted state
7250            // the app might end up being verified at runtime. That's because by default the apps
7251            // are verify-profile but for preopted apps there's no profile.
7252            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7253            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7254            // filter (by default interpret-only).
7255            // Note that at this stage unused apps are already filtered.
7256            if (isSystemApp(pkg) &&
7257                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7258                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7259                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7260            }
7261
7262            // checkProfiles is false to avoid merging profiles during boot which
7263            // might interfere with background compilation (b/28612421).
7264            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7265            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7266            // trade-off worth doing to save boot time work.
7267            int dexOptStatus = performDexOptTraced(pkg.packageName,
7268                    false /* checkProfiles */,
7269                    compilerFilter,
7270                    false /* force */);
7271            switch (dexOptStatus) {
7272                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7273                    numberOfPackagesOptimized++;
7274                    break;
7275                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7276                    numberOfPackagesSkipped++;
7277                    break;
7278                case PackageDexOptimizer.DEX_OPT_FAILED:
7279                    numberOfPackagesFailed++;
7280                    break;
7281                default:
7282                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7283                    break;
7284            }
7285        }
7286
7287        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7288                numberOfPackagesFailed };
7289    }
7290
7291    @Override
7292    public void notifyPackageUse(String packageName, int reason) {
7293        synchronized (mPackages) {
7294            PackageParser.Package p = mPackages.get(packageName);
7295            if (p == null) {
7296                return;
7297            }
7298            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7299        }
7300    }
7301
7302    // TODO: this is not used nor needed. Delete it.
7303    @Override
7304    public boolean performDexOptIfNeeded(String packageName) {
7305        int dexOptStatus = performDexOptTraced(packageName,
7306                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7307        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7308    }
7309
7310    @Override
7311    public boolean performDexOpt(String packageName,
7312            boolean checkProfiles, int compileReason, boolean force) {
7313        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7314                getCompilerFilterForReason(compileReason), force);
7315        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7316    }
7317
7318    @Override
7319    public boolean performDexOptMode(String packageName,
7320            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7321        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7322                targetCompilerFilter, force);
7323        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7324    }
7325
7326    private int performDexOptTraced(String packageName,
7327                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7328        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7329        try {
7330            return performDexOptInternal(packageName, checkProfiles,
7331                    targetCompilerFilter, force);
7332        } finally {
7333            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7334        }
7335    }
7336
7337    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7338    // if the package can now be considered up to date for the given filter.
7339    private int performDexOptInternal(String packageName,
7340                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7341        PackageParser.Package p;
7342        synchronized (mPackages) {
7343            p = mPackages.get(packageName);
7344            if (p == null) {
7345                // Package could not be found. Report failure.
7346                return PackageDexOptimizer.DEX_OPT_FAILED;
7347            }
7348            mPackageUsage.maybeWriteAsync(mPackages);
7349            mCompilerStats.maybeWriteAsync();
7350        }
7351        long callingId = Binder.clearCallingIdentity();
7352        try {
7353            synchronized (mInstallLock) {
7354                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7355                        targetCompilerFilter, force);
7356            }
7357        } finally {
7358            Binder.restoreCallingIdentity(callingId);
7359        }
7360    }
7361
7362    public ArraySet<String> getOptimizablePackages() {
7363        ArraySet<String> pkgs = new ArraySet<String>();
7364        synchronized (mPackages) {
7365            for (PackageParser.Package p : mPackages.values()) {
7366                if (PackageDexOptimizer.canOptimizePackage(p)) {
7367                    pkgs.add(p.packageName);
7368                }
7369            }
7370        }
7371        return pkgs;
7372    }
7373
7374    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7375            boolean checkProfiles, String targetCompilerFilter,
7376            boolean force) {
7377        // Select the dex optimizer based on the force parameter.
7378        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7379        //       allocate an object here.
7380        PackageDexOptimizer pdo = force
7381                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7382                : mPackageDexOptimizer;
7383
7384        // Optimize all dependencies first. Note: we ignore the return value and march on
7385        // on errors.
7386        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7387        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7388        if (!deps.isEmpty()) {
7389            for (PackageParser.Package depPackage : deps) {
7390                // TODO: Analyze and investigate if we (should) profile libraries.
7391                // Currently this will do a full compilation of the library by default.
7392                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7393                        false /* checkProfiles */,
7394                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7395                        getOrCreateCompilerPackageStats(depPackage));
7396            }
7397        }
7398        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7399                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7400    }
7401
7402    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7403        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7404            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7405            Set<String> collectedNames = new HashSet<>();
7406            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7407
7408            retValue.remove(p);
7409
7410            return retValue;
7411        } else {
7412            return Collections.emptyList();
7413        }
7414    }
7415
7416    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7417            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7418        if (!collectedNames.contains(p.packageName)) {
7419            collectedNames.add(p.packageName);
7420            collected.add(p);
7421
7422            if (p.usesLibraries != null) {
7423                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7424            }
7425            if (p.usesOptionalLibraries != null) {
7426                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7427                        collectedNames);
7428            }
7429        }
7430    }
7431
7432    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7433            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7434        for (String libName : libs) {
7435            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7436            if (libPkg != null) {
7437                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7438            }
7439        }
7440    }
7441
7442    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7443        synchronized (mPackages) {
7444            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7445            if (lib != null && lib.apk != null) {
7446                return mPackages.get(lib.apk);
7447            }
7448        }
7449        return null;
7450    }
7451
7452    public void shutdown() {
7453        mPackageUsage.writeNow(mPackages);
7454        mCompilerStats.writeNow();
7455    }
7456
7457    @Override
7458    public void dumpProfiles(String packageName) {
7459        PackageParser.Package pkg;
7460        synchronized (mPackages) {
7461            pkg = mPackages.get(packageName);
7462            if (pkg == null) {
7463                throw new IllegalArgumentException("Unknown package: " + packageName);
7464            }
7465        }
7466        /* Only the shell, root, or the app user should be able to dump profiles. */
7467        int callingUid = Binder.getCallingUid();
7468        if (callingUid != Process.SHELL_UID &&
7469            callingUid != Process.ROOT_UID &&
7470            callingUid != pkg.applicationInfo.uid) {
7471            throw new SecurityException("dumpProfiles");
7472        }
7473
7474        synchronized (mInstallLock) {
7475            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7476            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7477            try {
7478                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7479                String gid = Integer.toString(sharedGid);
7480                String codePaths = TextUtils.join(";", allCodePaths);
7481                mInstaller.dumpProfiles(gid, packageName, codePaths);
7482            } catch (InstallerException e) {
7483                Slog.w(TAG, "Failed to dump profiles", e);
7484            }
7485            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7486        }
7487    }
7488
7489    @Override
7490    public void forceDexOpt(String packageName) {
7491        enforceSystemOrRoot("forceDexOpt");
7492
7493        PackageParser.Package pkg;
7494        synchronized (mPackages) {
7495            pkg = mPackages.get(packageName);
7496            if (pkg == null) {
7497                throw new IllegalArgumentException("Unknown package: " + packageName);
7498            }
7499        }
7500
7501        synchronized (mInstallLock) {
7502            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7503
7504            // Whoever is calling forceDexOpt wants a fully compiled package.
7505            // Don't use profiles since that may cause compilation to be skipped.
7506            final int res = performDexOptInternalWithDependenciesLI(pkg,
7507                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7508                    true /* force */);
7509
7510            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7511            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7512                throw new IllegalStateException("Failed to dexopt: " + res);
7513            }
7514        }
7515    }
7516
7517    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7518        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7519            Slog.w(TAG, "Unable to update from " + oldPkg.name
7520                    + " to " + newPkg.packageName
7521                    + ": old package not in system partition");
7522            return false;
7523        } else if (mPackages.get(oldPkg.name) != null) {
7524            Slog.w(TAG, "Unable to update from " + oldPkg.name
7525                    + " to " + newPkg.packageName
7526                    + ": old package still exists");
7527            return false;
7528        }
7529        return true;
7530    }
7531
7532    void removeCodePathLI(File codePath) {
7533        if (codePath.isDirectory()) {
7534            try {
7535                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7536            } catch (InstallerException e) {
7537                Slog.w(TAG, "Failed to remove code path", e);
7538            }
7539        } else {
7540            codePath.delete();
7541        }
7542    }
7543
7544    private int[] resolveUserIds(int userId) {
7545        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7546    }
7547
7548    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7549        if (pkg == null) {
7550            Slog.wtf(TAG, "Package was null!", new Throwable());
7551            return;
7552        }
7553        clearAppDataLeafLIF(pkg, userId, flags);
7554        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7555        for (int i = 0; i < childCount; i++) {
7556            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7557        }
7558    }
7559
7560    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7561        final PackageSetting ps;
7562        synchronized (mPackages) {
7563            ps = mSettings.mPackages.get(pkg.packageName);
7564        }
7565        for (int realUserId : resolveUserIds(userId)) {
7566            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7567            try {
7568                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7569                        ceDataInode);
7570            } catch (InstallerException e) {
7571                Slog.w(TAG, String.valueOf(e));
7572            }
7573        }
7574    }
7575
7576    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7577        if (pkg == null) {
7578            Slog.wtf(TAG, "Package was null!", new Throwable());
7579            return;
7580        }
7581        destroyAppDataLeafLIF(pkg, userId, flags);
7582        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7583        for (int i = 0; i < childCount; i++) {
7584            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7585        }
7586    }
7587
7588    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7589        final PackageSetting ps;
7590        synchronized (mPackages) {
7591            ps = mSettings.mPackages.get(pkg.packageName);
7592        }
7593        for (int realUserId : resolveUserIds(userId)) {
7594            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7595            try {
7596                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7597                        ceDataInode);
7598            } catch (InstallerException e) {
7599                Slog.w(TAG, String.valueOf(e));
7600            }
7601        }
7602    }
7603
7604    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7605        if (pkg == null) {
7606            Slog.wtf(TAG, "Package was null!", new Throwable());
7607            return;
7608        }
7609        destroyAppProfilesLeafLIF(pkg);
7610        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7611        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7612        for (int i = 0; i < childCount; i++) {
7613            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7614            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7615                    true /* removeBaseMarker */);
7616        }
7617    }
7618
7619    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7620            boolean removeBaseMarker) {
7621        if (pkg.isForwardLocked()) {
7622            return;
7623        }
7624
7625        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7626            try {
7627                path = PackageManagerServiceUtils.realpath(new File(path));
7628            } catch (IOException e) {
7629                // TODO: Should we return early here ?
7630                Slog.w(TAG, "Failed to get canonical path", e);
7631                continue;
7632            }
7633
7634            final String useMarker = path.replace('/', '@');
7635            for (int realUserId : resolveUserIds(userId)) {
7636                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7637                if (removeBaseMarker) {
7638                    File foreignUseMark = new File(profileDir, useMarker);
7639                    if (foreignUseMark.exists()) {
7640                        if (!foreignUseMark.delete()) {
7641                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7642                                    + pkg.packageName);
7643                        }
7644                    }
7645                }
7646
7647                File[] markers = profileDir.listFiles();
7648                if (markers != null) {
7649                    final String searchString = "@" + pkg.packageName + "@";
7650                    // We also delete all markers that contain the package name we're
7651                    // uninstalling. These are associated with secondary dex-files belonging
7652                    // to the package. Reconstructing the path of these dex files is messy
7653                    // in general.
7654                    for (File marker : markers) {
7655                        if (marker.getName().indexOf(searchString) > 0) {
7656                            if (!marker.delete()) {
7657                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7658                                    + pkg.packageName);
7659                            }
7660                        }
7661                    }
7662                }
7663            }
7664        }
7665    }
7666
7667    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7668        try {
7669            mInstaller.destroyAppProfiles(pkg.packageName);
7670        } catch (InstallerException e) {
7671            Slog.w(TAG, String.valueOf(e));
7672        }
7673    }
7674
7675    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7676        if (pkg == null) {
7677            Slog.wtf(TAG, "Package was null!", new Throwable());
7678            return;
7679        }
7680        clearAppProfilesLeafLIF(pkg);
7681        // We don't remove the base foreign use marker when clearing profiles because
7682        // we will rename it when the app is updated. Unlike the actual profile contents,
7683        // the foreign use marker is good across installs.
7684        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7685        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7686        for (int i = 0; i < childCount; i++) {
7687            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7688        }
7689    }
7690
7691    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7692        try {
7693            mInstaller.clearAppProfiles(pkg.packageName);
7694        } catch (InstallerException e) {
7695            Slog.w(TAG, String.valueOf(e));
7696        }
7697    }
7698
7699    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7700            long lastUpdateTime) {
7701        // Set parent install/update time
7702        PackageSetting ps = (PackageSetting) pkg.mExtras;
7703        if (ps != null) {
7704            ps.firstInstallTime = firstInstallTime;
7705            ps.lastUpdateTime = lastUpdateTime;
7706        }
7707        // Set children install/update time
7708        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7709        for (int i = 0; i < childCount; i++) {
7710            PackageParser.Package childPkg = pkg.childPackages.get(i);
7711            ps = (PackageSetting) childPkg.mExtras;
7712            if (ps != null) {
7713                ps.firstInstallTime = firstInstallTime;
7714                ps.lastUpdateTime = lastUpdateTime;
7715            }
7716        }
7717    }
7718
7719    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7720            PackageParser.Package changingLib) {
7721        if (file.path != null) {
7722            usesLibraryFiles.add(file.path);
7723            return;
7724        }
7725        PackageParser.Package p = mPackages.get(file.apk);
7726        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7727            // If we are doing this while in the middle of updating a library apk,
7728            // then we need to make sure to use that new apk for determining the
7729            // dependencies here.  (We haven't yet finished committing the new apk
7730            // to the package manager state.)
7731            if (p == null || p.packageName.equals(changingLib.packageName)) {
7732                p = changingLib;
7733            }
7734        }
7735        if (p != null) {
7736            usesLibraryFiles.addAll(p.getAllCodePaths());
7737        }
7738    }
7739
7740    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7741            PackageParser.Package changingLib) throws PackageManagerException {
7742        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7743            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7744            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7745            for (int i=0; i<N; i++) {
7746                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7747                if (file == null) {
7748                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7749                            "Package " + pkg.packageName + " requires unavailable shared library "
7750                            + pkg.usesLibraries.get(i) + "; failing!");
7751                }
7752                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7753            }
7754            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7755            for (int i=0; i<N; i++) {
7756                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7757                if (file == null) {
7758                    Slog.w(TAG, "Package " + pkg.packageName
7759                            + " desires unavailable shared library "
7760                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7761                } else {
7762                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7763                }
7764            }
7765            N = usesLibraryFiles.size();
7766            if (N > 0) {
7767                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7768            } else {
7769                pkg.usesLibraryFiles = null;
7770            }
7771        }
7772    }
7773
7774    private static boolean hasString(List<String> list, List<String> which) {
7775        if (list == null) {
7776            return false;
7777        }
7778        for (int i=list.size()-1; i>=0; i--) {
7779            for (int j=which.size()-1; j>=0; j--) {
7780                if (which.get(j).equals(list.get(i))) {
7781                    return true;
7782                }
7783            }
7784        }
7785        return false;
7786    }
7787
7788    private void updateAllSharedLibrariesLPw() {
7789        for (PackageParser.Package pkg : mPackages.values()) {
7790            try {
7791                updateSharedLibrariesLPw(pkg, null);
7792            } catch (PackageManagerException e) {
7793                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7794            }
7795        }
7796    }
7797
7798    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7799            PackageParser.Package changingPkg) {
7800        ArrayList<PackageParser.Package> res = null;
7801        for (PackageParser.Package pkg : mPackages.values()) {
7802            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7803                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7804                if (res == null) {
7805                    res = new ArrayList<PackageParser.Package>();
7806                }
7807                res.add(pkg);
7808                try {
7809                    updateSharedLibrariesLPw(pkg, changingPkg);
7810                } catch (PackageManagerException e) {
7811                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7812                }
7813            }
7814        }
7815        return res;
7816    }
7817
7818    /**
7819     * Derive the value of the {@code cpuAbiOverride} based on the provided
7820     * value and an optional stored value from the package settings.
7821     */
7822    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7823        String cpuAbiOverride = null;
7824
7825        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7826            cpuAbiOverride = null;
7827        } else if (abiOverride != null) {
7828            cpuAbiOverride = abiOverride;
7829        } else if (settings != null) {
7830            cpuAbiOverride = settings.cpuAbiOverrideString;
7831        }
7832
7833        return cpuAbiOverride;
7834    }
7835
7836    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7837            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7838                    throws PackageManagerException {
7839        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7840        // If the package has children and this is the first dive in the function
7841        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7842        // whether all packages (parent and children) would be successfully scanned
7843        // before the actual scan since scanning mutates internal state and we want
7844        // to atomically install the package and its children.
7845        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7846            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7847                scanFlags |= SCAN_CHECK_ONLY;
7848            }
7849        } else {
7850            scanFlags &= ~SCAN_CHECK_ONLY;
7851        }
7852
7853        final PackageParser.Package scannedPkg;
7854        try {
7855            // Scan the parent
7856            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7857            // Scan the children
7858            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7859            for (int i = 0; i < childCount; i++) {
7860                PackageParser.Package childPkg = pkg.childPackages.get(i);
7861                scanPackageLI(childPkg, policyFlags,
7862                        scanFlags, currentTime, user);
7863            }
7864        } finally {
7865            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7866        }
7867
7868        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7869            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7870        }
7871
7872        return scannedPkg;
7873    }
7874
7875    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7876            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7877        boolean success = false;
7878        try {
7879            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7880                    currentTime, user);
7881            success = true;
7882            return res;
7883        } finally {
7884            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7885                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7886                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7887                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7888                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7889            }
7890        }
7891    }
7892
7893    /**
7894     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7895     */
7896    private static boolean apkHasCode(String fileName) {
7897        StrictJarFile jarFile = null;
7898        try {
7899            jarFile = new StrictJarFile(fileName,
7900                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7901            return jarFile.findEntry("classes.dex") != null;
7902        } catch (IOException ignore) {
7903        } finally {
7904            try {
7905                if (jarFile != null) {
7906                    jarFile.close();
7907                }
7908            } catch (IOException ignore) {}
7909        }
7910        return false;
7911    }
7912
7913    /**
7914     * Enforces code policy for the package. This ensures that if an APK has
7915     * declared hasCode="true" in its manifest that the APK actually contains
7916     * code.
7917     *
7918     * @throws PackageManagerException If bytecode could not be found when it should exist
7919     */
7920    private static void enforceCodePolicy(PackageParser.Package pkg)
7921            throws PackageManagerException {
7922        final boolean shouldHaveCode =
7923                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7924        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7925            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7926                    "Package " + pkg.baseCodePath + " code is missing");
7927        }
7928
7929        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7930            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7931                final boolean splitShouldHaveCode =
7932                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7933                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7934                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7935                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7936                }
7937            }
7938        }
7939    }
7940
7941    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7942            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7943            throws PackageManagerException {
7944        final File scanFile = new File(pkg.codePath);
7945        if (pkg.applicationInfo.getCodePath() == null ||
7946                pkg.applicationInfo.getResourcePath() == null) {
7947            // Bail out. The resource and code paths haven't been set.
7948            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7949                    "Code and resource paths haven't been set correctly");
7950        }
7951
7952        // Apply policy
7953        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7954            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7955            if (pkg.applicationInfo.isDirectBootAware()) {
7956                // we're direct boot aware; set for all components
7957                for (PackageParser.Service s : pkg.services) {
7958                    s.info.encryptionAware = s.info.directBootAware = true;
7959                }
7960                for (PackageParser.Provider p : pkg.providers) {
7961                    p.info.encryptionAware = p.info.directBootAware = true;
7962                }
7963                for (PackageParser.Activity a : pkg.activities) {
7964                    a.info.encryptionAware = a.info.directBootAware = true;
7965                }
7966                for (PackageParser.Activity r : pkg.receivers) {
7967                    r.info.encryptionAware = r.info.directBootAware = true;
7968                }
7969            }
7970        } else {
7971            // Only allow system apps to be flagged as core apps.
7972            pkg.coreApp = false;
7973            // clear flags not applicable to regular apps
7974            pkg.applicationInfo.privateFlags &=
7975                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7976            pkg.applicationInfo.privateFlags &=
7977                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7978        }
7979        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7980
7981        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7982            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7983        }
7984
7985        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7986            enforceCodePolicy(pkg);
7987        }
7988
7989        if (mCustomResolverComponentName != null &&
7990                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7991            setUpCustomResolverActivity(pkg);
7992        }
7993
7994        if (pkg.packageName.equals("android")) {
7995            synchronized (mPackages) {
7996                if (mAndroidApplication != null) {
7997                    Slog.w(TAG, "*************************************************");
7998                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7999                    Slog.w(TAG, " file=" + scanFile);
8000                    Slog.w(TAG, "*************************************************");
8001                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8002                            "Core android package being redefined.  Skipping.");
8003                }
8004
8005                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8006                    // Set up information for our fall-back user intent resolution activity.
8007                    mPlatformPackage = pkg;
8008                    pkg.mVersionCode = mSdkVersion;
8009                    mAndroidApplication = pkg.applicationInfo;
8010
8011                    if (!mResolverReplaced) {
8012                        mResolveActivity.applicationInfo = mAndroidApplication;
8013                        mResolveActivity.name = ResolverActivity.class.getName();
8014                        mResolveActivity.packageName = mAndroidApplication.packageName;
8015                        mResolveActivity.processName = "system:ui";
8016                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8017                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8018                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8019                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8020                        mResolveActivity.exported = true;
8021                        mResolveActivity.enabled = true;
8022                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8023                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8024                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8025                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8026                                | ActivityInfo.CONFIG_ORIENTATION
8027                                | ActivityInfo.CONFIG_KEYBOARD
8028                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8029                        mResolveInfo.activityInfo = mResolveActivity;
8030                        mResolveInfo.priority = 0;
8031                        mResolveInfo.preferredOrder = 0;
8032                        mResolveInfo.match = 0;
8033                        mResolveComponentName = new ComponentName(
8034                                mAndroidApplication.packageName, mResolveActivity.name);
8035                    }
8036                }
8037            }
8038        }
8039
8040        if (DEBUG_PACKAGE_SCANNING) {
8041            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8042                Log.d(TAG, "Scanning package " + pkg.packageName);
8043        }
8044
8045        synchronized (mPackages) {
8046            if (mPackages.containsKey(pkg.packageName)
8047                    || mSharedLibraries.containsKey(pkg.packageName)) {
8048                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8049                        "Application package " + pkg.packageName
8050                                + " already installed.  Skipping duplicate.");
8051            }
8052
8053            // If we're only installing presumed-existing packages, require that the
8054            // scanned APK is both already known and at the path previously established
8055            // for it.  Previously unknown packages we pick up normally, but if we have an
8056            // a priori expectation about this package's install presence, enforce it.
8057            // With a singular exception for new system packages. When an OTA contains
8058            // a new system package, we allow the codepath to change from a system location
8059            // to the user-installed location. If we don't allow this change, any newer,
8060            // user-installed version of the application will be ignored.
8061            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8062                if (mExpectingBetter.containsKey(pkg.packageName)) {
8063                    logCriticalInfo(Log.WARN,
8064                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8065                } else {
8066                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8067                    if (known != null) {
8068                        if (DEBUG_PACKAGE_SCANNING) {
8069                            Log.d(TAG, "Examining " + pkg.codePath
8070                                    + " and requiring known paths " + known.codePathString
8071                                    + " & " + known.resourcePathString);
8072                        }
8073                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8074                                || !pkg.applicationInfo.getResourcePath().equals(
8075                                known.resourcePathString)) {
8076                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8077                                    "Application package " + pkg.packageName
8078                                            + " found at " + pkg.applicationInfo.getCodePath()
8079                                            + " but expected at " + known.codePathString
8080                                            + "; ignoring.");
8081                        }
8082                    }
8083                }
8084            }
8085        }
8086
8087        // Initialize package source and resource directories
8088        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8089        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8090
8091        SharedUserSetting suid = null;
8092        PackageSetting pkgSetting = null;
8093
8094        if (!isSystemApp(pkg)) {
8095            // Only system apps can use these features.
8096            pkg.mOriginalPackages = null;
8097            pkg.mRealPackage = null;
8098            pkg.mAdoptPermissions = null;
8099        }
8100
8101        // Getting the package setting may have a side-effect, so if we
8102        // are only checking if scan would succeed, stash a copy of the
8103        // old setting to restore at the end.
8104        PackageSetting nonMutatedPs = null;
8105
8106        // writer
8107        synchronized (mPackages) {
8108            if (pkg.mSharedUserId != null) {
8109                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8110                if (suid == null) {
8111                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8112                            "Creating application package " + pkg.packageName
8113                            + " for shared user failed");
8114                }
8115                if (DEBUG_PACKAGE_SCANNING) {
8116                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8117                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8118                                + "): packages=" + suid.packages);
8119                }
8120            }
8121
8122            // Check if we are renaming from an original package name.
8123            PackageSetting origPackage = null;
8124            String realName = null;
8125            if (pkg.mOriginalPackages != null) {
8126                // This package may need to be renamed to a previously
8127                // installed name.  Let's check on that...
8128                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8129                if (pkg.mOriginalPackages.contains(renamed)) {
8130                    // This package had originally been installed as the
8131                    // original name, and we have already taken care of
8132                    // transitioning to the new one.  Just update the new
8133                    // one to continue using the old name.
8134                    realName = pkg.mRealPackage;
8135                    if (!pkg.packageName.equals(renamed)) {
8136                        // Callers into this function may have already taken
8137                        // care of renaming the package; only do it here if
8138                        // it is not already done.
8139                        pkg.setPackageName(renamed);
8140                    }
8141
8142                } else {
8143                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8144                        if ((origPackage = mSettings.peekPackageLPr(
8145                                pkg.mOriginalPackages.get(i))) != null) {
8146                            // We do have the package already installed under its
8147                            // original name...  should we use it?
8148                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8149                                // New package is not compatible with original.
8150                                origPackage = null;
8151                                continue;
8152                            } else if (origPackage.sharedUser != null) {
8153                                // Make sure uid is compatible between packages.
8154                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8155                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8156                                            + " to " + pkg.packageName + ": old uid "
8157                                            + origPackage.sharedUser.name
8158                                            + " differs from " + pkg.mSharedUserId);
8159                                    origPackage = null;
8160                                    continue;
8161                                }
8162                                // TODO: Add case when shared user id is added [b/28144775]
8163                            } else {
8164                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8165                                        + pkg.packageName + " to old name " + origPackage.name);
8166                            }
8167                            break;
8168                        }
8169                    }
8170                }
8171            }
8172
8173            if (mTransferedPackages.contains(pkg.packageName)) {
8174                Slog.w(TAG, "Package " + pkg.packageName
8175                        + " was transferred to another, but its .apk remains");
8176            }
8177
8178            // See comments in nonMutatedPs declaration
8179            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8180                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8181                if (foundPs != null) {
8182                    nonMutatedPs = new PackageSetting(foundPs);
8183                }
8184            }
8185
8186            // Just create the setting, don't add it yet. For already existing packages
8187            // the PkgSetting exists already and doesn't have to be created.
8188            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8189                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8190                    pkg.applicationInfo.primaryCpuAbi,
8191                    pkg.applicationInfo.secondaryCpuAbi,
8192                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8193                    user, false);
8194            if (pkgSetting == null) {
8195                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8196                        "Creating application package " + pkg.packageName + " failed");
8197            }
8198
8199            if (pkgSetting.origPackage != null) {
8200                // If we are first transitioning from an original package,
8201                // fix up the new package's name now.  We need to do this after
8202                // looking up the package under its new name, so getPackageLP
8203                // can take care of fiddling things correctly.
8204                pkg.setPackageName(origPackage.name);
8205
8206                // File a report about this.
8207                String msg = "New package " + pkgSetting.realName
8208                        + " renamed to replace old package " + pkgSetting.name;
8209                reportSettingsProblem(Log.WARN, msg);
8210
8211                // Make a note of it.
8212                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8213                    mTransferedPackages.add(origPackage.name);
8214                }
8215
8216                // No longer need to retain this.
8217                pkgSetting.origPackage = null;
8218            }
8219
8220            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8221                // Make a note of it.
8222                mTransferedPackages.add(pkg.packageName);
8223            }
8224
8225            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8226                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8227            }
8228
8229            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8230                // Check all shared libraries and map to their actual file path.
8231                // We only do this here for apps not on a system dir, because those
8232                // are the only ones that can fail an install due to this.  We
8233                // will take care of the system apps by updating all of their
8234                // library paths after the scan is done.
8235                updateSharedLibrariesLPw(pkg, null);
8236            }
8237
8238            if (mFoundPolicyFile) {
8239                SELinuxMMAC.assignSeinfoValue(pkg);
8240            }
8241
8242            pkg.applicationInfo.uid = pkgSetting.appId;
8243            pkg.mExtras = pkgSetting;
8244            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8245                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8246                    // We just determined the app is signed correctly, so bring
8247                    // over the latest parsed certs.
8248                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8249                } else {
8250                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8251                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8252                                "Package " + pkg.packageName + " upgrade keys do not match the "
8253                                + "previously installed version");
8254                    } else {
8255                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8256                        String msg = "System package " + pkg.packageName
8257                            + " signature changed; retaining data.";
8258                        reportSettingsProblem(Log.WARN, msg);
8259                    }
8260                }
8261            } else {
8262                try {
8263                    verifySignaturesLP(pkgSetting, pkg);
8264                    // We just determined the app is signed correctly, so bring
8265                    // over the latest parsed certs.
8266                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8267                } catch (PackageManagerException e) {
8268                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8269                        throw e;
8270                    }
8271                    // The signature has changed, but this package is in the system
8272                    // image...  let's recover!
8273                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8274                    // However...  if this package is part of a shared user, but it
8275                    // doesn't match the signature of the shared user, let's fail.
8276                    // What this means is that you can't change the signatures
8277                    // associated with an overall shared user, which doesn't seem all
8278                    // that unreasonable.
8279                    if (pkgSetting.sharedUser != null) {
8280                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8281                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8282                            throw new PackageManagerException(
8283                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8284                                            "Signature mismatch for shared user: "
8285                                            + pkgSetting.sharedUser);
8286                        }
8287                    }
8288                    // File a report about this.
8289                    String msg = "System package " + pkg.packageName
8290                        + " signature changed; retaining data.";
8291                    reportSettingsProblem(Log.WARN, msg);
8292                }
8293            }
8294            // Verify that this new package doesn't have any content providers
8295            // that conflict with existing packages.  Only do this if the
8296            // package isn't already installed, since we don't want to break
8297            // things that are installed.
8298            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8299                final int N = pkg.providers.size();
8300                int i;
8301                for (i=0; i<N; i++) {
8302                    PackageParser.Provider p = pkg.providers.get(i);
8303                    if (p.info.authority != null) {
8304                        String names[] = p.info.authority.split(";");
8305                        for (int j = 0; j < names.length; j++) {
8306                            if (mProvidersByAuthority.containsKey(names[j])) {
8307                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8308                                final String otherPackageName =
8309                                        ((other != null && other.getComponentName() != null) ?
8310                                                other.getComponentName().getPackageName() : "?");
8311                                throw new PackageManagerException(
8312                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8313                                                "Can't install because provider name " + names[j]
8314                                                + " (in package " + pkg.applicationInfo.packageName
8315                                                + ") is already used by " + otherPackageName);
8316                            }
8317                        }
8318                    }
8319                }
8320            }
8321
8322            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8323                // This package wants to adopt ownership of permissions from
8324                // another package.
8325                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8326                    final String origName = pkg.mAdoptPermissions.get(i);
8327                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8328                    if (orig != null) {
8329                        if (verifyPackageUpdateLPr(orig, pkg)) {
8330                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8331                                    + pkg.packageName);
8332                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8333                        }
8334                    }
8335                }
8336            }
8337        }
8338
8339        final String pkgName = pkg.packageName;
8340
8341        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8342        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8343        pkg.applicationInfo.processName = fixProcessName(
8344                pkg.applicationInfo.packageName,
8345                pkg.applicationInfo.processName,
8346                pkg.applicationInfo.uid);
8347
8348        if (pkg != mPlatformPackage) {
8349            // Get all of our default paths setup
8350            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8351        }
8352
8353        final String path = scanFile.getPath();
8354        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8355
8356        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8357            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8358
8359            // Some system apps still use directory structure for native libraries
8360            // in which case we might end up not detecting abi solely based on apk
8361            // structure. Try to detect abi based on directory structure.
8362            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8363                    pkg.applicationInfo.primaryCpuAbi == null) {
8364                setBundledAppAbisAndRoots(pkg, pkgSetting);
8365                setNativeLibraryPaths(pkg);
8366            }
8367
8368        } else {
8369            if ((scanFlags & SCAN_MOVE) != 0) {
8370                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8371                // but we already have this packages package info in the PackageSetting. We just
8372                // use that and derive the native library path based on the new codepath.
8373                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8374                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8375            }
8376
8377            // Set native library paths again. For moves, the path will be updated based on the
8378            // ABIs we've determined above. For non-moves, the path will be updated based on the
8379            // ABIs we determined during compilation, but the path will depend on the final
8380            // package path (after the rename away from the stage path).
8381            setNativeLibraryPaths(pkg);
8382        }
8383
8384        // This is a special case for the "system" package, where the ABI is
8385        // dictated by the zygote configuration (and init.rc). We should keep track
8386        // of this ABI so that we can deal with "normal" applications that run under
8387        // the same UID correctly.
8388        if (mPlatformPackage == pkg) {
8389            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8390                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8391        }
8392
8393        // If there's a mismatch between the abi-override in the package setting
8394        // and the abiOverride specified for the install. Warn about this because we
8395        // would've already compiled the app without taking the package setting into
8396        // account.
8397        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8398            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8399                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8400                        " for package " + pkg.packageName);
8401            }
8402        }
8403
8404        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8405        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8406        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8407
8408        // Copy the derived override back to the parsed package, so that we can
8409        // update the package settings accordingly.
8410        pkg.cpuAbiOverride = cpuAbiOverride;
8411
8412        if (DEBUG_ABI_SELECTION) {
8413            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8414                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8415                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8416        }
8417
8418        // Push the derived path down into PackageSettings so we know what to
8419        // clean up at uninstall time.
8420        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8421
8422        if (DEBUG_ABI_SELECTION) {
8423            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8424                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8425                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8426        }
8427
8428        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8429            // We don't do this here during boot because we can do it all
8430            // at once after scanning all existing packages.
8431            //
8432            // We also do this *before* we perform dexopt on this package, so that
8433            // we can avoid redundant dexopts, and also to make sure we've got the
8434            // code and package path correct.
8435            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8436                    pkg, true /* boot complete */);
8437        }
8438
8439        if (mFactoryTest && pkg.requestedPermissions.contains(
8440                android.Manifest.permission.FACTORY_TEST)) {
8441            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8442        }
8443
8444        if (isSystemApp(pkg)) {
8445            pkgSetting.isOrphaned = true;
8446        }
8447
8448        ArrayList<PackageParser.Package> clientLibPkgs = null;
8449
8450        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8451            if (nonMutatedPs != null) {
8452                synchronized (mPackages) {
8453                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8454                }
8455            }
8456            return pkg;
8457        }
8458
8459        // Only privileged apps and updated privileged apps can add child packages.
8460        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8461            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8462                throw new PackageManagerException("Only privileged apps and updated "
8463                        + "privileged apps can add child packages. Ignoring package "
8464                        + pkg.packageName);
8465            }
8466            final int childCount = pkg.childPackages.size();
8467            for (int i = 0; i < childCount; i++) {
8468                PackageParser.Package childPkg = pkg.childPackages.get(i);
8469                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8470                        childPkg.packageName)) {
8471                    throw new PackageManagerException("Cannot override a child package of "
8472                            + "another disabled system app. Ignoring package " + pkg.packageName);
8473                }
8474            }
8475        }
8476
8477        // writer
8478        synchronized (mPackages) {
8479            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8480                // Only system apps can add new shared libraries.
8481                if (pkg.libraryNames != null) {
8482                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8483                        String name = pkg.libraryNames.get(i);
8484                        boolean allowed = false;
8485                        if (pkg.isUpdatedSystemApp()) {
8486                            // New library entries can only be added through the
8487                            // system image.  This is important to get rid of a lot
8488                            // of nasty edge cases: for example if we allowed a non-
8489                            // system update of the app to add a library, then uninstalling
8490                            // the update would make the library go away, and assumptions
8491                            // we made such as through app install filtering would now
8492                            // have allowed apps on the device which aren't compatible
8493                            // with it.  Better to just have the restriction here, be
8494                            // conservative, and create many fewer cases that can negatively
8495                            // impact the user experience.
8496                            final PackageSetting sysPs = mSettings
8497                                    .getDisabledSystemPkgLPr(pkg.packageName);
8498                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8499                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8500                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8501                                        allowed = true;
8502                                        break;
8503                                    }
8504                                }
8505                            }
8506                        } else {
8507                            allowed = true;
8508                        }
8509                        if (allowed) {
8510                            if (!mSharedLibraries.containsKey(name)) {
8511                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8512                            } else if (!name.equals(pkg.packageName)) {
8513                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8514                                        + name + " already exists; skipping");
8515                            }
8516                        } else {
8517                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8518                                    + name + " that is not declared on system image; skipping");
8519                        }
8520                    }
8521                    if ((scanFlags & SCAN_BOOTING) == 0) {
8522                        // If we are not booting, we need to update any applications
8523                        // that are clients of our shared library.  If we are booting,
8524                        // this will all be done once the scan is complete.
8525                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8526                    }
8527                }
8528            }
8529        }
8530
8531        if ((scanFlags & SCAN_BOOTING) != 0) {
8532            // No apps can run during boot scan, so they don't need to be frozen
8533        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8534            // Caller asked to not kill app, so it's probably not frozen
8535        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8536            // Caller asked us to ignore frozen check for some reason; they
8537            // probably didn't know the package name
8538        } else {
8539            // We're doing major surgery on this package, so it better be frozen
8540            // right now to keep it from launching
8541            checkPackageFrozen(pkgName);
8542        }
8543
8544        // Also need to kill any apps that are dependent on the library.
8545        if (clientLibPkgs != null) {
8546            for (int i=0; i<clientLibPkgs.size(); i++) {
8547                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8548                killApplication(clientPkg.applicationInfo.packageName,
8549                        clientPkg.applicationInfo.uid, "update lib");
8550            }
8551        }
8552
8553        // Make sure we're not adding any bogus keyset info
8554        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8555        ksms.assertScannedPackageValid(pkg);
8556
8557        // writer
8558        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8559
8560        boolean createIdmapFailed = false;
8561        synchronized (mPackages) {
8562            // We don't expect installation to fail beyond this point
8563
8564            if (pkgSetting.pkg != null) {
8565                // Note that |user| might be null during the initial boot scan. If a codePath
8566                // for an app has changed during a boot scan, it's due to an app update that's
8567                // part of the system partition and marker changes must be applied to all users.
8568                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8569                    (user != null) ? user : UserHandle.ALL);
8570            }
8571
8572            // Add the new setting to mSettings
8573            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8574            // Add the new setting to mPackages
8575            mPackages.put(pkg.applicationInfo.packageName, pkg);
8576            // Make sure we don't accidentally delete its data.
8577            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8578            while (iter.hasNext()) {
8579                PackageCleanItem item = iter.next();
8580                if (pkgName.equals(item.packageName)) {
8581                    iter.remove();
8582                }
8583            }
8584
8585            // Take care of first install / last update times.
8586            if (currentTime != 0) {
8587                if (pkgSetting.firstInstallTime == 0) {
8588                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8589                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8590                    pkgSetting.lastUpdateTime = currentTime;
8591                }
8592            } else if (pkgSetting.firstInstallTime == 0) {
8593                // We need *something*.  Take time time stamp of the file.
8594                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8595            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8596                if (scanFileTime != pkgSetting.timeStamp) {
8597                    // A package on the system image has changed; consider this
8598                    // to be an update.
8599                    pkgSetting.lastUpdateTime = scanFileTime;
8600                }
8601            }
8602
8603            // Add the package's KeySets to the global KeySetManagerService
8604            ksms.addScannedPackageLPw(pkg);
8605
8606            int N = pkg.providers.size();
8607            StringBuilder r = null;
8608            int i;
8609            for (i=0; i<N; i++) {
8610                PackageParser.Provider p = pkg.providers.get(i);
8611                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8612                        p.info.processName, pkg.applicationInfo.uid);
8613                mProviders.addProvider(p);
8614                p.syncable = p.info.isSyncable;
8615                if (p.info.authority != null) {
8616                    String names[] = p.info.authority.split(";");
8617                    p.info.authority = null;
8618                    for (int j = 0; j < names.length; j++) {
8619                        if (j == 1 && p.syncable) {
8620                            // We only want the first authority for a provider to possibly be
8621                            // syncable, so if we already added this provider using a different
8622                            // authority clear the syncable flag. We copy the provider before
8623                            // changing it because the mProviders object contains a reference
8624                            // to a provider that we don't want to change.
8625                            // Only do this for the second authority since the resulting provider
8626                            // object can be the same for all future authorities for this provider.
8627                            p = new PackageParser.Provider(p);
8628                            p.syncable = false;
8629                        }
8630                        if (!mProvidersByAuthority.containsKey(names[j])) {
8631                            mProvidersByAuthority.put(names[j], p);
8632                            if (p.info.authority == null) {
8633                                p.info.authority = names[j];
8634                            } else {
8635                                p.info.authority = p.info.authority + ";" + names[j];
8636                            }
8637                            if (DEBUG_PACKAGE_SCANNING) {
8638                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8639                                    Log.d(TAG, "Registered content provider: " + names[j]
8640                                            + ", className = " + p.info.name + ", isSyncable = "
8641                                            + p.info.isSyncable);
8642                            }
8643                        } else {
8644                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8645                            Slog.w(TAG, "Skipping provider name " + names[j] +
8646                                    " (in package " + pkg.applicationInfo.packageName +
8647                                    "): name already used by "
8648                                    + ((other != null && other.getComponentName() != null)
8649                                            ? other.getComponentName().getPackageName() : "?"));
8650                        }
8651                    }
8652                }
8653                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8654                    if (r == null) {
8655                        r = new StringBuilder(256);
8656                    } else {
8657                        r.append(' ');
8658                    }
8659                    r.append(p.info.name);
8660                }
8661            }
8662            if (r != null) {
8663                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8664            }
8665
8666            N = pkg.services.size();
8667            r = null;
8668            for (i=0; i<N; i++) {
8669                PackageParser.Service s = pkg.services.get(i);
8670                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8671                        s.info.processName, pkg.applicationInfo.uid);
8672                mServices.addService(s);
8673                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8674                    if (r == null) {
8675                        r = new StringBuilder(256);
8676                    } else {
8677                        r.append(' ');
8678                    }
8679                    r.append(s.info.name);
8680                }
8681            }
8682            if (r != null) {
8683                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8684            }
8685
8686            N = pkg.receivers.size();
8687            r = null;
8688            for (i=0; i<N; i++) {
8689                PackageParser.Activity a = pkg.receivers.get(i);
8690                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8691                        a.info.processName, pkg.applicationInfo.uid);
8692                mReceivers.addActivity(a, "receiver");
8693                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8694                    if (r == null) {
8695                        r = new StringBuilder(256);
8696                    } else {
8697                        r.append(' ');
8698                    }
8699                    r.append(a.info.name);
8700                }
8701            }
8702            if (r != null) {
8703                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8704            }
8705
8706            N = pkg.activities.size();
8707            r = null;
8708            for (i=0; i<N; i++) {
8709                PackageParser.Activity a = pkg.activities.get(i);
8710                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8711                        a.info.processName, pkg.applicationInfo.uid);
8712                mActivities.addActivity(a, "activity");
8713                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8714                    if (r == null) {
8715                        r = new StringBuilder(256);
8716                    } else {
8717                        r.append(' ');
8718                    }
8719                    r.append(a.info.name);
8720                }
8721            }
8722            if (r != null) {
8723                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8724            }
8725
8726            N = pkg.permissionGroups.size();
8727            r = null;
8728            for (i=0; i<N; i++) {
8729                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8730                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8731                final String curPackageName = cur == null ? null : cur.info.packageName;
8732                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8733                if (cur == null || isPackageUpdate) {
8734                    mPermissionGroups.put(pg.info.name, pg);
8735                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8736                        if (r == null) {
8737                            r = new StringBuilder(256);
8738                        } else {
8739                            r.append(' ');
8740                        }
8741                        if (isPackageUpdate) {
8742                            r.append("UPD:");
8743                        }
8744                        r.append(pg.info.name);
8745                    }
8746                } else {
8747                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8748                            + pg.info.packageName + " ignored: original from "
8749                            + cur.info.packageName);
8750                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8751                        if (r == null) {
8752                            r = new StringBuilder(256);
8753                        } else {
8754                            r.append(' ');
8755                        }
8756                        r.append("DUP:");
8757                        r.append(pg.info.name);
8758                    }
8759                }
8760            }
8761            if (r != null) {
8762                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8763            }
8764
8765            N = pkg.permissions.size();
8766            r = null;
8767            for (i=0; i<N; i++) {
8768                PackageParser.Permission p = pkg.permissions.get(i);
8769
8770                // Assume by default that we did not install this permission into the system.
8771                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8772
8773                // Now that permission groups have a special meaning, we ignore permission
8774                // groups for legacy apps to prevent unexpected behavior. In particular,
8775                // permissions for one app being granted to someone just becase they happen
8776                // to be in a group defined by another app (before this had no implications).
8777                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8778                    p.group = mPermissionGroups.get(p.info.group);
8779                    // Warn for a permission in an unknown group.
8780                    if (p.info.group != null && p.group == null) {
8781                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8782                                + p.info.packageName + " in an unknown group " + p.info.group);
8783                    }
8784                }
8785
8786                ArrayMap<String, BasePermission> permissionMap =
8787                        p.tree ? mSettings.mPermissionTrees
8788                                : mSettings.mPermissions;
8789                BasePermission bp = permissionMap.get(p.info.name);
8790
8791                // Allow system apps to redefine non-system permissions
8792                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8793                    final boolean currentOwnerIsSystem = (bp.perm != null
8794                            && isSystemApp(bp.perm.owner));
8795                    if (isSystemApp(p.owner)) {
8796                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8797                            // It's a built-in permission and no owner, take ownership now
8798                            bp.packageSetting = pkgSetting;
8799                            bp.perm = p;
8800                            bp.uid = pkg.applicationInfo.uid;
8801                            bp.sourcePackage = p.info.packageName;
8802                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8803                        } else if (!currentOwnerIsSystem) {
8804                            String msg = "New decl " + p.owner + " of permission  "
8805                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8806                            reportSettingsProblem(Log.WARN, msg);
8807                            bp = null;
8808                        }
8809                    }
8810                }
8811
8812                if (bp == null) {
8813                    bp = new BasePermission(p.info.name, p.info.packageName,
8814                            BasePermission.TYPE_NORMAL);
8815                    permissionMap.put(p.info.name, bp);
8816                }
8817
8818                if (bp.perm == null) {
8819                    if (bp.sourcePackage == null
8820                            || bp.sourcePackage.equals(p.info.packageName)) {
8821                        BasePermission tree = findPermissionTreeLP(p.info.name);
8822                        if (tree == null
8823                                || tree.sourcePackage.equals(p.info.packageName)) {
8824                            bp.packageSetting = pkgSetting;
8825                            bp.perm = p;
8826                            bp.uid = pkg.applicationInfo.uid;
8827                            bp.sourcePackage = p.info.packageName;
8828                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8829                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8830                                if (r == null) {
8831                                    r = new StringBuilder(256);
8832                                } else {
8833                                    r.append(' ');
8834                                }
8835                                r.append(p.info.name);
8836                            }
8837                        } else {
8838                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8839                                    + p.info.packageName + " ignored: base tree "
8840                                    + tree.name + " is from package "
8841                                    + tree.sourcePackage);
8842                        }
8843                    } else {
8844                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8845                                + p.info.packageName + " ignored: original from "
8846                                + bp.sourcePackage);
8847                    }
8848                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8849                    if (r == null) {
8850                        r = new StringBuilder(256);
8851                    } else {
8852                        r.append(' ');
8853                    }
8854                    r.append("DUP:");
8855                    r.append(p.info.name);
8856                }
8857                if (bp.perm == p) {
8858                    bp.protectionLevel = p.info.protectionLevel;
8859                }
8860            }
8861
8862            if (r != null) {
8863                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8864            }
8865
8866            N = pkg.instrumentation.size();
8867            r = null;
8868            for (i=0; i<N; i++) {
8869                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8870                a.info.packageName = pkg.applicationInfo.packageName;
8871                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8872                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8873                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8874                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8875                a.info.dataDir = pkg.applicationInfo.dataDir;
8876                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8877                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8878
8879                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8880                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8881                mInstrumentation.put(a.getComponentName(), a);
8882                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8883                    if (r == null) {
8884                        r = new StringBuilder(256);
8885                    } else {
8886                        r.append(' ');
8887                    }
8888                    r.append(a.info.name);
8889                }
8890            }
8891            if (r != null) {
8892                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8893            }
8894
8895            if (pkg.protectedBroadcasts != null) {
8896                N = pkg.protectedBroadcasts.size();
8897                for (i=0; i<N; i++) {
8898                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8899                }
8900            }
8901
8902            pkgSetting.setTimeStamp(scanFileTime);
8903
8904            // Create idmap files for pairs of (packages, overlay packages).
8905            // Note: "android", ie framework-res.apk, is handled by native layers.
8906            if (pkg.mOverlayTarget != null) {
8907                // This is an overlay package.
8908                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8909                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8910                        mOverlays.put(pkg.mOverlayTarget,
8911                                new ArrayMap<String, PackageParser.Package>());
8912                    }
8913                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8914                    map.put(pkg.packageName, pkg);
8915                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8916                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8917                        createIdmapFailed = true;
8918                    }
8919                }
8920            } else if (mOverlays.containsKey(pkg.packageName) &&
8921                    !pkg.packageName.equals("android")) {
8922                // This is a regular package, with one or more known overlay packages.
8923                createIdmapsForPackageLI(pkg);
8924            }
8925        }
8926
8927        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8928
8929        if (createIdmapFailed) {
8930            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8931                    "scanPackageLI failed to createIdmap");
8932        }
8933        return pkg;
8934    }
8935
8936    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8937            PackageParser.Package update, UserHandle user) {
8938        if (existing.applicationInfo == null || update.applicationInfo == null) {
8939            // This isn't due to an app installation.
8940            return;
8941        }
8942
8943        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8944        final File newCodePath = new File(update.applicationInfo.getCodePath());
8945
8946        // The codePath hasn't changed, so there's nothing for us to do.
8947        if (Objects.equals(oldCodePath, newCodePath)) {
8948            return;
8949        }
8950
8951        File canonicalNewCodePath;
8952        try {
8953            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
8954        } catch (IOException e) {
8955            Slog.w(TAG, "Failed to get canonical path.", e);
8956            return;
8957        }
8958
8959        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
8960        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
8961        // that the last component of the path (i.e, the name) doesn't need canonicalization
8962        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
8963        // but may change in the future. Hopefully this function won't exist at that point.
8964        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
8965                oldCodePath.getName());
8966
8967        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
8968        // with "@".
8969        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
8970        if (!oldMarkerPrefix.endsWith("@")) {
8971            oldMarkerPrefix += "@";
8972        }
8973        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
8974        if (!newMarkerPrefix.endsWith("@")) {
8975            newMarkerPrefix += "@";
8976        }
8977
8978        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
8979        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
8980        for (String updatedPath : updatedPaths) {
8981            String updatedPathName = new File(updatedPath).getName();
8982            markerSuffixes.add(updatedPathName.replace('/', '@'));
8983        }
8984
8985        for (int userId : resolveUserIds(user.getIdentifier())) {
8986            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
8987
8988            for (String markerSuffix : markerSuffixes) {
8989                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
8990                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
8991                if (oldForeignUseMark.exists()) {
8992                    try {
8993                        Os.rename(oldForeignUseMark.getAbsolutePath(),
8994                                newForeignUseMark.getAbsolutePath());
8995                    } catch (ErrnoException e) {
8996                        Slog.w(TAG, "Failed to rename foreign use marker", e);
8997                        oldForeignUseMark.delete();
8998                    }
8999                }
9000            }
9001        }
9002    }
9003
9004    /**
9005     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9006     * is derived purely on the basis of the contents of {@code scanFile} and
9007     * {@code cpuAbiOverride}.
9008     *
9009     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9010     */
9011    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9012                                 String cpuAbiOverride, boolean extractLibs)
9013            throws PackageManagerException {
9014        // TODO: We can probably be smarter about this stuff. For installed apps,
9015        // we can calculate this information at install time once and for all. For
9016        // system apps, we can probably assume that this information doesn't change
9017        // after the first boot scan. As things stand, we do lots of unnecessary work.
9018
9019        // Give ourselves some initial paths; we'll come back for another
9020        // pass once we've determined ABI below.
9021        setNativeLibraryPaths(pkg);
9022
9023        // We would never need to extract libs for forward-locked and external packages,
9024        // since the container service will do it for us. We shouldn't attempt to
9025        // extract libs from system app when it was not updated.
9026        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9027                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9028            extractLibs = false;
9029        }
9030
9031        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9032        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9033
9034        NativeLibraryHelper.Handle handle = null;
9035        try {
9036            handle = NativeLibraryHelper.Handle.create(pkg);
9037            // TODO(multiArch): This can be null for apps that didn't go through the
9038            // usual installation process. We can calculate it again, like we
9039            // do during install time.
9040            //
9041            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9042            // unnecessary.
9043            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9044
9045            // Null out the abis so that they can be recalculated.
9046            pkg.applicationInfo.primaryCpuAbi = null;
9047            pkg.applicationInfo.secondaryCpuAbi = null;
9048            if (isMultiArch(pkg.applicationInfo)) {
9049                // Warn if we've set an abiOverride for multi-lib packages..
9050                // By definition, we need to copy both 32 and 64 bit libraries for
9051                // such packages.
9052                if (pkg.cpuAbiOverride != null
9053                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9054                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9055                }
9056
9057                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9058                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9059                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9060                    if (extractLibs) {
9061                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9062                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9063                                useIsaSpecificSubdirs);
9064                    } else {
9065                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9066                    }
9067                }
9068
9069                maybeThrowExceptionForMultiArchCopy(
9070                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9071
9072                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9073                    if (extractLibs) {
9074                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9075                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9076                                useIsaSpecificSubdirs);
9077                    } else {
9078                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9079                    }
9080                }
9081
9082                maybeThrowExceptionForMultiArchCopy(
9083                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9084
9085                if (abi64 >= 0) {
9086                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9087                }
9088
9089                if (abi32 >= 0) {
9090                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9091                    if (abi64 >= 0) {
9092                        if (pkg.use32bitAbi) {
9093                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9094                            pkg.applicationInfo.primaryCpuAbi = abi;
9095                        } else {
9096                            pkg.applicationInfo.secondaryCpuAbi = abi;
9097                        }
9098                    } else {
9099                        pkg.applicationInfo.primaryCpuAbi = abi;
9100                    }
9101                }
9102
9103            } else {
9104                String[] abiList = (cpuAbiOverride != null) ?
9105                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9106
9107                // Enable gross and lame hacks for apps that are built with old
9108                // SDK tools. We must scan their APKs for renderscript bitcode and
9109                // not launch them if it's present. Don't bother checking on devices
9110                // that don't have 64 bit support.
9111                boolean needsRenderScriptOverride = false;
9112                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9113                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9114                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9115                    needsRenderScriptOverride = true;
9116                }
9117
9118                final int copyRet;
9119                if (extractLibs) {
9120                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9121                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9122                } else {
9123                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9124                }
9125
9126                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9127                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9128                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9129                }
9130
9131                if (copyRet >= 0) {
9132                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9133                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9134                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9135                } else if (needsRenderScriptOverride) {
9136                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9137                }
9138            }
9139        } catch (IOException ioe) {
9140            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9141        } finally {
9142            IoUtils.closeQuietly(handle);
9143        }
9144
9145        // Now that we've calculated the ABIs and determined if it's an internal app,
9146        // we will go ahead and populate the nativeLibraryPath.
9147        setNativeLibraryPaths(pkg);
9148    }
9149
9150    /**
9151     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9152     * i.e, so that all packages can be run inside a single process if required.
9153     *
9154     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9155     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9156     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9157     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9158     * updating a package that belongs to a shared user.
9159     *
9160     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9161     * adds unnecessary complexity.
9162     */
9163    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9164            PackageParser.Package scannedPackage, boolean bootComplete) {
9165        String requiredInstructionSet = null;
9166        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9167            requiredInstructionSet = VMRuntime.getInstructionSet(
9168                     scannedPackage.applicationInfo.primaryCpuAbi);
9169        }
9170
9171        PackageSetting requirer = null;
9172        for (PackageSetting ps : packagesForUser) {
9173            // If packagesForUser contains scannedPackage, we skip it. This will happen
9174            // when scannedPackage is an update of an existing package. Without this check,
9175            // we will never be able to change the ABI of any package belonging to a shared
9176            // user, even if it's compatible with other packages.
9177            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9178                if (ps.primaryCpuAbiString == null) {
9179                    continue;
9180                }
9181
9182                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9183                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9184                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9185                    // this but there's not much we can do.
9186                    String errorMessage = "Instruction set mismatch, "
9187                            + ((requirer == null) ? "[caller]" : requirer)
9188                            + " requires " + requiredInstructionSet + " whereas " + ps
9189                            + " requires " + instructionSet;
9190                    Slog.w(TAG, errorMessage);
9191                }
9192
9193                if (requiredInstructionSet == null) {
9194                    requiredInstructionSet = instructionSet;
9195                    requirer = ps;
9196                }
9197            }
9198        }
9199
9200        if (requiredInstructionSet != null) {
9201            String adjustedAbi;
9202            if (requirer != null) {
9203                // requirer != null implies that either scannedPackage was null or that scannedPackage
9204                // did not require an ABI, in which case we have to adjust scannedPackage to match
9205                // the ABI of the set (which is the same as requirer's ABI)
9206                adjustedAbi = requirer.primaryCpuAbiString;
9207                if (scannedPackage != null) {
9208                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9209                }
9210            } else {
9211                // requirer == null implies that we're updating all ABIs in the set to
9212                // match scannedPackage.
9213                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9214            }
9215
9216            for (PackageSetting ps : packagesForUser) {
9217                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9218                    if (ps.primaryCpuAbiString != null) {
9219                        continue;
9220                    }
9221
9222                    ps.primaryCpuAbiString = adjustedAbi;
9223                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9224                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9225                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9226                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9227                                + " (requirer="
9228                                + (requirer == null ? "null" : requirer.pkg.packageName)
9229                                + ", scannedPackage="
9230                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9231                                + ")");
9232                        try {
9233                            mInstaller.rmdex(ps.codePathString,
9234                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9235                        } catch (InstallerException ignored) {
9236                        }
9237                    }
9238                }
9239            }
9240        }
9241    }
9242
9243    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9244        synchronized (mPackages) {
9245            mResolverReplaced = true;
9246            // Set up information for custom user intent resolution activity.
9247            mResolveActivity.applicationInfo = pkg.applicationInfo;
9248            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9249            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9250            mResolveActivity.processName = pkg.applicationInfo.packageName;
9251            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9252            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9253                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9254            mResolveActivity.theme = 0;
9255            mResolveActivity.exported = true;
9256            mResolveActivity.enabled = true;
9257            mResolveInfo.activityInfo = mResolveActivity;
9258            mResolveInfo.priority = 0;
9259            mResolveInfo.preferredOrder = 0;
9260            mResolveInfo.match = 0;
9261            mResolveComponentName = mCustomResolverComponentName;
9262            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9263                    mResolveComponentName);
9264        }
9265    }
9266
9267    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9268        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9269
9270        // Set up information for ephemeral installer activity
9271        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9272        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9273        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9274        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9275        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9276        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9277                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9278        mEphemeralInstallerActivity.theme = 0;
9279        mEphemeralInstallerActivity.exported = true;
9280        mEphemeralInstallerActivity.enabled = true;
9281        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9282        mEphemeralInstallerInfo.priority = 0;
9283        mEphemeralInstallerInfo.preferredOrder = 1;
9284        mEphemeralInstallerInfo.isDefault = true;
9285        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9286                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9287
9288        if (DEBUG_EPHEMERAL) {
9289            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9290        }
9291    }
9292
9293    private static String calculateBundledApkRoot(final String codePathString) {
9294        final File codePath = new File(codePathString);
9295        final File codeRoot;
9296        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9297            codeRoot = Environment.getRootDirectory();
9298        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9299            codeRoot = Environment.getOemDirectory();
9300        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9301            codeRoot = Environment.getVendorDirectory();
9302        } else {
9303            // Unrecognized code path; take its top real segment as the apk root:
9304            // e.g. /something/app/blah.apk => /something
9305            try {
9306                File f = codePath.getCanonicalFile();
9307                File parent = f.getParentFile();    // non-null because codePath is a file
9308                File tmp;
9309                while ((tmp = parent.getParentFile()) != null) {
9310                    f = parent;
9311                    parent = tmp;
9312                }
9313                codeRoot = f;
9314                Slog.w(TAG, "Unrecognized code path "
9315                        + codePath + " - using " + codeRoot);
9316            } catch (IOException e) {
9317                // Can't canonicalize the code path -- shenanigans?
9318                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9319                return Environment.getRootDirectory().getPath();
9320            }
9321        }
9322        return codeRoot.getPath();
9323    }
9324
9325    /**
9326     * Derive and set the location of native libraries for the given package,
9327     * which varies depending on where and how the package was installed.
9328     */
9329    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9330        final ApplicationInfo info = pkg.applicationInfo;
9331        final String codePath = pkg.codePath;
9332        final File codeFile = new File(codePath);
9333        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9334        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9335
9336        info.nativeLibraryRootDir = null;
9337        info.nativeLibraryRootRequiresIsa = false;
9338        info.nativeLibraryDir = null;
9339        info.secondaryNativeLibraryDir = null;
9340
9341        if (isApkFile(codeFile)) {
9342            // Monolithic install
9343            if (bundledApp) {
9344                // If "/system/lib64/apkname" exists, assume that is the per-package
9345                // native library directory to use; otherwise use "/system/lib/apkname".
9346                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9347                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9348                        getPrimaryInstructionSet(info));
9349
9350                // This is a bundled system app so choose the path based on the ABI.
9351                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9352                // is just the default path.
9353                final String apkName = deriveCodePathName(codePath);
9354                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9355                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9356                        apkName).getAbsolutePath();
9357
9358                if (info.secondaryCpuAbi != null) {
9359                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9360                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9361                            secondaryLibDir, apkName).getAbsolutePath();
9362                }
9363            } else if (asecApp) {
9364                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9365                        .getAbsolutePath();
9366            } else {
9367                final String apkName = deriveCodePathName(codePath);
9368                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9369                        .getAbsolutePath();
9370            }
9371
9372            info.nativeLibraryRootRequiresIsa = false;
9373            info.nativeLibraryDir = info.nativeLibraryRootDir;
9374        } else {
9375            // Cluster install
9376            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9377            info.nativeLibraryRootRequiresIsa = true;
9378
9379            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9380                    getPrimaryInstructionSet(info)).getAbsolutePath();
9381
9382            if (info.secondaryCpuAbi != null) {
9383                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9384                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9385            }
9386        }
9387    }
9388
9389    /**
9390     * Calculate the abis and roots for a bundled app. These can uniquely
9391     * be determined from the contents of the system partition, i.e whether
9392     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9393     * of this information, and instead assume that the system was built
9394     * sensibly.
9395     */
9396    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9397                                           PackageSetting pkgSetting) {
9398        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9399
9400        // If "/system/lib64/apkname" exists, assume that is the per-package
9401        // native library directory to use; otherwise use "/system/lib/apkname".
9402        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9403        setBundledAppAbi(pkg, apkRoot, apkName);
9404        // pkgSetting might be null during rescan following uninstall of updates
9405        // to a bundled app, so accommodate that possibility.  The settings in
9406        // that case will be established later from the parsed package.
9407        //
9408        // If the settings aren't null, sync them up with what we've just derived.
9409        // note that apkRoot isn't stored in the package settings.
9410        if (pkgSetting != null) {
9411            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9412            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9413        }
9414    }
9415
9416    /**
9417     * Deduces the ABI of a bundled app and sets the relevant fields on the
9418     * parsed pkg object.
9419     *
9420     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9421     *        under which system libraries are installed.
9422     * @param apkName the name of the installed package.
9423     */
9424    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9425        final File codeFile = new File(pkg.codePath);
9426
9427        final boolean has64BitLibs;
9428        final boolean has32BitLibs;
9429        if (isApkFile(codeFile)) {
9430            // Monolithic install
9431            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9432            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9433        } else {
9434            // Cluster install
9435            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9436            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9437                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9438                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9439                has64BitLibs = (new File(rootDir, isa)).exists();
9440            } else {
9441                has64BitLibs = false;
9442            }
9443            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9444                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9445                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9446                has32BitLibs = (new File(rootDir, isa)).exists();
9447            } else {
9448                has32BitLibs = false;
9449            }
9450        }
9451
9452        if (has64BitLibs && !has32BitLibs) {
9453            // The package has 64 bit libs, but not 32 bit libs. Its primary
9454            // ABI should be 64 bit. We can safely assume here that the bundled
9455            // native libraries correspond to the most preferred ABI in the list.
9456
9457            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9458            pkg.applicationInfo.secondaryCpuAbi = null;
9459        } else if (has32BitLibs && !has64BitLibs) {
9460            // The package has 32 bit libs but not 64 bit libs. Its primary
9461            // ABI should be 32 bit.
9462
9463            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9464            pkg.applicationInfo.secondaryCpuAbi = null;
9465        } else if (has32BitLibs && has64BitLibs) {
9466            // The application has both 64 and 32 bit bundled libraries. We check
9467            // here that the app declares multiArch support, and warn if it doesn't.
9468            //
9469            // We will be lenient here and record both ABIs. The primary will be the
9470            // ABI that's higher on the list, i.e, a device that's configured to prefer
9471            // 64 bit apps will see a 64 bit primary ABI,
9472
9473            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9474                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9475            }
9476
9477            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9478                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9479                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9480            } else {
9481                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9482                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9483            }
9484        } else {
9485            pkg.applicationInfo.primaryCpuAbi = null;
9486            pkg.applicationInfo.secondaryCpuAbi = null;
9487        }
9488    }
9489
9490    private void killApplication(String pkgName, int appId, String reason) {
9491        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9492    }
9493
9494    private void killApplication(String pkgName, int appId, int userId, String reason) {
9495        // Request the ActivityManager to kill the process(only for existing packages)
9496        // so that we do not end up in a confused state while the user is still using the older
9497        // version of the application while the new one gets installed.
9498        final long token = Binder.clearCallingIdentity();
9499        try {
9500            IActivityManager am = ActivityManagerNative.getDefault();
9501            if (am != null) {
9502                try {
9503                    am.killApplication(pkgName, appId, userId, reason);
9504                } catch (RemoteException e) {
9505                }
9506            }
9507        } finally {
9508            Binder.restoreCallingIdentity(token);
9509        }
9510    }
9511
9512    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9513        // Remove the parent package setting
9514        PackageSetting ps = (PackageSetting) pkg.mExtras;
9515        if (ps != null) {
9516            removePackageLI(ps, chatty);
9517        }
9518        // Remove the child package setting
9519        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9520        for (int i = 0; i < childCount; i++) {
9521            PackageParser.Package childPkg = pkg.childPackages.get(i);
9522            ps = (PackageSetting) childPkg.mExtras;
9523            if (ps != null) {
9524                removePackageLI(ps, chatty);
9525            }
9526        }
9527    }
9528
9529    void removePackageLI(PackageSetting ps, boolean chatty) {
9530        if (DEBUG_INSTALL) {
9531            if (chatty)
9532                Log.d(TAG, "Removing package " + ps.name);
9533        }
9534
9535        // writer
9536        synchronized (mPackages) {
9537            mPackages.remove(ps.name);
9538            final PackageParser.Package pkg = ps.pkg;
9539            if (pkg != null) {
9540                cleanPackageDataStructuresLILPw(pkg, chatty);
9541            }
9542        }
9543    }
9544
9545    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9546        if (DEBUG_INSTALL) {
9547            if (chatty)
9548                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9549        }
9550
9551        // writer
9552        synchronized (mPackages) {
9553            // Remove the parent package
9554            mPackages.remove(pkg.applicationInfo.packageName);
9555            cleanPackageDataStructuresLILPw(pkg, chatty);
9556
9557            // Remove the child packages
9558            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9559            for (int i = 0; i < childCount; i++) {
9560                PackageParser.Package childPkg = pkg.childPackages.get(i);
9561                mPackages.remove(childPkg.applicationInfo.packageName);
9562                cleanPackageDataStructuresLILPw(childPkg, chatty);
9563            }
9564        }
9565    }
9566
9567    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9568        int N = pkg.providers.size();
9569        StringBuilder r = null;
9570        int i;
9571        for (i=0; i<N; i++) {
9572            PackageParser.Provider p = pkg.providers.get(i);
9573            mProviders.removeProvider(p);
9574            if (p.info.authority == null) {
9575
9576                /* There was another ContentProvider with this authority when
9577                 * this app was installed so this authority is null,
9578                 * Ignore it as we don't have to unregister the provider.
9579                 */
9580                continue;
9581            }
9582            String names[] = p.info.authority.split(";");
9583            for (int j = 0; j < names.length; j++) {
9584                if (mProvidersByAuthority.get(names[j]) == p) {
9585                    mProvidersByAuthority.remove(names[j]);
9586                    if (DEBUG_REMOVE) {
9587                        if (chatty)
9588                            Log.d(TAG, "Unregistered content provider: " + names[j]
9589                                    + ", className = " + p.info.name + ", isSyncable = "
9590                                    + p.info.isSyncable);
9591                    }
9592                }
9593            }
9594            if (DEBUG_REMOVE && chatty) {
9595                if (r == null) {
9596                    r = new StringBuilder(256);
9597                } else {
9598                    r.append(' ');
9599                }
9600                r.append(p.info.name);
9601            }
9602        }
9603        if (r != null) {
9604            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9605        }
9606
9607        N = pkg.services.size();
9608        r = null;
9609        for (i=0; i<N; i++) {
9610            PackageParser.Service s = pkg.services.get(i);
9611            mServices.removeService(s);
9612            if (chatty) {
9613                if (r == null) {
9614                    r = new StringBuilder(256);
9615                } else {
9616                    r.append(' ');
9617                }
9618                r.append(s.info.name);
9619            }
9620        }
9621        if (r != null) {
9622            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9623        }
9624
9625        N = pkg.receivers.size();
9626        r = null;
9627        for (i=0; i<N; i++) {
9628            PackageParser.Activity a = pkg.receivers.get(i);
9629            mReceivers.removeActivity(a, "receiver");
9630            if (DEBUG_REMOVE && chatty) {
9631                if (r == null) {
9632                    r = new StringBuilder(256);
9633                } else {
9634                    r.append(' ');
9635                }
9636                r.append(a.info.name);
9637            }
9638        }
9639        if (r != null) {
9640            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9641        }
9642
9643        N = pkg.activities.size();
9644        r = null;
9645        for (i=0; i<N; i++) {
9646            PackageParser.Activity a = pkg.activities.get(i);
9647            mActivities.removeActivity(a, "activity");
9648            if (DEBUG_REMOVE && chatty) {
9649                if (r == null) {
9650                    r = new StringBuilder(256);
9651                } else {
9652                    r.append(' ');
9653                }
9654                r.append(a.info.name);
9655            }
9656        }
9657        if (r != null) {
9658            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9659        }
9660
9661        N = pkg.permissions.size();
9662        r = null;
9663        for (i=0; i<N; i++) {
9664            PackageParser.Permission p = pkg.permissions.get(i);
9665            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9666            if (bp == null) {
9667                bp = mSettings.mPermissionTrees.get(p.info.name);
9668            }
9669            if (bp != null && bp.perm == p) {
9670                bp.perm = null;
9671                if (DEBUG_REMOVE && chatty) {
9672                    if (r == null) {
9673                        r = new StringBuilder(256);
9674                    } else {
9675                        r.append(' ');
9676                    }
9677                    r.append(p.info.name);
9678                }
9679            }
9680            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9681                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9682                if (appOpPkgs != null) {
9683                    appOpPkgs.remove(pkg.packageName);
9684                }
9685            }
9686        }
9687        if (r != null) {
9688            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9689        }
9690
9691        N = pkg.requestedPermissions.size();
9692        r = null;
9693        for (i=0; i<N; i++) {
9694            String perm = pkg.requestedPermissions.get(i);
9695            BasePermission bp = mSettings.mPermissions.get(perm);
9696            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9697                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9698                if (appOpPkgs != null) {
9699                    appOpPkgs.remove(pkg.packageName);
9700                    if (appOpPkgs.isEmpty()) {
9701                        mAppOpPermissionPackages.remove(perm);
9702                    }
9703                }
9704            }
9705        }
9706        if (r != null) {
9707            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9708        }
9709
9710        N = pkg.instrumentation.size();
9711        r = null;
9712        for (i=0; i<N; i++) {
9713            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9714            mInstrumentation.remove(a.getComponentName());
9715            if (DEBUG_REMOVE && chatty) {
9716                if (r == null) {
9717                    r = new StringBuilder(256);
9718                } else {
9719                    r.append(' ');
9720                }
9721                r.append(a.info.name);
9722            }
9723        }
9724        if (r != null) {
9725            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9726        }
9727
9728        r = null;
9729        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9730            // Only system apps can hold shared libraries.
9731            if (pkg.libraryNames != null) {
9732                for (i=0; i<pkg.libraryNames.size(); i++) {
9733                    String name = pkg.libraryNames.get(i);
9734                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9735                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9736                        mSharedLibraries.remove(name);
9737                        if (DEBUG_REMOVE && chatty) {
9738                            if (r == null) {
9739                                r = new StringBuilder(256);
9740                            } else {
9741                                r.append(' ');
9742                            }
9743                            r.append(name);
9744                        }
9745                    }
9746                }
9747            }
9748        }
9749        if (r != null) {
9750            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9751        }
9752    }
9753
9754    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9755        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9756            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9757                return true;
9758            }
9759        }
9760        return false;
9761    }
9762
9763    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9764    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9765    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9766
9767    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9768        // Update the parent permissions
9769        updatePermissionsLPw(pkg.packageName, pkg, flags);
9770        // Update the child permissions
9771        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9772        for (int i = 0; i < childCount; i++) {
9773            PackageParser.Package childPkg = pkg.childPackages.get(i);
9774            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9775        }
9776    }
9777
9778    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9779            int flags) {
9780        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9781        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9782    }
9783
9784    private void updatePermissionsLPw(String changingPkg,
9785            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9786        // Make sure there are no dangling permission trees.
9787        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9788        while (it.hasNext()) {
9789            final BasePermission bp = it.next();
9790            if (bp.packageSetting == null) {
9791                // We may not yet have parsed the package, so just see if
9792                // we still know about its settings.
9793                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9794            }
9795            if (bp.packageSetting == null) {
9796                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9797                        + " from package " + bp.sourcePackage);
9798                it.remove();
9799            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9800                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9801                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9802                            + " from package " + bp.sourcePackage);
9803                    flags |= UPDATE_PERMISSIONS_ALL;
9804                    it.remove();
9805                }
9806            }
9807        }
9808
9809        // Make sure all dynamic permissions have been assigned to a package,
9810        // and make sure there are no dangling permissions.
9811        it = mSettings.mPermissions.values().iterator();
9812        while (it.hasNext()) {
9813            final BasePermission bp = it.next();
9814            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9815                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9816                        + bp.name + " pkg=" + bp.sourcePackage
9817                        + " info=" + bp.pendingInfo);
9818                if (bp.packageSetting == null && bp.pendingInfo != null) {
9819                    final BasePermission tree = findPermissionTreeLP(bp.name);
9820                    if (tree != null && tree.perm != null) {
9821                        bp.packageSetting = tree.packageSetting;
9822                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9823                                new PermissionInfo(bp.pendingInfo));
9824                        bp.perm.info.packageName = tree.perm.info.packageName;
9825                        bp.perm.info.name = bp.name;
9826                        bp.uid = tree.uid;
9827                    }
9828                }
9829            }
9830            if (bp.packageSetting == null) {
9831                // We may not yet have parsed the package, so just see if
9832                // we still know about its settings.
9833                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9834            }
9835            if (bp.packageSetting == null) {
9836                Slog.w(TAG, "Removing dangling permission: " + bp.name
9837                        + " from package " + bp.sourcePackage);
9838                it.remove();
9839            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9840                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9841                    Slog.i(TAG, "Removing old permission: " + bp.name
9842                            + " from package " + bp.sourcePackage);
9843                    flags |= UPDATE_PERMISSIONS_ALL;
9844                    it.remove();
9845                }
9846            }
9847        }
9848
9849        // Now update the permissions for all packages, in particular
9850        // replace the granted permissions of the system packages.
9851        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9852            for (PackageParser.Package pkg : mPackages.values()) {
9853                if (pkg != pkgInfo) {
9854                    // Only replace for packages on requested volume
9855                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9856                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9857                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9858                    grantPermissionsLPw(pkg, replace, changingPkg);
9859                }
9860            }
9861        }
9862
9863        if (pkgInfo != null) {
9864            // Only replace for packages on requested volume
9865            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9866            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9867                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9868            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9869        }
9870    }
9871
9872    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9873            String packageOfInterest) {
9874        // IMPORTANT: There are two types of permissions: install and runtime.
9875        // Install time permissions are granted when the app is installed to
9876        // all device users and users added in the future. Runtime permissions
9877        // are granted at runtime explicitly to specific users. Normal and signature
9878        // protected permissions are install time permissions. Dangerous permissions
9879        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9880        // otherwise they are runtime permissions. This function does not manage
9881        // runtime permissions except for the case an app targeting Lollipop MR1
9882        // being upgraded to target a newer SDK, in which case dangerous permissions
9883        // are transformed from install time to runtime ones.
9884
9885        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9886        if (ps == null) {
9887            return;
9888        }
9889
9890        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9891
9892        PermissionsState permissionsState = ps.getPermissionsState();
9893        PermissionsState origPermissions = permissionsState;
9894
9895        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9896
9897        boolean runtimePermissionsRevoked = false;
9898        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9899
9900        boolean changedInstallPermission = false;
9901
9902        if (replace) {
9903            ps.installPermissionsFixed = false;
9904            if (!ps.isSharedUser()) {
9905                origPermissions = new PermissionsState(permissionsState);
9906                permissionsState.reset();
9907            } else {
9908                // We need to know only about runtime permission changes since the
9909                // calling code always writes the install permissions state but
9910                // the runtime ones are written only if changed. The only cases of
9911                // changed runtime permissions here are promotion of an install to
9912                // runtime and revocation of a runtime from a shared user.
9913                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9914                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9915                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9916                    runtimePermissionsRevoked = true;
9917                }
9918            }
9919        }
9920
9921        permissionsState.setGlobalGids(mGlobalGids);
9922
9923        final int N = pkg.requestedPermissions.size();
9924        for (int i=0; i<N; i++) {
9925            final String name = pkg.requestedPermissions.get(i);
9926            final BasePermission bp = mSettings.mPermissions.get(name);
9927
9928            if (DEBUG_INSTALL) {
9929                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9930            }
9931
9932            if (bp == null || bp.packageSetting == null) {
9933                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9934                    Slog.w(TAG, "Unknown permission " + name
9935                            + " in package " + pkg.packageName);
9936                }
9937                continue;
9938            }
9939
9940            final String perm = bp.name;
9941            boolean allowedSig = false;
9942            int grant = GRANT_DENIED;
9943
9944            // Keep track of app op permissions.
9945            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9946                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9947                if (pkgs == null) {
9948                    pkgs = new ArraySet<>();
9949                    mAppOpPermissionPackages.put(bp.name, pkgs);
9950                }
9951                pkgs.add(pkg.packageName);
9952            }
9953
9954            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9955            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9956                    >= Build.VERSION_CODES.M;
9957            switch (level) {
9958                case PermissionInfo.PROTECTION_NORMAL: {
9959                    // For all apps normal permissions are install time ones.
9960                    grant = GRANT_INSTALL;
9961                } break;
9962
9963                case PermissionInfo.PROTECTION_DANGEROUS: {
9964                    // If a permission review is required for legacy apps we represent
9965                    // their permissions as always granted runtime ones since we need
9966                    // to keep the review required permission flag per user while an
9967                    // install permission's state is shared across all users.
9968                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9969                        // For legacy apps dangerous permissions are install time ones.
9970                        grant = GRANT_INSTALL;
9971                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9972                        // For legacy apps that became modern, install becomes runtime.
9973                        grant = GRANT_UPGRADE;
9974                    } else if (mPromoteSystemApps
9975                            && isSystemApp(ps)
9976                            && mExistingSystemPackages.contains(ps.name)) {
9977                        // For legacy system apps, install becomes runtime.
9978                        // We cannot check hasInstallPermission() for system apps since those
9979                        // permissions were granted implicitly and not persisted pre-M.
9980                        grant = GRANT_UPGRADE;
9981                    } else {
9982                        // For modern apps keep runtime permissions unchanged.
9983                        grant = GRANT_RUNTIME;
9984                    }
9985                } break;
9986
9987                case PermissionInfo.PROTECTION_SIGNATURE: {
9988                    // For all apps signature permissions are install time ones.
9989                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9990                    if (allowedSig) {
9991                        grant = GRANT_INSTALL;
9992                    }
9993                } break;
9994            }
9995
9996            if (DEBUG_INSTALL) {
9997                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9998            }
9999
10000            if (grant != GRANT_DENIED) {
10001                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10002                    // If this is an existing, non-system package, then
10003                    // we can't add any new permissions to it.
10004                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10005                        // Except...  if this is a permission that was added
10006                        // to the platform (note: need to only do this when
10007                        // updating the platform).
10008                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10009                            grant = GRANT_DENIED;
10010                        }
10011                    }
10012                }
10013
10014                switch (grant) {
10015                    case GRANT_INSTALL: {
10016                        // Revoke this as runtime permission to handle the case of
10017                        // a runtime permission being downgraded to an install one.
10018                        // Also in permission review mode we keep dangerous permissions
10019                        // for legacy apps
10020                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10021                            if (origPermissions.getRuntimePermissionState(
10022                                    bp.name, userId) != null) {
10023                                // Revoke the runtime permission and clear the flags.
10024                                origPermissions.revokeRuntimePermission(bp, userId);
10025                                origPermissions.updatePermissionFlags(bp, userId,
10026                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10027                                // If we revoked a permission permission, we have to write.
10028                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10029                                        changedRuntimePermissionUserIds, userId);
10030                            }
10031                        }
10032                        // Grant an install permission.
10033                        if (permissionsState.grantInstallPermission(bp) !=
10034                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10035                            changedInstallPermission = true;
10036                        }
10037                    } break;
10038
10039                    case GRANT_RUNTIME: {
10040                        // Grant previously granted runtime permissions.
10041                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10042                            PermissionState permissionState = origPermissions
10043                                    .getRuntimePermissionState(bp.name, userId);
10044                            int flags = permissionState != null
10045                                    ? permissionState.getFlags() : 0;
10046                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10047                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10048                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10049                                    // If we cannot put the permission as it was, we have to write.
10050                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10051                                            changedRuntimePermissionUserIds, userId);
10052                                }
10053                                // If the app supports runtime permissions no need for a review.
10054                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10055                                        && appSupportsRuntimePermissions
10056                                        && (flags & PackageManager
10057                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10058                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10059                                    // Since we changed the flags, we have to write.
10060                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10061                                            changedRuntimePermissionUserIds, userId);
10062                                }
10063                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10064                                    && !appSupportsRuntimePermissions) {
10065                                // For legacy apps that need a permission review, every new
10066                                // runtime permission is granted but it is pending a review.
10067                                // We also need to review only platform defined runtime
10068                                // permissions as these are the only ones the platform knows
10069                                // how to disable the API to simulate revocation as legacy
10070                                // apps don't expect to run with revoked permissions.
10071                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10072                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10073                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10074                                        // We changed the flags, hence have to write.
10075                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10076                                                changedRuntimePermissionUserIds, userId);
10077                                    }
10078                                }
10079                                if (permissionsState.grantRuntimePermission(bp, userId)
10080                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10081                                    // We changed the permission, hence have to write.
10082                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10083                                            changedRuntimePermissionUserIds, userId);
10084                                }
10085                            }
10086                            // Propagate the permission flags.
10087                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10088                        }
10089                    } break;
10090
10091                    case GRANT_UPGRADE: {
10092                        // Grant runtime permissions for a previously held install permission.
10093                        PermissionState permissionState = origPermissions
10094                                .getInstallPermissionState(bp.name);
10095                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10096
10097                        if (origPermissions.revokeInstallPermission(bp)
10098                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10099                            // We will be transferring the permission flags, so clear them.
10100                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10101                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10102                            changedInstallPermission = true;
10103                        }
10104
10105                        // If the permission is not to be promoted to runtime we ignore it and
10106                        // also its other flags as they are not applicable to install permissions.
10107                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10108                            for (int userId : currentUserIds) {
10109                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10110                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10111                                    // Transfer the permission flags.
10112                                    permissionsState.updatePermissionFlags(bp, userId,
10113                                            flags, flags);
10114                                    // If we granted the permission, we have to write.
10115                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10116                                            changedRuntimePermissionUserIds, userId);
10117                                }
10118                            }
10119                        }
10120                    } break;
10121
10122                    default: {
10123                        if (packageOfInterest == null
10124                                || packageOfInterest.equals(pkg.packageName)) {
10125                            Slog.w(TAG, "Not granting permission " + perm
10126                                    + " to package " + pkg.packageName
10127                                    + " because it was previously installed without");
10128                        }
10129                    } break;
10130                }
10131            } else {
10132                if (permissionsState.revokeInstallPermission(bp) !=
10133                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10134                    // Also drop the permission flags.
10135                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10136                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10137                    changedInstallPermission = true;
10138                    Slog.i(TAG, "Un-granting permission " + perm
10139                            + " from package " + pkg.packageName
10140                            + " (protectionLevel=" + bp.protectionLevel
10141                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10142                            + ")");
10143                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10144                    // Don't print warning for app op permissions, since it is fine for them
10145                    // not to be granted, there is a UI for the user to decide.
10146                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10147                        Slog.w(TAG, "Not granting permission " + perm
10148                                + " to package " + pkg.packageName
10149                                + " (protectionLevel=" + bp.protectionLevel
10150                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10151                                + ")");
10152                    }
10153                }
10154            }
10155        }
10156
10157        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10158                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10159            // This is the first that we have heard about this package, so the
10160            // permissions we have now selected are fixed until explicitly
10161            // changed.
10162            ps.installPermissionsFixed = true;
10163        }
10164
10165        // Persist the runtime permissions state for users with changes. If permissions
10166        // were revoked because no app in the shared user declares them we have to
10167        // write synchronously to avoid losing runtime permissions state.
10168        for (int userId : changedRuntimePermissionUserIds) {
10169            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10170        }
10171
10172        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10173    }
10174
10175    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10176        boolean allowed = false;
10177        final int NP = PackageParser.NEW_PERMISSIONS.length;
10178        for (int ip=0; ip<NP; ip++) {
10179            final PackageParser.NewPermissionInfo npi
10180                    = PackageParser.NEW_PERMISSIONS[ip];
10181            if (npi.name.equals(perm)
10182                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10183                allowed = true;
10184                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10185                        + pkg.packageName);
10186                break;
10187            }
10188        }
10189        return allowed;
10190    }
10191
10192    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10193            BasePermission bp, PermissionsState origPermissions) {
10194        boolean allowed;
10195        allowed = (compareSignatures(
10196                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10197                        == PackageManager.SIGNATURE_MATCH)
10198                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10199                        == PackageManager.SIGNATURE_MATCH);
10200        if (!allowed && (bp.protectionLevel
10201                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10202            if (isSystemApp(pkg)) {
10203                // For updated system applications, a system permission
10204                // is granted only if it had been defined by the original application.
10205                if (pkg.isUpdatedSystemApp()) {
10206                    final PackageSetting sysPs = mSettings
10207                            .getDisabledSystemPkgLPr(pkg.packageName);
10208                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10209                        // If the original was granted this permission, we take
10210                        // that grant decision as read and propagate it to the
10211                        // update.
10212                        if (sysPs.isPrivileged()) {
10213                            allowed = true;
10214                        }
10215                    } else {
10216                        // The system apk may have been updated with an older
10217                        // version of the one on the data partition, but which
10218                        // granted a new system permission that it didn't have
10219                        // before.  In this case we do want to allow the app to
10220                        // now get the new permission if the ancestral apk is
10221                        // privileged to get it.
10222                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10223                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10224                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10225                                    allowed = true;
10226                                    break;
10227                                }
10228                            }
10229                        }
10230                        // Also if a privileged parent package on the system image or any of
10231                        // its children requested a privileged permission, the updated child
10232                        // packages can also get the permission.
10233                        if (pkg.parentPackage != null) {
10234                            final PackageSetting disabledSysParentPs = mSettings
10235                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10236                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10237                                    && disabledSysParentPs.isPrivileged()) {
10238                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10239                                    allowed = true;
10240                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10241                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10242                                    for (int i = 0; i < count; i++) {
10243                                        PackageParser.Package disabledSysChildPkg =
10244                                                disabledSysParentPs.pkg.childPackages.get(i);
10245                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10246                                                perm)) {
10247                                            allowed = true;
10248                                            break;
10249                                        }
10250                                    }
10251                                }
10252                            }
10253                        }
10254                    }
10255                } else {
10256                    allowed = isPrivilegedApp(pkg);
10257                }
10258            }
10259        }
10260        if (!allowed) {
10261            if (!allowed && (bp.protectionLevel
10262                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10263                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10264                // If this was a previously normal/dangerous permission that got moved
10265                // to a system permission as part of the runtime permission redesign, then
10266                // we still want to blindly grant it to old apps.
10267                allowed = true;
10268            }
10269            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10270                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10271                // If this permission is to be granted to the system installer and
10272                // this app is an installer, then it gets the permission.
10273                allowed = true;
10274            }
10275            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10276                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10277                // If this permission is to be granted to the system verifier and
10278                // this app is a verifier, then it gets the permission.
10279                allowed = true;
10280            }
10281            if (!allowed && (bp.protectionLevel
10282                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10283                    && isSystemApp(pkg)) {
10284                // Any pre-installed system app is allowed to get this permission.
10285                allowed = true;
10286            }
10287            if (!allowed && (bp.protectionLevel
10288                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10289                // For development permissions, a development permission
10290                // is granted only if it was already granted.
10291                allowed = origPermissions.hasInstallPermission(perm);
10292            }
10293            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10294                    && pkg.packageName.equals(mSetupWizardPackage)) {
10295                // If this permission is to be granted to the system setup wizard and
10296                // this app is a setup wizard, then it gets the permission.
10297                allowed = true;
10298            }
10299        }
10300        return allowed;
10301    }
10302
10303    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10304        final int permCount = pkg.requestedPermissions.size();
10305        for (int j = 0; j < permCount; j++) {
10306            String requestedPermission = pkg.requestedPermissions.get(j);
10307            if (permission.equals(requestedPermission)) {
10308                return true;
10309            }
10310        }
10311        return false;
10312    }
10313
10314    final class ActivityIntentResolver
10315            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10316        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10317                boolean defaultOnly, int userId) {
10318            if (!sUserManager.exists(userId)) return null;
10319            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10320            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10321        }
10322
10323        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10324                int userId) {
10325            if (!sUserManager.exists(userId)) return null;
10326            mFlags = flags;
10327            return super.queryIntent(intent, resolvedType,
10328                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10329        }
10330
10331        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10332                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10333            if (!sUserManager.exists(userId)) return null;
10334            if (packageActivities == null) {
10335                return null;
10336            }
10337            mFlags = flags;
10338            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10339            final int N = packageActivities.size();
10340            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10341                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10342
10343            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10344            for (int i = 0; i < N; ++i) {
10345                intentFilters = packageActivities.get(i).intents;
10346                if (intentFilters != null && intentFilters.size() > 0) {
10347                    PackageParser.ActivityIntentInfo[] array =
10348                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10349                    intentFilters.toArray(array);
10350                    listCut.add(array);
10351                }
10352            }
10353            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10354        }
10355
10356        /**
10357         * Finds a privileged activity that matches the specified activity names.
10358         */
10359        private PackageParser.Activity findMatchingActivity(
10360                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10361            for (PackageParser.Activity sysActivity : activityList) {
10362                if (sysActivity.info.name.equals(activityInfo.name)) {
10363                    return sysActivity;
10364                }
10365                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10366                    return sysActivity;
10367                }
10368                if (sysActivity.info.targetActivity != null) {
10369                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10370                        return sysActivity;
10371                    }
10372                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10373                        return sysActivity;
10374                    }
10375                }
10376            }
10377            return null;
10378        }
10379
10380        public class IterGenerator<E> {
10381            public Iterator<E> generate(ActivityIntentInfo info) {
10382                return null;
10383            }
10384        }
10385
10386        public class ActionIterGenerator extends IterGenerator<String> {
10387            @Override
10388            public Iterator<String> generate(ActivityIntentInfo info) {
10389                return info.actionsIterator();
10390            }
10391        }
10392
10393        public class CategoriesIterGenerator extends IterGenerator<String> {
10394            @Override
10395            public Iterator<String> generate(ActivityIntentInfo info) {
10396                return info.categoriesIterator();
10397            }
10398        }
10399
10400        public class SchemesIterGenerator extends IterGenerator<String> {
10401            @Override
10402            public Iterator<String> generate(ActivityIntentInfo info) {
10403                return info.schemesIterator();
10404            }
10405        }
10406
10407        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10408            @Override
10409            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10410                return info.authoritiesIterator();
10411            }
10412        }
10413
10414        /**
10415         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10416         * MODIFIED. Do not pass in a list that should not be changed.
10417         */
10418        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10419                IterGenerator<T> generator, Iterator<T> searchIterator) {
10420            // loop through the set of actions; every one must be found in the intent filter
10421            while (searchIterator.hasNext()) {
10422                // we must have at least one filter in the list to consider a match
10423                if (intentList.size() == 0) {
10424                    break;
10425                }
10426
10427                final T searchAction = searchIterator.next();
10428
10429                // loop through the set of intent filters
10430                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10431                while (intentIter.hasNext()) {
10432                    final ActivityIntentInfo intentInfo = intentIter.next();
10433                    boolean selectionFound = false;
10434
10435                    // loop through the intent filter's selection criteria; at least one
10436                    // of them must match the searched criteria
10437                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10438                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10439                        final T intentSelection = intentSelectionIter.next();
10440                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10441                            selectionFound = true;
10442                            break;
10443                        }
10444                    }
10445
10446                    // the selection criteria wasn't found in this filter's set; this filter
10447                    // is not a potential match
10448                    if (!selectionFound) {
10449                        intentIter.remove();
10450                    }
10451                }
10452            }
10453        }
10454
10455        private boolean isProtectedAction(ActivityIntentInfo filter) {
10456            final Iterator<String> actionsIter = filter.actionsIterator();
10457            while (actionsIter != null && actionsIter.hasNext()) {
10458                final String filterAction = actionsIter.next();
10459                if (PROTECTED_ACTIONS.contains(filterAction)) {
10460                    return true;
10461                }
10462            }
10463            return false;
10464        }
10465
10466        /**
10467         * Adjusts the priority of the given intent filter according to policy.
10468         * <p>
10469         * <ul>
10470         * <li>The priority for non privileged applications is capped to '0'</li>
10471         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10472         * <li>The priority for unbundled updates to privileged applications is capped to the
10473         *      priority defined on the system partition</li>
10474         * </ul>
10475         * <p>
10476         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10477         * allowed to obtain any priority on any action.
10478         */
10479        private void adjustPriority(
10480                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10481            // nothing to do; priority is fine as-is
10482            if (intent.getPriority() <= 0) {
10483                return;
10484            }
10485
10486            final ActivityInfo activityInfo = intent.activity.info;
10487            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10488
10489            final boolean privilegedApp =
10490                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10491            if (!privilegedApp) {
10492                // non-privileged applications can never define a priority >0
10493                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10494                        + " package: " + applicationInfo.packageName
10495                        + " activity: " + intent.activity.className
10496                        + " origPrio: " + intent.getPriority());
10497                intent.setPriority(0);
10498                return;
10499            }
10500
10501            if (systemActivities == null) {
10502                // the system package is not disabled; we're parsing the system partition
10503                if (isProtectedAction(intent)) {
10504                    if (mDeferProtectedFilters) {
10505                        // We can't deal with these just yet. No component should ever obtain a
10506                        // >0 priority for a protected actions, with ONE exception -- the setup
10507                        // wizard. The setup wizard, however, cannot be known until we're able to
10508                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10509                        // until all intent filters have been processed. Chicken, meet egg.
10510                        // Let the filter temporarily have a high priority and rectify the
10511                        // priorities after all system packages have been scanned.
10512                        mProtectedFilters.add(intent);
10513                        if (DEBUG_FILTERS) {
10514                            Slog.i(TAG, "Protected action; save for later;"
10515                                    + " package: " + applicationInfo.packageName
10516                                    + " activity: " + intent.activity.className
10517                                    + " origPrio: " + intent.getPriority());
10518                        }
10519                        return;
10520                    } else {
10521                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10522                            Slog.i(TAG, "No setup wizard;"
10523                                + " All protected intents capped to priority 0");
10524                        }
10525                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10526                            if (DEBUG_FILTERS) {
10527                                Slog.i(TAG, "Found setup wizard;"
10528                                    + " allow priority " + intent.getPriority() + ";"
10529                                    + " package: " + intent.activity.info.packageName
10530                                    + " activity: " + intent.activity.className
10531                                    + " priority: " + intent.getPriority());
10532                            }
10533                            // setup wizard gets whatever it wants
10534                            return;
10535                        }
10536                        Slog.w(TAG, "Protected action; cap priority to 0;"
10537                                + " package: " + intent.activity.info.packageName
10538                                + " activity: " + intent.activity.className
10539                                + " origPrio: " + intent.getPriority());
10540                        intent.setPriority(0);
10541                        return;
10542                    }
10543                }
10544                // privileged apps on the system image get whatever priority they request
10545                return;
10546            }
10547
10548            // privileged app unbundled update ... try to find the same activity
10549            final PackageParser.Activity foundActivity =
10550                    findMatchingActivity(systemActivities, activityInfo);
10551            if (foundActivity == null) {
10552                // this is a new activity; it cannot obtain >0 priority
10553                if (DEBUG_FILTERS) {
10554                    Slog.i(TAG, "New activity; cap priority to 0;"
10555                            + " package: " + applicationInfo.packageName
10556                            + " activity: " + intent.activity.className
10557                            + " origPrio: " + intent.getPriority());
10558                }
10559                intent.setPriority(0);
10560                return;
10561            }
10562
10563            // found activity, now check for filter equivalence
10564
10565            // a shallow copy is enough; we modify the list, not its contents
10566            final List<ActivityIntentInfo> intentListCopy =
10567                    new ArrayList<>(foundActivity.intents);
10568            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10569
10570            // find matching action subsets
10571            final Iterator<String> actionsIterator = intent.actionsIterator();
10572            if (actionsIterator != null) {
10573                getIntentListSubset(
10574                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10575                if (intentListCopy.size() == 0) {
10576                    // no more intents to match; we're not equivalent
10577                    if (DEBUG_FILTERS) {
10578                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10579                                + " package: " + applicationInfo.packageName
10580                                + " activity: " + intent.activity.className
10581                                + " origPrio: " + intent.getPriority());
10582                    }
10583                    intent.setPriority(0);
10584                    return;
10585                }
10586            }
10587
10588            // find matching category subsets
10589            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10590            if (categoriesIterator != null) {
10591                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10592                        categoriesIterator);
10593                if (intentListCopy.size() == 0) {
10594                    // no more intents to match; we're not equivalent
10595                    if (DEBUG_FILTERS) {
10596                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10597                                + " package: " + applicationInfo.packageName
10598                                + " activity: " + intent.activity.className
10599                                + " origPrio: " + intent.getPriority());
10600                    }
10601                    intent.setPriority(0);
10602                    return;
10603                }
10604            }
10605
10606            // find matching schemes subsets
10607            final Iterator<String> schemesIterator = intent.schemesIterator();
10608            if (schemesIterator != null) {
10609                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10610                        schemesIterator);
10611                if (intentListCopy.size() == 0) {
10612                    // no more intents to match; we're not equivalent
10613                    if (DEBUG_FILTERS) {
10614                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10615                                + " package: " + applicationInfo.packageName
10616                                + " activity: " + intent.activity.className
10617                                + " origPrio: " + intent.getPriority());
10618                    }
10619                    intent.setPriority(0);
10620                    return;
10621                }
10622            }
10623
10624            // find matching authorities subsets
10625            final Iterator<IntentFilter.AuthorityEntry>
10626                    authoritiesIterator = intent.authoritiesIterator();
10627            if (authoritiesIterator != null) {
10628                getIntentListSubset(intentListCopy,
10629                        new AuthoritiesIterGenerator(),
10630                        authoritiesIterator);
10631                if (intentListCopy.size() == 0) {
10632                    // no more intents to match; we're not equivalent
10633                    if (DEBUG_FILTERS) {
10634                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10635                                + " package: " + applicationInfo.packageName
10636                                + " activity: " + intent.activity.className
10637                                + " origPrio: " + intent.getPriority());
10638                    }
10639                    intent.setPriority(0);
10640                    return;
10641                }
10642            }
10643
10644            // we found matching filter(s); app gets the max priority of all intents
10645            int cappedPriority = 0;
10646            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10647                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10648            }
10649            if (intent.getPriority() > cappedPriority) {
10650                if (DEBUG_FILTERS) {
10651                    Slog.i(TAG, "Found matching filter(s);"
10652                            + " cap priority to " + cappedPriority + ";"
10653                            + " package: " + applicationInfo.packageName
10654                            + " activity: " + intent.activity.className
10655                            + " origPrio: " + intent.getPriority());
10656                }
10657                intent.setPriority(cappedPriority);
10658                return;
10659            }
10660            // all this for nothing; the requested priority was <= what was on the system
10661        }
10662
10663        public final void addActivity(PackageParser.Activity a, String type) {
10664            mActivities.put(a.getComponentName(), a);
10665            if (DEBUG_SHOW_INFO)
10666                Log.v(
10667                TAG, "  " + type + " " +
10668                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10669            if (DEBUG_SHOW_INFO)
10670                Log.v(TAG, "    Class=" + a.info.name);
10671            final int NI = a.intents.size();
10672            for (int j=0; j<NI; j++) {
10673                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10674                if ("activity".equals(type)) {
10675                    final PackageSetting ps =
10676                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10677                    final List<PackageParser.Activity> systemActivities =
10678                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10679                    adjustPriority(systemActivities, intent);
10680                }
10681                if (DEBUG_SHOW_INFO) {
10682                    Log.v(TAG, "    IntentFilter:");
10683                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10684                }
10685                if (!intent.debugCheck()) {
10686                    Log.w(TAG, "==> For Activity " + a.info.name);
10687                }
10688                addFilter(intent);
10689            }
10690        }
10691
10692        public final void removeActivity(PackageParser.Activity a, String type) {
10693            mActivities.remove(a.getComponentName());
10694            if (DEBUG_SHOW_INFO) {
10695                Log.v(TAG, "  " + type + " "
10696                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10697                                : a.info.name) + ":");
10698                Log.v(TAG, "    Class=" + a.info.name);
10699            }
10700            final int NI = a.intents.size();
10701            for (int j=0; j<NI; j++) {
10702                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10703                if (DEBUG_SHOW_INFO) {
10704                    Log.v(TAG, "    IntentFilter:");
10705                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10706                }
10707                removeFilter(intent);
10708            }
10709        }
10710
10711        @Override
10712        protected boolean allowFilterResult(
10713                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10714            ActivityInfo filterAi = filter.activity.info;
10715            for (int i=dest.size()-1; i>=0; i--) {
10716                ActivityInfo destAi = dest.get(i).activityInfo;
10717                if (destAi.name == filterAi.name
10718                        && destAi.packageName == filterAi.packageName) {
10719                    return false;
10720                }
10721            }
10722            return true;
10723        }
10724
10725        @Override
10726        protected ActivityIntentInfo[] newArray(int size) {
10727            return new ActivityIntentInfo[size];
10728        }
10729
10730        @Override
10731        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10732            if (!sUserManager.exists(userId)) return true;
10733            PackageParser.Package p = filter.activity.owner;
10734            if (p != null) {
10735                PackageSetting ps = (PackageSetting)p.mExtras;
10736                if (ps != null) {
10737                    // System apps are never considered stopped for purposes of
10738                    // filtering, because there may be no way for the user to
10739                    // actually re-launch them.
10740                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10741                            && ps.getStopped(userId);
10742                }
10743            }
10744            return false;
10745        }
10746
10747        @Override
10748        protected boolean isPackageForFilter(String packageName,
10749                PackageParser.ActivityIntentInfo info) {
10750            return packageName.equals(info.activity.owner.packageName);
10751        }
10752
10753        @Override
10754        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10755                int match, int userId) {
10756            if (!sUserManager.exists(userId)) return null;
10757            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10758                return null;
10759            }
10760            final PackageParser.Activity activity = info.activity;
10761            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10762            if (ps == null) {
10763                return null;
10764            }
10765            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10766                    ps.readUserState(userId), userId);
10767            if (ai == null) {
10768                return null;
10769            }
10770            final ResolveInfo res = new ResolveInfo();
10771            res.activityInfo = ai;
10772            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10773                res.filter = info;
10774            }
10775            if (info != null) {
10776                res.handleAllWebDataURI = info.handleAllWebDataURI();
10777            }
10778            res.priority = info.getPriority();
10779            res.preferredOrder = activity.owner.mPreferredOrder;
10780            //System.out.println("Result: " + res.activityInfo.className +
10781            //                   " = " + res.priority);
10782            res.match = match;
10783            res.isDefault = info.hasDefault;
10784            res.labelRes = info.labelRes;
10785            res.nonLocalizedLabel = info.nonLocalizedLabel;
10786            if (userNeedsBadging(userId)) {
10787                res.noResourceId = true;
10788            } else {
10789                res.icon = info.icon;
10790            }
10791            res.iconResourceId = info.icon;
10792            res.system = res.activityInfo.applicationInfo.isSystemApp();
10793            return res;
10794        }
10795
10796        @Override
10797        protected void sortResults(List<ResolveInfo> results) {
10798            Collections.sort(results, mResolvePrioritySorter);
10799        }
10800
10801        @Override
10802        protected void dumpFilter(PrintWriter out, String prefix,
10803                PackageParser.ActivityIntentInfo filter) {
10804            out.print(prefix); out.print(
10805                    Integer.toHexString(System.identityHashCode(filter.activity)));
10806                    out.print(' ');
10807                    filter.activity.printComponentShortName(out);
10808                    out.print(" filter ");
10809                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10810        }
10811
10812        @Override
10813        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10814            return filter.activity;
10815        }
10816
10817        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10818            PackageParser.Activity activity = (PackageParser.Activity)label;
10819            out.print(prefix); out.print(
10820                    Integer.toHexString(System.identityHashCode(activity)));
10821                    out.print(' ');
10822                    activity.printComponentShortName(out);
10823            if (count > 1) {
10824                out.print(" ("); out.print(count); out.print(" filters)");
10825            }
10826            out.println();
10827        }
10828
10829        // Keys are String (activity class name), values are Activity.
10830        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10831                = new ArrayMap<ComponentName, PackageParser.Activity>();
10832        private int mFlags;
10833    }
10834
10835    private final class ServiceIntentResolver
10836            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10837        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10838                boolean defaultOnly, int userId) {
10839            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10840            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10841        }
10842
10843        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10844                int userId) {
10845            if (!sUserManager.exists(userId)) return null;
10846            mFlags = flags;
10847            return super.queryIntent(intent, resolvedType,
10848                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10849        }
10850
10851        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10852                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10853            if (!sUserManager.exists(userId)) return null;
10854            if (packageServices == null) {
10855                return null;
10856            }
10857            mFlags = flags;
10858            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10859            final int N = packageServices.size();
10860            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10861                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10862
10863            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10864            for (int i = 0; i < N; ++i) {
10865                intentFilters = packageServices.get(i).intents;
10866                if (intentFilters != null && intentFilters.size() > 0) {
10867                    PackageParser.ServiceIntentInfo[] array =
10868                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10869                    intentFilters.toArray(array);
10870                    listCut.add(array);
10871                }
10872            }
10873            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10874        }
10875
10876        public final void addService(PackageParser.Service s) {
10877            mServices.put(s.getComponentName(), s);
10878            if (DEBUG_SHOW_INFO) {
10879                Log.v(TAG, "  "
10880                        + (s.info.nonLocalizedLabel != null
10881                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10882                Log.v(TAG, "    Class=" + s.info.name);
10883            }
10884            final int NI = s.intents.size();
10885            int j;
10886            for (j=0; j<NI; j++) {
10887                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10888                if (DEBUG_SHOW_INFO) {
10889                    Log.v(TAG, "    IntentFilter:");
10890                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10891                }
10892                if (!intent.debugCheck()) {
10893                    Log.w(TAG, "==> For Service " + s.info.name);
10894                }
10895                addFilter(intent);
10896            }
10897        }
10898
10899        public final void removeService(PackageParser.Service s) {
10900            mServices.remove(s.getComponentName());
10901            if (DEBUG_SHOW_INFO) {
10902                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10903                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10904                Log.v(TAG, "    Class=" + s.info.name);
10905            }
10906            final int NI = s.intents.size();
10907            int j;
10908            for (j=0; j<NI; j++) {
10909                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10910                if (DEBUG_SHOW_INFO) {
10911                    Log.v(TAG, "    IntentFilter:");
10912                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10913                }
10914                removeFilter(intent);
10915            }
10916        }
10917
10918        @Override
10919        protected boolean allowFilterResult(
10920                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10921            ServiceInfo filterSi = filter.service.info;
10922            for (int i=dest.size()-1; i>=0; i--) {
10923                ServiceInfo destAi = dest.get(i).serviceInfo;
10924                if (destAi.name == filterSi.name
10925                        && destAi.packageName == filterSi.packageName) {
10926                    return false;
10927                }
10928            }
10929            return true;
10930        }
10931
10932        @Override
10933        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10934            return new PackageParser.ServiceIntentInfo[size];
10935        }
10936
10937        @Override
10938        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10939            if (!sUserManager.exists(userId)) return true;
10940            PackageParser.Package p = filter.service.owner;
10941            if (p != null) {
10942                PackageSetting ps = (PackageSetting)p.mExtras;
10943                if (ps != null) {
10944                    // System apps are never considered stopped for purposes of
10945                    // filtering, because there may be no way for the user to
10946                    // actually re-launch them.
10947                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10948                            && ps.getStopped(userId);
10949                }
10950            }
10951            return false;
10952        }
10953
10954        @Override
10955        protected boolean isPackageForFilter(String packageName,
10956                PackageParser.ServiceIntentInfo info) {
10957            return packageName.equals(info.service.owner.packageName);
10958        }
10959
10960        @Override
10961        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10962                int match, int userId) {
10963            if (!sUserManager.exists(userId)) return null;
10964            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10965            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10966                return null;
10967            }
10968            final PackageParser.Service service = info.service;
10969            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10970            if (ps == null) {
10971                return null;
10972            }
10973            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10974                    ps.readUserState(userId), userId);
10975            if (si == null) {
10976                return null;
10977            }
10978            final ResolveInfo res = new ResolveInfo();
10979            res.serviceInfo = si;
10980            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10981                res.filter = filter;
10982            }
10983            res.priority = info.getPriority();
10984            res.preferredOrder = service.owner.mPreferredOrder;
10985            res.match = match;
10986            res.isDefault = info.hasDefault;
10987            res.labelRes = info.labelRes;
10988            res.nonLocalizedLabel = info.nonLocalizedLabel;
10989            res.icon = info.icon;
10990            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10991            return res;
10992        }
10993
10994        @Override
10995        protected void sortResults(List<ResolveInfo> results) {
10996            Collections.sort(results, mResolvePrioritySorter);
10997        }
10998
10999        @Override
11000        protected void dumpFilter(PrintWriter out, String prefix,
11001                PackageParser.ServiceIntentInfo filter) {
11002            out.print(prefix); out.print(
11003                    Integer.toHexString(System.identityHashCode(filter.service)));
11004                    out.print(' ');
11005                    filter.service.printComponentShortName(out);
11006                    out.print(" filter ");
11007                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11008        }
11009
11010        @Override
11011        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11012            return filter.service;
11013        }
11014
11015        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11016            PackageParser.Service service = (PackageParser.Service)label;
11017            out.print(prefix); out.print(
11018                    Integer.toHexString(System.identityHashCode(service)));
11019                    out.print(' ');
11020                    service.printComponentShortName(out);
11021            if (count > 1) {
11022                out.print(" ("); out.print(count); out.print(" filters)");
11023            }
11024            out.println();
11025        }
11026
11027//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11028//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11029//            final List<ResolveInfo> retList = Lists.newArrayList();
11030//            while (i.hasNext()) {
11031//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11032//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11033//                    retList.add(resolveInfo);
11034//                }
11035//            }
11036//            return retList;
11037//        }
11038
11039        // Keys are String (activity class name), values are Activity.
11040        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11041                = new ArrayMap<ComponentName, PackageParser.Service>();
11042        private int mFlags;
11043    };
11044
11045    private final class ProviderIntentResolver
11046            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11047        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11048                boolean defaultOnly, int userId) {
11049            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11050            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11051        }
11052
11053        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11054                int userId) {
11055            if (!sUserManager.exists(userId))
11056                return null;
11057            mFlags = flags;
11058            return super.queryIntent(intent, resolvedType,
11059                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11060        }
11061
11062        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11063                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11064            if (!sUserManager.exists(userId))
11065                return null;
11066            if (packageProviders == null) {
11067                return null;
11068            }
11069            mFlags = flags;
11070            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11071            final int N = packageProviders.size();
11072            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11073                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11074
11075            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11076            for (int i = 0; i < N; ++i) {
11077                intentFilters = packageProviders.get(i).intents;
11078                if (intentFilters != null && intentFilters.size() > 0) {
11079                    PackageParser.ProviderIntentInfo[] array =
11080                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11081                    intentFilters.toArray(array);
11082                    listCut.add(array);
11083                }
11084            }
11085            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11086        }
11087
11088        public final void addProvider(PackageParser.Provider p) {
11089            if (mProviders.containsKey(p.getComponentName())) {
11090                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11091                return;
11092            }
11093
11094            mProviders.put(p.getComponentName(), p);
11095            if (DEBUG_SHOW_INFO) {
11096                Log.v(TAG, "  "
11097                        + (p.info.nonLocalizedLabel != null
11098                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11099                Log.v(TAG, "    Class=" + p.info.name);
11100            }
11101            final int NI = p.intents.size();
11102            int j;
11103            for (j = 0; j < NI; j++) {
11104                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11105                if (DEBUG_SHOW_INFO) {
11106                    Log.v(TAG, "    IntentFilter:");
11107                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11108                }
11109                if (!intent.debugCheck()) {
11110                    Log.w(TAG, "==> For Provider " + p.info.name);
11111                }
11112                addFilter(intent);
11113            }
11114        }
11115
11116        public final void removeProvider(PackageParser.Provider p) {
11117            mProviders.remove(p.getComponentName());
11118            if (DEBUG_SHOW_INFO) {
11119                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11120                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11121                Log.v(TAG, "    Class=" + p.info.name);
11122            }
11123            final int NI = p.intents.size();
11124            int j;
11125            for (j = 0; j < NI; j++) {
11126                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11127                if (DEBUG_SHOW_INFO) {
11128                    Log.v(TAG, "    IntentFilter:");
11129                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11130                }
11131                removeFilter(intent);
11132            }
11133        }
11134
11135        @Override
11136        protected boolean allowFilterResult(
11137                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11138            ProviderInfo filterPi = filter.provider.info;
11139            for (int i = dest.size() - 1; i >= 0; i--) {
11140                ProviderInfo destPi = dest.get(i).providerInfo;
11141                if (destPi.name == filterPi.name
11142                        && destPi.packageName == filterPi.packageName) {
11143                    return false;
11144                }
11145            }
11146            return true;
11147        }
11148
11149        @Override
11150        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11151            return new PackageParser.ProviderIntentInfo[size];
11152        }
11153
11154        @Override
11155        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11156            if (!sUserManager.exists(userId))
11157                return true;
11158            PackageParser.Package p = filter.provider.owner;
11159            if (p != null) {
11160                PackageSetting ps = (PackageSetting) p.mExtras;
11161                if (ps != null) {
11162                    // System apps are never considered stopped for purposes of
11163                    // filtering, because there may be no way for the user to
11164                    // actually re-launch them.
11165                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11166                            && ps.getStopped(userId);
11167                }
11168            }
11169            return false;
11170        }
11171
11172        @Override
11173        protected boolean isPackageForFilter(String packageName,
11174                PackageParser.ProviderIntentInfo info) {
11175            return packageName.equals(info.provider.owner.packageName);
11176        }
11177
11178        @Override
11179        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11180                int match, int userId) {
11181            if (!sUserManager.exists(userId))
11182                return null;
11183            final PackageParser.ProviderIntentInfo info = filter;
11184            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11185                return null;
11186            }
11187            final PackageParser.Provider provider = info.provider;
11188            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11189            if (ps == null) {
11190                return null;
11191            }
11192            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11193                    ps.readUserState(userId), userId);
11194            if (pi == null) {
11195                return null;
11196            }
11197            final ResolveInfo res = new ResolveInfo();
11198            res.providerInfo = pi;
11199            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11200                res.filter = filter;
11201            }
11202            res.priority = info.getPriority();
11203            res.preferredOrder = provider.owner.mPreferredOrder;
11204            res.match = match;
11205            res.isDefault = info.hasDefault;
11206            res.labelRes = info.labelRes;
11207            res.nonLocalizedLabel = info.nonLocalizedLabel;
11208            res.icon = info.icon;
11209            res.system = res.providerInfo.applicationInfo.isSystemApp();
11210            return res;
11211        }
11212
11213        @Override
11214        protected void sortResults(List<ResolveInfo> results) {
11215            Collections.sort(results, mResolvePrioritySorter);
11216        }
11217
11218        @Override
11219        protected void dumpFilter(PrintWriter out, String prefix,
11220                PackageParser.ProviderIntentInfo filter) {
11221            out.print(prefix);
11222            out.print(
11223                    Integer.toHexString(System.identityHashCode(filter.provider)));
11224            out.print(' ');
11225            filter.provider.printComponentShortName(out);
11226            out.print(" filter ");
11227            out.println(Integer.toHexString(System.identityHashCode(filter)));
11228        }
11229
11230        @Override
11231        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11232            return filter.provider;
11233        }
11234
11235        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11236            PackageParser.Provider provider = (PackageParser.Provider)label;
11237            out.print(prefix); out.print(
11238                    Integer.toHexString(System.identityHashCode(provider)));
11239                    out.print(' ');
11240                    provider.printComponentShortName(out);
11241            if (count > 1) {
11242                out.print(" ("); out.print(count); out.print(" filters)");
11243            }
11244            out.println();
11245        }
11246
11247        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11248                = new ArrayMap<ComponentName, PackageParser.Provider>();
11249        private int mFlags;
11250    }
11251
11252    private static final class EphemeralIntentResolver
11253            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11254        @Override
11255        protected EphemeralResolveIntentInfo[] newArray(int size) {
11256            return new EphemeralResolveIntentInfo[size];
11257        }
11258
11259        @Override
11260        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11261            return true;
11262        }
11263
11264        @Override
11265        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11266                int userId) {
11267            if (!sUserManager.exists(userId)) {
11268                return null;
11269            }
11270            return info.getEphemeralResolveInfo();
11271        }
11272    }
11273
11274    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11275            new Comparator<ResolveInfo>() {
11276        public int compare(ResolveInfo r1, ResolveInfo r2) {
11277            int v1 = r1.priority;
11278            int v2 = r2.priority;
11279            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11280            if (v1 != v2) {
11281                return (v1 > v2) ? -1 : 1;
11282            }
11283            v1 = r1.preferredOrder;
11284            v2 = r2.preferredOrder;
11285            if (v1 != v2) {
11286                return (v1 > v2) ? -1 : 1;
11287            }
11288            if (r1.isDefault != r2.isDefault) {
11289                return r1.isDefault ? -1 : 1;
11290            }
11291            v1 = r1.match;
11292            v2 = r2.match;
11293            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11294            if (v1 != v2) {
11295                return (v1 > v2) ? -1 : 1;
11296            }
11297            if (r1.system != r2.system) {
11298                return r1.system ? -1 : 1;
11299            }
11300            if (r1.activityInfo != null) {
11301                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11302            }
11303            if (r1.serviceInfo != null) {
11304                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11305            }
11306            if (r1.providerInfo != null) {
11307                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11308            }
11309            return 0;
11310        }
11311    };
11312
11313    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11314            new Comparator<ProviderInfo>() {
11315        public int compare(ProviderInfo p1, ProviderInfo p2) {
11316            final int v1 = p1.initOrder;
11317            final int v2 = p2.initOrder;
11318            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11319        }
11320    };
11321
11322    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11323            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11324            final int[] userIds) {
11325        mHandler.post(new Runnable() {
11326            @Override
11327            public void run() {
11328                try {
11329                    final IActivityManager am = ActivityManagerNative.getDefault();
11330                    if (am == null) return;
11331                    final int[] resolvedUserIds;
11332                    if (userIds == null) {
11333                        resolvedUserIds = am.getRunningUserIds();
11334                    } else {
11335                        resolvedUserIds = userIds;
11336                    }
11337                    for (int id : resolvedUserIds) {
11338                        final Intent intent = new Intent(action,
11339                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11340                        if (extras != null) {
11341                            intent.putExtras(extras);
11342                        }
11343                        if (targetPkg != null) {
11344                            intent.setPackage(targetPkg);
11345                        }
11346                        // Modify the UID when posting to other users
11347                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11348                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11349                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11350                            intent.putExtra(Intent.EXTRA_UID, uid);
11351                        }
11352                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11353                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11354                        if (DEBUG_BROADCASTS) {
11355                            RuntimeException here = new RuntimeException("here");
11356                            here.fillInStackTrace();
11357                            Slog.d(TAG, "Sending to user " + id + ": "
11358                                    + intent.toShortString(false, true, false, false)
11359                                    + " " + intent.getExtras(), here);
11360                        }
11361                        am.broadcastIntent(null, intent, null, finishedReceiver,
11362                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11363                                null, finishedReceiver != null, false, id);
11364                    }
11365                } catch (RemoteException ex) {
11366                }
11367            }
11368        });
11369    }
11370
11371    /**
11372     * Check if the external storage media is available. This is true if there
11373     * is a mounted external storage medium or if the external storage is
11374     * emulated.
11375     */
11376    private boolean isExternalMediaAvailable() {
11377        return mMediaMounted || Environment.isExternalStorageEmulated();
11378    }
11379
11380    @Override
11381    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11382        // writer
11383        synchronized (mPackages) {
11384            if (!isExternalMediaAvailable()) {
11385                // If the external storage is no longer mounted at this point,
11386                // the caller may not have been able to delete all of this
11387                // packages files and can not delete any more.  Bail.
11388                return null;
11389            }
11390            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11391            if (lastPackage != null) {
11392                pkgs.remove(lastPackage);
11393            }
11394            if (pkgs.size() > 0) {
11395                return pkgs.get(0);
11396            }
11397        }
11398        return null;
11399    }
11400
11401    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11402        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11403                userId, andCode ? 1 : 0, packageName);
11404        if (mSystemReady) {
11405            msg.sendToTarget();
11406        } else {
11407            if (mPostSystemReadyMessages == null) {
11408                mPostSystemReadyMessages = new ArrayList<>();
11409            }
11410            mPostSystemReadyMessages.add(msg);
11411        }
11412    }
11413
11414    void startCleaningPackages() {
11415        // reader
11416        if (!isExternalMediaAvailable()) {
11417            return;
11418        }
11419        synchronized (mPackages) {
11420            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11421                return;
11422            }
11423        }
11424        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11425        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11426        IActivityManager am = ActivityManagerNative.getDefault();
11427        if (am != null) {
11428            try {
11429                am.startService(null, intent, null, mContext.getOpPackageName(),
11430                        UserHandle.USER_SYSTEM);
11431            } catch (RemoteException e) {
11432            }
11433        }
11434    }
11435
11436    @Override
11437    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11438            int installFlags, String installerPackageName, int userId) {
11439        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11440
11441        final int callingUid = Binder.getCallingUid();
11442        enforceCrossUserPermission(callingUid, userId,
11443                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11444
11445        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11446            try {
11447                if (observer != null) {
11448                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11449                }
11450            } catch (RemoteException re) {
11451            }
11452            return;
11453        }
11454
11455        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11456            installFlags |= PackageManager.INSTALL_FROM_ADB;
11457
11458        } else {
11459            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11460            // about installerPackageName.
11461
11462            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11463            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11464        }
11465
11466        UserHandle user;
11467        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11468            user = UserHandle.ALL;
11469        } else {
11470            user = new UserHandle(userId);
11471        }
11472
11473        // Only system components can circumvent runtime permissions when installing.
11474        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11475                && mContext.checkCallingOrSelfPermission(Manifest.permission
11476                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11477            throw new SecurityException("You need the "
11478                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11479                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11480        }
11481
11482        final File originFile = new File(originPath);
11483        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11484
11485        final Message msg = mHandler.obtainMessage(INIT_COPY);
11486        final VerificationInfo verificationInfo = new VerificationInfo(
11487                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11488        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11489                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11490                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11491                null /*certificates*/);
11492        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11493        msg.obj = params;
11494
11495        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11496                System.identityHashCode(msg.obj));
11497        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11498                System.identityHashCode(msg.obj));
11499
11500        mHandler.sendMessage(msg);
11501    }
11502
11503    void installStage(String packageName, File stagedDir, String stagedCid,
11504            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11505            String installerPackageName, int installerUid, UserHandle user,
11506            Certificate[][] certificates) {
11507        if (DEBUG_EPHEMERAL) {
11508            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11509                Slog.d(TAG, "Ephemeral install of " + packageName);
11510            }
11511        }
11512        final VerificationInfo verificationInfo = new VerificationInfo(
11513                sessionParams.originatingUri, sessionParams.referrerUri,
11514                sessionParams.originatingUid, installerUid);
11515
11516        final OriginInfo origin;
11517        if (stagedDir != null) {
11518            origin = OriginInfo.fromStagedFile(stagedDir);
11519        } else {
11520            origin = OriginInfo.fromStagedContainer(stagedCid);
11521        }
11522
11523        final Message msg = mHandler.obtainMessage(INIT_COPY);
11524        final InstallParams params = new InstallParams(origin, null, observer,
11525                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11526                verificationInfo, user, sessionParams.abiOverride,
11527                sessionParams.grantedRuntimePermissions, certificates);
11528        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11529        msg.obj = params;
11530
11531        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11532                System.identityHashCode(msg.obj));
11533        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11534                System.identityHashCode(msg.obj));
11535
11536        mHandler.sendMessage(msg);
11537    }
11538
11539    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11540            int userId) {
11541        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11542        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11543    }
11544
11545    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11546            int appId, int userId) {
11547        Bundle extras = new Bundle(1);
11548        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11549
11550        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11551                packageName, extras, 0, null, null, new int[] {userId});
11552        try {
11553            IActivityManager am = ActivityManagerNative.getDefault();
11554            if (isSystem && am.isUserRunning(userId, 0)) {
11555                // The just-installed/enabled app is bundled on the system, so presumed
11556                // to be able to run automatically without needing an explicit launch.
11557                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11558                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11559                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11560                        .setPackage(packageName);
11561                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11562                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11563            }
11564        } catch (RemoteException e) {
11565            // shouldn't happen
11566            Slog.w(TAG, "Unable to bootstrap installed package", e);
11567        }
11568    }
11569
11570    @Override
11571    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11572            int userId) {
11573        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11574        PackageSetting pkgSetting;
11575        final int uid = Binder.getCallingUid();
11576        enforceCrossUserPermission(uid, userId,
11577                true /* requireFullPermission */, true /* checkShell */,
11578                "setApplicationHiddenSetting for user " + userId);
11579
11580        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11581            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11582            return false;
11583        }
11584
11585        long callingId = Binder.clearCallingIdentity();
11586        try {
11587            boolean sendAdded = false;
11588            boolean sendRemoved = false;
11589            // writer
11590            synchronized (mPackages) {
11591                pkgSetting = mSettings.mPackages.get(packageName);
11592                if (pkgSetting == null) {
11593                    return false;
11594                }
11595                // Do not allow "android" is being disabled
11596                if ("android".equals(packageName)) {
11597                    Slog.w(TAG, "Cannot hide package: android");
11598                    return false;
11599                }
11600                // Only allow protected packages to hide themselves.
11601                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11602                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11603                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11604                    return false;
11605                }
11606
11607                if (pkgSetting.getHidden(userId) != hidden) {
11608                    pkgSetting.setHidden(hidden, userId);
11609                    mSettings.writePackageRestrictionsLPr(userId);
11610                    if (hidden) {
11611                        sendRemoved = true;
11612                    } else {
11613                        sendAdded = true;
11614                    }
11615                }
11616            }
11617            if (sendAdded) {
11618                sendPackageAddedForUser(packageName, pkgSetting, userId);
11619                return true;
11620            }
11621            if (sendRemoved) {
11622                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11623                        "hiding pkg");
11624                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11625                return true;
11626            }
11627        } finally {
11628            Binder.restoreCallingIdentity(callingId);
11629        }
11630        return false;
11631    }
11632
11633    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11634            int userId) {
11635        final PackageRemovedInfo info = new PackageRemovedInfo();
11636        info.removedPackage = packageName;
11637        info.removedUsers = new int[] {userId};
11638        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11639        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11640    }
11641
11642    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11643        if (pkgList.length > 0) {
11644            Bundle extras = new Bundle(1);
11645            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11646
11647            sendPackageBroadcast(
11648                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11649                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11650                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11651                    new int[] {userId});
11652        }
11653    }
11654
11655    /**
11656     * Returns true if application is not found or there was an error. Otherwise it returns
11657     * the hidden state of the package for the given user.
11658     */
11659    @Override
11660    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11661        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11662        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11663                true /* requireFullPermission */, false /* checkShell */,
11664                "getApplicationHidden for user " + userId);
11665        PackageSetting pkgSetting;
11666        long callingId = Binder.clearCallingIdentity();
11667        try {
11668            // writer
11669            synchronized (mPackages) {
11670                pkgSetting = mSettings.mPackages.get(packageName);
11671                if (pkgSetting == null) {
11672                    return true;
11673                }
11674                return pkgSetting.getHidden(userId);
11675            }
11676        } finally {
11677            Binder.restoreCallingIdentity(callingId);
11678        }
11679    }
11680
11681    /**
11682     * @hide
11683     */
11684    @Override
11685    public int installExistingPackageAsUser(String packageName, int userId) {
11686        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11687                null);
11688        PackageSetting pkgSetting;
11689        final int uid = Binder.getCallingUid();
11690        enforceCrossUserPermission(uid, userId,
11691                true /* requireFullPermission */, true /* checkShell */,
11692                "installExistingPackage for user " + userId);
11693        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11694            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11695        }
11696
11697        long callingId = Binder.clearCallingIdentity();
11698        try {
11699            boolean installed = false;
11700
11701            // writer
11702            synchronized (mPackages) {
11703                pkgSetting = mSettings.mPackages.get(packageName);
11704                if (pkgSetting == null) {
11705                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11706                }
11707                if (!pkgSetting.getInstalled(userId)) {
11708                    pkgSetting.setInstalled(true, userId);
11709                    pkgSetting.setHidden(false, userId);
11710                    mSettings.writePackageRestrictionsLPr(userId);
11711                    installed = true;
11712                }
11713            }
11714
11715            if (installed) {
11716                if (pkgSetting.pkg != null) {
11717                    synchronized (mInstallLock) {
11718                        // We don't need to freeze for a brand new install
11719                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11720                    }
11721                }
11722                sendPackageAddedForUser(packageName, pkgSetting, userId);
11723            }
11724        } finally {
11725            Binder.restoreCallingIdentity(callingId);
11726        }
11727
11728        return PackageManager.INSTALL_SUCCEEDED;
11729    }
11730
11731    boolean isUserRestricted(int userId, String restrictionKey) {
11732        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11733        if (restrictions.getBoolean(restrictionKey, false)) {
11734            Log.w(TAG, "User is restricted: " + restrictionKey);
11735            return true;
11736        }
11737        return false;
11738    }
11739
11740    @Override
11741    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11742            int userId) {
11743        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11744        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11745                true /* requireFullPermission */, true /* checkShell */,
11746                "setPackagesSuspended for user " + userId);
11747
11748        if (ArrayUtils.isEmpty(packageNames)) {
11749            return packageNames;
11750        }
11751
11752        // List of package names for whom the suspended state has changed.
11753        List<String> changedPackages = new ArrayList<>(packageNames.length);
11754        // List of package names for whom the suspended state is not set as requested in this
11755        // method.
11756        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11757        long callingId = Binder.clearCallingIdentity();
11758        try {
11759            for (int i = 0; i < packageNames.length; i++) {
11760                String packageName = packageNames[i];
11761                boolean changed = false;
11762                final int appId;
11763                synchronized (mPackages) {
11764                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11765                    if (pkgSetting == null) {
11766                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11767                                + "\". Skipping suspending/un-suspending.");
11768                        unactionedPackages.add(packageName);
11769                        continue;
11770                    }
11771                    appId = pkgSetting.appId;
11772                    if (pkgSetting.getSuspended(userId) != suspended) {
11773                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11774                            unactionedPackages.add(packageName);
11775                            continue;
11776                        }
11777                        pkgSetting.setSuspended(suspended, userId);
11778                        mSettings.writePackageRestrictionsLPr(userId);
11779                        changed = true;
11780                        changedPackages.add(packageName);
11781                    }
11782                }
11783
11784                if (changed && suspended) {
11785                    killApplication(packageName, UserHandle.getUid(userId, appId),
11786                            "suspending package");
11787                }
11788            }
11789        } finally {
11790            Binder.restoreCallingIdentity(callingId);
11791        }
11792
11793        if (!changedPackages.isEmpty()) {
11794            sendPackagesSuspendedForUser(changedPackages.toArray(
11795                    new String[changedPackages.size()]), userId, suspended);
11796        }
11797
11798        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11799    }
11800
11801    @Override
11802    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11803        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11804                true /* requireFullPermission */, false /* checkShell */,
11805                "isPackageSuspendedForUser for user " + userId);
11806        synchronized (mPackages) {
11807            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11808            if (pkgSetting == null) {
11809                throw new IllegalArgumentException("Unknown target package: " + packageName);
11810            }
11811            return pkgSetting.getSuspended(userId);
11812        }
11813    }
11814
11815    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11816        if (isPackageDeviceAdmin(packageName, userId)) {
11817            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11818                    + "\": has an active device admin");
11819            return false;
11820        }
11821
11822        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11823        if (packageName.equals(activeLauncherPackageName)) {
11824            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11825                    + "\": contains the active launcher");
11826            return false;
11827        }
11828
11829        if (packageName.equals(mRequiredInstallerPackage)) {
11830            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11831                    + "\": required for package installation");
11832            return false;
11833        }
11834
11835        if (packageName.equals(mRequiredUninstallerPackage)) {
11836            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11837                    + "\": required for package uninstallation");
11838            return false;
11839        }
11840
11841        if (packageName.equals(mRequiredVerifierPackage)) {
11842            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11843                    + "\": required for package verification");
11844            return false;
11845        }
11846
11847        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11848            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11849                    + "\": is the default dialer");
11850            return false;
11851        }
11852
11853        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11854            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11855                    + "\": protected package");
11856            return false;
11857        }
11858
11859        return true;
11860    }
11861
11862    private String getActiveLauncherPackageName(int userId) {
11863        Intent intent = new Intent(Intent.ACTION_MAIN);
11864        intent.addCategory(Intent.CATEGORY_HOME);
11865        ResolveInfo resolveInfo = resolveIntent(
11866                intent,
11867                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11868                PackageManager.MATCH_DEFAULT_ONLY,
11869                userId);
11870
11871        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11872    }
11873
11874    private String getDefaultDialerPackageName(int userId) {
11875        synchronized (mPackages) {
11876            return mSettings.getDefaultDialerPackageNameLPw(userId);
11877        }
11878    }
11879
11880    @Override
11881    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11882        mContext.enforceCallingOrSelfPermission(
11883                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11884                "Only package verification agents can verify applications");
11885
11886        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11887        final PackageVerificationResponse response = new PackageVerificationResponse(
11888                verificationCode, Binder.getCallingUid());
11889        msg.arg1 = id;
11890        msg.obj = response;
11891        mHandler.sendMessage(msg);
11892    }
11893
11894    @Override
11895    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11896            long millisecondsToDelay) {
11897        mContext.enforceCallingOrSelfPermission(
11898                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11899                "Only package verification agents can extend verification timeouts");
11900
11901        final PackageVerificationState state = mPendingVerification.get(id);
11902        final PackageVerificationResponse response = new PackageVerificationResponse(
11903                verificationCodeAtTimeout, Binder.getCallingUid());
11904
11905        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11906            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11907        }
11908        if (millisecondsToDelay < 0) {
11909            millisecondsToDelay = 0;
11910        }
11911        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11912                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11913            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11914        }
11915
11916        if ((state != null) && !state.timeoutExtended()) {
11917            state.extendTimeout();
11918
11919            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11920            msg.arg1 = id;
11921            msg.obj = response;
11922            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11923        }
11924    }
11925
11926    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11927            int verificationCode, UserHandle user) {
11928        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11929        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11930        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11931        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11932        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11933
11934        mContext.sendBroadcastAsUser(intent, user,
11935                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11936    }
11937
11938    private ComponentName matchComponentForVerifier(String packageName,
11939            List<ResolveInfo> receivers) {
11940        ActivityInfo targetReceiver = null;
11941
11942        final int NR = receivers.size();
11943        for (int i = 0; i < NR; i++) {
11944            final ResolveInfo info = receivers.get(i);
11945            if (info.activityInfo == null) {
11946                continue;
11947            }
11948
11949            if (packageName.equals(info.activityInfo.packageName)) {
11950                targetReceiver = info.activityInfo;
11951                break;
11952            }
11953        }
11954
11955        if (targetReceiver == null) {
11956            return null;
11957        }
11958
11959        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11960    }
11961
11962    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11963            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11964        if (pkgInfo.verifiers.length == 0) {
11965            return null;
11966        }
11967
11968        final int N = pkgInfo.verifiers.length;
11969        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11970        for (int i = 0; i < N; i++) {
11971            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11972
11973            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11974                    receivers);
11975            if (comp == null) {
11976                continue;
11977            }
11978
11979            final int verifierUid = getUidForVerifier(verifierInfo);
11980            if (verifierUid == -1) {
11981                continue;
11982            }
11983
11984            if (DEBUG_VERIFY) {
11985                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11986                        + " with the correct signature");
11987            }
11988            sufficientVerifiers.add(comp);
11989            verificationState.addSufficientVerifier(verifierUid);
11990        }
11991
11992        return sufficientVerifiers;
11993    }
11994
11995    private int getUidForVerifier(VerifierInfo verifierInfo) {
11996        synchronized (mPackages) {
11997            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11998            if (pkg == null) {
11999                return -1;
12000            } else if (pkg.mSignatures.length != 1) {
12001                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12002                        + " has more than one signature; ignoring");
12003                return -1;
12004            }
12005
12006            /*
12007             * If the public key of the package's signature does not match
12008             * our expected public key, then this is a different package and
12009             * we should skip.
12010             */
12011
12012            final byte[] expectedPublicKey;
12013            try {
12014                final Signature verifierSig = pkg.mSignatures[0];
12015                final PublicKey publicKey = verifierSig.getPublicKey();
12016                expectedPublicKey = publicKey.getEncoded();
12017            } catch (CertificateException e) {
12018                return -1;
12019            }
12020
12021            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12022
12023            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12024                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12025                        + " does not have the expected public key; ignoring");
12026                return -1;
12027            }
12028
12029            return pkg.applicationInfo.uid;
12030        }
12031    }
12032
12033    @Override
12034    public void finishPackageInstall(int token, boolean didLaunch) {
12035        enforceSystemOrRoot("Only the system is allowed to finish installs");
12036
12037        if (DEBUG_INSTALL) {
12038            Slog.v(TAG, "BM finishing package install for " + token);
12039        }
12040        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12041
12042        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12043        mHandler.sendMessage(msg);
12044    }
12045
12046    /**
12047     * Get the verification agent timeout.
12048     *
12049     * @return verification timeout in milliseconds
12050     */
12051    private long getVerificationTimeout() {
12052        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12053                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12054                DEFAULT_VERIFICATION_TIMEOUT);
12055    }
12056
12057    /**
12058     * Get the default verification agent response code.
12059     *
12060     * @return default verification response code
12061     */
12062    private int getDefaultVerificationResponse() {
12063        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12064                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12065                DEFAULT_VERIFICATION_RESPONSE);
12066    }
12067
12068    /**
12069     * Check whether or not package verification has been enabled.
12070     *
12071     * @return true if verification should be performed
12072     */
12073    private boolean isVerificationEnabled(int userId, int installFlags) {
12074        if (!DEFAULT_VERIFY_ENABLE) {
12075            return false;
12076        }
12077        // Ephemeral apps don't get the full verification treatment
12078        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12079            if (DEBUG_EPHEMERAL) {
12080                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12081            }
12082            return false;
12083        }
12084
12085        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12086
12087        // Check if installing from ADB
12088        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12089            // Do not run verification in a test harness environment
12090            if (ActivityManager.isRunningInTestHarness()) {
12091                return false;
12092            }
12093            if (ensureVerifyAppsEnabled) {
12094                return true;
12095            }
12096            // Check if the developer does not want package verification for ADB installs
12097            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12098                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12099                return false;
12100            }
12101        }
12102
12103        if (ensureVerifyAppsEnabled) {
12104            return true;
12105        }
12106
12107        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12108                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12109    }
12110
12111    @Override
12112    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12113            throws RemoteException {
12114        mContext.enforceCallingOrSelfPermission(
12115                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12116                "Only intentfilter verification agents can verify applications");
12117
12118        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12119        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12120                Binder.getCallingUid(), verificationCode, failedDomains);
12121        msg.arg1 = id;
12122        msg.obj = response;
12123        mHandler.sendMessage(msg);
12124    }
12125
12126    @Override
12127    public int getIntentVerificationStatus(String packageName, int userId) {
12128        synchronized (mPackages) {
12129            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12130        }
12131    }
12132
12133    @Override
12134    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12135        mContext.enforceCallingOrSelfPermission(
12136                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12137
12138        boolean result = false;
12139        synchronized (mPackages) {
12140            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12141        }
12142        if (result) {
12143            scheduleWritePackageRestrictionsLocked(userId);
12144        }
12145        return result;
12146    }
12147
12148    @Override
12149    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12150            String packageName) {
12151        synchronized (mPackages) {
12152            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12153        }
12154    }
12155
12156    @Override
12157    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12158        if (TextUtils.isEmpty(packageName)) {
12159            return ParceledListSlice.emptyList();
12160        }
12161        synchronized (mPackages) {
12162            PackageParser.Package pkg = mPackages.get(packageName);
12163            if (pkg == null || pkg.activities == null) {
12164                return ParceledListSlice.emptyList();
12165            }
12166            final int count = pkg.activities.size();
12167            ArrayList<IntentFilter> result = new ArrayList<>();
12168            for (int n=0; n<count; n++) {
12169                PackageParser.Activity activity = pkg.activities.get(n);
12170                if (activity.intents != null && activity.intents.size() > 0) {
12171                    result.addAll(activity.intents);
12172                }
12173            }
12174            return new ParceledListSlice<>(result);
12175        }
12176    }
12177
12178    @Override
12179    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12180        mContext.enforceCallingOrSelfPermission(
12181                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12182
12183        synchronized (mPackages) {
12184            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12185            if (packageName != null) {
12186                result |= updateIntentVerificationStatus(packageName,
12187                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12188                        userId);
12189                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12190                        packageName, userId);
12191            }
12192            return result;
12193        }
12194    }
12195
12196    @Override
12197    public String getDefaultBrowserPackageName(int userId) {
12198        synchronized (mPackages) {
12199            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12200        }
12201    }
12202
12203    /**
12204     * Get the "allow unknown sources" setting.
12205     *
12206     * @return the current "allow unknown sources" setting
12207     */
12208    private int getUnknownSourcesSettings() {
12209        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12210                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12211                -1);
12212    }
12213
12214    @Override
12215    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12216        final int uid = Binder.getCallingUid();
12217        // writer
12218        synchronized (mPackages) {
12219            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12220            if (targetPackageSetting == null) {
12221                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12222            }
12223
12224            PackageSetting installerPackageSetting;
12225            if (installerPackageName != null) {
12226                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12227                if (installerPackageSetting == null) {
12228                    throw new IllegalArgumentException("Unknown installer package: "
12229                            + installerPackageName);
12230                }
12231            } else {
12232                installerPackageSetting = null;
12233            }
12234
12235            Signature[] callerSignature;
12236            Object obj = mSettings.getUserIdLPr(uid);
12237            if (obj != null) {
12238                if (obj instanceof SharedUserSetting) {
12239                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12240                } else if (obj instanceof PackageSetting) {
12241                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12242                } else {
12243                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12244                }
12245            } else {
12246                throw new SecurityException("Unknown calling UID: " + uid);
12247            }
12248
12249            // Verify: can't set installerPackageName to a package that is
12250            // not signed with the same cert as the caller.
12251            if (installerPackageSetting != null) {
12252                if (compareSignatures(callerSignature,
12253                        installerPackageSetting.signatures.mSignatures)
12254                        != PackageManager.SIGNATURE_MATCH) {
12255                    throw new SecurityException(
12256                            "Caller does not have same cert as new installer package "
12257                            + installerPackageName);
12258                }
12259            }
12260
12261            // Verify: if target already has an installer package, it must
12262            // be signed with the same cert as the caller.
12263            if (targetPackageSetting.installerPackageName != null) {
12264                PackageSetting setting = mSettings.mPackages.get(
12265                        targetPackageSetting.installerPackageName);
12266                // If the currently set package isn't valid, then it's always
12267                // okay to change it.
12268                if (setting != null) {
12269                    if (compareSignatures(callerSignature,
12270                            setting.signatures.mSignatures)
12271                            != PackageManager.SIGNATURE_MATCH) {
12272                        throw new SecurityException(
12273                                "Caller does not have same cert as old installer package "
12274                                + targetPackageSetting.installerPackageName);
12275                    }
12276                }
12277            }
12278
12279            // Okay!
12280            targetPackageSetting.installerPackageName = installerPackageName;
12281            if (installerPackageName != null) {
12282                mSettings.mInstallerPackages.add(installerPackageName);
12283            }
12284            scheduleWriteSettingsLocked();
12285        }
12286    }
12287
12288    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12289        // Queue up an async operation since the package installation may take a little while.
12290        mHandler.post(new Runnable() {
12291            public void run() {
12292                mHandler.removeCallbacks(this);
12293                 // Result object to be returned
12294                PackageInstalledInfo res = new PackageInstalledInfo();
12295                res.setReturnCode(currentStatus);
12296                res.uid = -1;
12297                res.pkg = null;
12298                res.removedInfo = null;
12299                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12300                    args.doPreInstall(res.returnCode);
12301                    synchronized (mInstallLock) {
12302                        installPackageTracedLI(args, res);
12303                    }
12304                    args.doPostInstall(res.returnCode, res.uid);
12305                }
12306
12307                // A restore should be performed at this point if (a) the install
12308                // succeeded, (b) the operation is not an update, and (c) the new
12309                // package has not opted out of backup participation.
12310                final boolean update = res.removedInfo != null
12311                        && res.removedInfo.removedPackage != null;
12312                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12313                boolean doRestore = !update
12314                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12315
12316                // Set up the post-install work request bookkeeping.  This will be used
12317                // and cleaned up by the post-install event handling regardless of whether
12318                // there's a restore pass performed.  Token values are >= 1.
12319                int token;
12320                if (mNextInstallToken < 0) mNextInstallToken = 1;
12321                token = mNextInstallToken++;
12322
12323                PostInstallData data = new PostInstallData(args, res);
12324                mRunningInstalls.put(token, data);
12325                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12326
12327                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12328                    // Pass responsibility to the Backup Manager.  It will perform a
12329                    // restore if appropriate, then pass responsibility back to the
12330                    // Package Manager to run the post-install observer callbacks
12331                    // and broadcasts.
12332                    IBackupManager bm = IBackupManager.Stub.asInterface(
12333                            ServiceManager.getService(Context.BACKUP_SERVICE));
12334                    if (bm != null) {
12335                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12336                                + " to BM for possible restore");
12337                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12338                        try {
12339                            // TODO: http://b/22388012
12340                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12341                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12342                            } else {
12343                                doRestore = false;
12344                            }
12345                        } catch (RemoteException e) {
12346                            // can't happen; the backup manager is local
12347                        } catch (Exception e) {
12348                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12349                            doRestore = false;
12350                        }
12351                    } else {
12352                        Slog.e(TAG, "Backup Manager not found!");
12353                        doRestore = false;
12354                    }
12355                }
12356
12357                if (!doRestore) {
12358                    // No restore possible, or the Backup Manager was mysteriously not
12359                    // available -- just fire the post-install work request directly.
12360                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12361
12362                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12363
12364                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12365                    mHandler.sendMessage(msg);
12366                }
12367            }
12368        });
12369    }
12370
12371    /**
12372     * Callback from PackageSettings whenever an app is first transitioned out of the
12373     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12374     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12375     * here whether the app is the target of an ongoing install, and only send the
12376     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12377     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12378     * handling.
12379     */
12380    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12381        // Serialize this with the rest of the install-process message chain.  In the
12382        // restore-at-install case, this Runnable will necessarily run before the
12383        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12384        // are coherent.  In the non-restore case, the app has already completed install
12385        // and been launched through some other means, so it is not in a problematic
12386        // state for observers to see the FIRST_LAUNCH signal.
12387        mHandler.post(new Runnable() {
12388            @Override
12389            public void run() {
12390                for (int i = 0; i < mRunningInstalls.size(); i++) {
12391                    final PostInstallData data = mRunningInstalls.valueAt(i);
12392                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12393                        continue;
12394                    }
12395                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12396                        // right package; but is it for the right user?
12397                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12398                            if (userId == data.res.newUsers[uIndex]) {
12399                                if (DEBUG_BACKUP) {
12400                                    Slog.i(TAG, "Package " + pkgName
12401                                            + " being restored so deferring FIRST_LAUNCH");
12402                                }
12403                                return;
12404                            }
12405                        }
12406                    }
12407                }
12408                // didn't find it, so not being restored
12409                if (DEBUG_BACKUP) {
12410                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12411                }
12412                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12413            }
12414        });
12415    }
12416
12417    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12418        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12419                installerPkg, null, userIds);
12420    }
12421
12422    private abstract class HandlerParams {
12423        private static final int MAX_RETRIES = 4;
12424
12425        /**
12426         * Number of times startCopy() has been attempted and had a non-fatal
12427         * error.
12428         */
12429        private int mRetries = 0;
12430
12431        /** User handle for the user requesting the information or installation. */
12432        private final UserHandle mUser;
12433        String traceMethod;
12434        int traceCookie;
12435
12436        HandlerParams(UserHandle user) {
12437            mUser = user;
12438        }
12439
12440        UserHandle getUser() {
12441            return mUser;
12442        }
12443
12444        HandlerParams setTraceMethod(String traceMethod) {
12445            this.traceMethod = traceMethod;
12446            return this;
12447        }
12448
12449        HandlerParams setTraceCookie(int traceCookie) {
12450            this.traceCookie = traceCookie;
12451            return this;
12452        }
12453
12454        final boolean startCopy() {
12455            boolean res;
12456            try {
12457                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12458
12459                if (++mRetries > MAX_RETRIES) {
12460                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12461                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12462                    handleServiceError();
12463                    return false;
12464                } else {
12465                    handleStartCopy();
12466                    res = true;
12467                }
12468            } catch (RemoteException e) {
12469                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12470                mHandler.sendEmptyMessage(MCS_RECONNECT);
12471                res = false;
12472            }
12473            handleReturnCode();
12474            return res;
12475        }
12476
12477        final void serviceError() {
12478            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12479            handleServiceError();
12480            handleReturnCode();
12481        }
12482
12483        abstract void handleStartCopy() throws RemoteException;
12484        abstract void handleServiceError();
12485        abstract void handleReturnCode();
12486    }
12487
12488    class MeasureParams extends HandlerParams {
12489        private final PackageStats mStats;
12490        private boolean mSuccess;
12491
12492        private final IPackageStatsObserver mObserver;
12493
12494        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12495            super(new UserHandle(stats.userHandle));
12496            mObserver = observer;
12497            mStats = stats;
12498        }
12499
12500        @Override
12501        public String toString() {
12502            return "MeasureParams{"
12503                + Integer.toHexString(System.identityHashCode(this))
12504                + " " + mStats.packageName + "}";
12505        }
12506
12507        @Override
12508        void handleStartCopy() throws RemoteException {
12509            synchronized (mInstallLock) {
12510                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12511            }
12512
12513            if (mSuccess) {
12514                boolean mounted = false;
12515                try {
12516                    final String status = Environment.getExternalStorageState();
12517                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12518                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12519                } catch (Exception e) {
12520                }
12521
12522                if (mounted) {
12523                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12524
12525                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12526                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12527
12528                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12529                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12530
12531                    // Always subtract cache size, since it's a subdirectory
12532                    mStats.externalDataSize -= mStats.externalCacheSize;
12533
12534                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12535                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12536
12537                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12538                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12539                }
12540            }
12541        }
12542
12543        @Override
12544        void handleReturnCode() {
12545            if (mObserver != null) {
12546                try {
12547                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12548                } catch (RemoteException e) {
12549                    Slog.i(TAG, "Observer no longer exists.");
12550                }
12551            }
12552        }
12553
12554        @Override
12555        void handleServiceError() {
12556            Slog.e(TAG, "Could not measure application " + mStats.packageName
12557                            + " external storage");
12558        }
12559    }
12560
12561    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12562            throws RemoteException {
12563        long result = 0;
12564        for (File path : paths) {
12565            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12566        }
12567        return result;
12568    }
12569
12570    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12571        for (File path : paths) {
12572            try {
12573                mcs.clearDirectory(path.getAbsolutePath());
12574            } catch (RemoteException e) {
12575            }
12576        }
12577    }
12578
12579    static class OriginInfo {
12580        /**
12581         * Location where install is coming from, before it has been
12582         * copied/renamed into place. This could be a single monolithic APK
12583         * file, or a cluster directory. This location may be untrusted.
12584         */
12585        final File file;
12586        final String cid;
12587
12588        /**
12589         * Flag indicating that {@link #file} or {@link #cid} has already been
12590         * staged, meaning downstream users don't need to defensively copy the
12591         * contents.
12592         */
12593        final boolean staged;
12594
12595        /**
12596         * Flag indicating that {@link #file} or {@link #cid} is an already
12597         * installed app that is being moved.
12598         */
12599        final boolean existing;
12600
12601        final String resolvedPath;
12602        final File resolvedFile;
12603
12604        static OriginInfo fromNothing() {
12605            return new OriginInfo(null, null, false, false);
12606        }
12607
12608        static OriginInfo fromUntrustedFile(File file) {
12609            return new OriginInfo(file, null, false, false);
12610        }
12611
12612        static OriginInfo fromExistingFile(File file) {
12613            return new OriginInfo(file, null, false, true);
12614        }
12615
12616        static OriginInfo fromStagedFile(File file) {
12617            return new OriginInfo(file, null, true, false);
12618        }
12619
12620        static OriginInfo fromStagedContainer(String cid) {
12621            return new OriginInfo(null, cid, true, false);
12622        }
12623
12624        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12625            this.file = file;
12626            this.cid = cid;
12627            this.staged = staged;
12628            this.existing = existing;
12629
12630            if (cid != null) {
12631                resolvedPath = PackageHelper.getSdDir(cid);
12632                resolvedFile = new File(resolvedPath);
12633            } else if (file != null) {
12634                resolvedPath = file.getAbsolutePath();
12635                resolvedFile = file;
12636            } else {
12637                resolvedPath = null;
12638                resolvedFile = null;
12639            }
12640        }
12641    }
12642
12643    static class MoveInfo {
12644        final int moveId;
12645        final String fromUuid;
12646        final String toUuid;
12647        final String packageName;
12648        final String dataAppName;
12649        final int appId;
12650        final String seinfo;
12651        final int targetSdkVersion;
12652
12653        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12654                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12655            this.moveId = moveId;
12656            this.fromUuid = fromUuid;
12657            this.toUuid = toUuid;
12658            this.packageName = packageName;
12659            this.dataAppName = dataAppName;
12660            this.appId = appId;
12661            this.seinfo = seinfo;
12662            this.targetSdkVersion = targetSdkVersion;
12663        }
12664    }
12665
12666    static class VerificationInfo {
12667        /** A constant used to indicate that a uid value is not present. */
12668        public static final int NO_UID = -1;
12669
12670        /** URI referencing where the package was downloaded from. */
12671        final Uri originatingUri;
12672
12673        /** HTTP referrer URI associated with the originatingURI. */
12674        final Uri referrer;
12675
12676        /** UID of the application that the install request originated from. */
12677        final int originatingUid;
12678
12679        /** UID of application requesting the install */
12680        final int installerUid;
12681
12682        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12683            this.originatingUri = originatingUri;
12684            this.referrer = referrer;
12685            this.originatingUid = originatingUid;
12686            this.installerUid = installerUid;
12687        }
12688    }
12689
12690    class InstallParams extends HandlerParams {
12691        final OriginInfo origin;
12692        final MoveInfo move;
12693        final IPackageInstallObserver2 observer;
12694        int installFlags;
12695        final String installerPackageName;
12696        final String volumeUuid;
12697        private InstallArgs mArgs;
12698        private int mRet;
12699        final String packageAbiOverride;
12700        final String[] grantedRuntimePermissions;
12701        final VerificationInfo verificationInfo;
12702        final Certificate[][] certificates;
12703
12704        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12705                int installFlags, String installerPackageName, String volumeUuid,
12706                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12707                String[] grantedPermissions, Certificate[][] certificates) {
12708            super(user);
12709            this.origin = origin;
12710            this.move = move;
12711            this.observer = observer;
12712            this.installFlags = installFlags;
12713            this.installerPackageName = installerPackageName;
12714            this.volumeUuid = volumeUuid;
12715            this.verificationInfo = verificationInfo;
12716            this.packageAbiOverride = packageAbiOverride;
12717            this.grantedRuntimePermissions = grantedPermissions;
12718            this.certificates = certificates;
12719        }
12720
12721        @Override
12722        public String toString() {
12723            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12724                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12725        }
12726
12727        private int installLocationPolicy(PackageInfoLite pkgLite) {
12728            String packageName = pkgLite.packageName;
12729            int installLocation = pkgLite.installLocation;
12730            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12731            // reader
12732            synchronized (mPackages) {
12733                // Currently installed package which the new package is attempting to replace or
12734                // null if no such package is installed.
12735                PackageParser.Package installedPkg = mPackages.get(packageName);
12736                // Package which currently owns the data which the new package will own if installed.
12737                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12738                // will be null whereas dataOwnerPkg will contain information about the package
12739                // which was uninstalled while keeping its data.
12740                PackageParser.Package dataOwnerPkg = installedPkg;
12741                if (dataOwnerPkg  == null) {
12742                    PackageSetting ps = mSettings.mPackages.get(packageName);
12743                    if (ps != null) {
12744                        dataOwnerPkg = ps.pkg;
12745                    }
12746                }
12747
12748                if (dataOwnerPkg != null) {
12749                    // If installed, the package will get access to data left on the device by its
12750                    // predecessor. As a security measure, this is permited only if this is not a
12751                    // version downgrade or if the predecessor package is marked as debuggable and
12752                    // a downgrade is explicitly requested.
12753                    //
12754                    // On debuggable platform builds, downgrades are permitted even for
12755                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12756                    // not offer security guarantees and thus it's OK to disable some security
12757                    // mechanisms to make debugging/testing easier on those builds. However, even on
12758                    // debuggable builds downgrades of packages are permitted only if requested via
12759                    // installFlags. This is because we aim to keep the behavior of debuggable
12760                    // platform builds as close as possible to the behavior of non-debuggable
12761                    // platform builds.
12762                    final boolean downgradeRequested =
12763                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12764                    final boolean packageDebuggable =
12765                                (dataOwnerPkg.applicationInfo.flags
12766                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12767                    final boolean downgradePermitted =
12768                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12769                    if (!downgradePermitted) {
12770                        try {
12771                            checkDowngrade(dataOwnerPkg, pkgLite);
12772                        } catch (PackageManagerException e) {
12773                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12774                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12775                        }
12776                    }
12777                }
12778
12779                if (installedPkg != null) {
12780                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12781                        // Check for updated system application.
12782                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12783                            if (onSd) {
12784                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12785                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12786                            }
12787                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12788                        } else {
12789                            if (onSd) {
12790                                // Install flag overrides everything.
12791                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12792                            }
12793                            // If current upgrade specifies particular preference
12794                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12795                                // Application explicitly specified internal.
12796                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12797                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12798                                // App explictly prefers external. Let policy decide
12799                            } else {
12800                                // Prefer previous location
12801                                if (isExternal(installedPkg)) {
12802                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12803                                }
12804                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12805                            }
12806                        }
12807                    } else {
12808                        // Invalid install. Return error code
12809                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12810                    }
12811                }
12812            }
12813            // All the special cases have been taken care of.
12814            // Return result based on recommended install location.
12815            if (onSd) {
12816                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12817            }
12818            return pkgLite.recommendedInstallLocation;
12819        }
12820
12821        /*
12822         * Invoke remote method to get package information and install
12823         * location values. Override install location based on default
12824         * policy if needed and then create install arguments based
12825         * on the install location.
12826         */
12827        public void handleStartCopy() throws RemoteException {
12828            int ret = PackageManager.INSTALL_SUCCEEDED;
12829
12830            // If we're already staged, we've firmly committed to an install location
12831            if (origin.staged) {
12832                if (origin.file != null) {
12833                    installFlags |= PackageManager.INSTALL_INTERNAL;
12834                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12835                } else if (origin.cid != null) {
12836                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12837                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12838                } else {
12839                    throw new IllegalStateException("Invalid stage location");
12840                }
12841            }
12842
12843            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12844            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12845            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12846            PackageInfoLite pkgLite = null;
12847
12848            if (onInt && onSd) {
12849                // Check if both bits are set.
12850                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12851                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12852            } else if (onSd && ephemeral) {
12853                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12854                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12855            } else {
12856                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12857                        packageAbiOverride);
12858
12859                if (DEBUG_EPHEMERAL && ephemeral) {
12860                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12861                }
12862
12863                /*
12864                 * If we have too little free space, try to free cache
12865                 * before giving up.
12866                 */
12867                if (!origin.staged && pkgLite.recommendedInstallLocation
12868                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12869                    // TODO: focus freeing disk space on the target device
12870                    final StorageManager storage = StorageManager.from(mContext);
12871                    final long lowThreshold = storage.getStorageLowBytes(
12872                            Environment.getDataDirectory());
12873
12874                    final long sizeBytes = mContainerService.calculateInstalledSize(
12875                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12876
12877                    try {
12878                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12879                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12880                                installFlags, packageAbiOverride);
12881                    } catch (InstallerException e) {
12882                        Slog.w(TAG, "Failed to free cache", e);
12883                    }
12884
12885                    /*
12886                     * The cache free must have deleted the file we
12887                     * downloaded to install.
12888                     *
12889                     * TODO: fix the "freeCache" call to not delete
12890                     *       the file we care about.
12891                     */
12892                    if (pkgLite.recommendedInstallLocation
12893                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12894                        pkgLite.recommendedInstallLocation
12895                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12896                    }
12897                }
12898            }
12899
12900            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12901                int loc = pkgLite.recommendedInstallLocation;
12902                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12903                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12904                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12905                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12906                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12907                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12908                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12909                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12910                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12911                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12912                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12913                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12914                } else {
12915                    // Override with defaults if needed.
12916                    loc = installLocationPolicy(pkgLite);
12917                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12918                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12919                    } else if (!onSd && !onInt) {
12920                        // Override install location with flags
12921                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12922                            // Set the flag to install on external media.
12923                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12924                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12925                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12926                            if (DEBUG_EPHEMERAL) {
12927                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12928                            }
12929                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12930                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12931                                    |PackageManager.INSTALL_INTERNAL);
12932                        } else {
12933                            // Make sure the flag for installing on external
12934                            // media is unset
12935                            installFlags |= PackageManager.INSTALL_INTERNAL;
12936                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12937                        }
12938                    }
12939                }
12940            }
12941
12942            final InstallArgs args = createInstallArgs(this);
12943            mArgs = args;
12944
12945            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12946                // TODO: http://b/22976637
12947                // Apps installed for "all" users use the device owner to verify the app
12948                UserHandle verifierUser = getUser();
12949                if (verifierUser == UserHandle.ALL) {
12950                    verifierUser = UserHandle.SYSTEM;
12951                }
12952
12953                /*
12954                 * Determine if we have any installed package verifiers. If we
12955                 * do, then we'll defer to them to verify the packages.
12956                 */
12957                final int requiredUid = mRequiredVerifierPackage == null ? -1
12958                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12959                                verifierUser.getIdentifier());
12960                if (!origin.existing && requiredUid != -1
12961                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12962                    final Intent verification = new Intent(
12963                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12964                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12965                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12966                            PACKAGE_MIME_TYPE);
12967                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12968
12969                    // Query all live verifiers based on current user state
12970                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12971                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12972
12973                    if (DEBUG_VERIFY) {
12974                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12975                                + verification.toString() + " with " + pkgLite.verifiers.length
12976                                + " optional verifiers");
12977                    }
12978
12979                    final int verificationId = mPendingVerificationToken++;
12980
12981                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12982
12983                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12984                            installerPackageName);
12985
12986                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12987                            installFlags);
12988
12989                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12990                            pkgLite.packageName);
12991
12992                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12993                            pkgLite.versionCode);
12994
12995                    if (verificationInfo != null) {
12996                        if (verificationInfo.originatingUri != null) {
12997                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12998                                    verificationInfo.originatingUri);
12999                        }
13000                        if (verificationInfo.referrer != null) {
13001                            verification.putExtra(Intent.EXTRA_REFERRER,
13002                                    verificationInfo.referrer);
13003                        }
13004                        if (verificationInfo.originatingUid >= 0) {
13005                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13006                                    verificationInfo.originatingUid);
13007                        }
13008                        if (verificationInfo.installerUid >= 0) {
13009                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13010                                    verificationInfo.installerUid);
13011                        }
13012                    }
13013
13014                    final PackageVerificationState verificationState = new PackageVerificationState(
13015                            requiredUid, args);
13016
13017                    mPendingVerification.append(verificationId, verificationState);
13018
13019                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13020                            receivers, verificationState);
13021
13022                    /*
13023                     * If any sufficient verifiers were listed in the package
13024                     * manifest, attempt to ask them.
13025                     */
13026                    if (sufficientVerifiers != null) {
13027                        final int N = sufficientVerifiers.size();
13028                        if (N == 0) {
13029                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13030                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13031                        } else {
13032                            for (int i = 0; i < N; i++) {
13033                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13034
13035                                final Intent sufficientIntent = new Intent(verification);
13036                                sufficientIntent.setComponent(verifierComponent);
13037                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13038                            }
13039                        }
13040                    }
13041
13042                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13043                            mRequiredVerifierPackage, receivers);
13044                    if (ret == PackageManager.INSTALL_SUCCEEDED
13045                            && mRequiredVerifierPackage != null) {
13046                        Trace.asyncTraceBegin(
13047                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13048                        /*
13049                         * Send the intent to the required verification agent,
13050                         * but only start the verification timeout after the
13051                         * target BroadcastReceivers have run.
13052                         */
13053                        verification.setComponent(requiredVerifierComponent);
13054                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13055                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13056                                new BroadcastReceiver() {
13057                                    @Override
13058                                    public void onReceive(Context context, Intent intent) {
13059                                        final Message msg = mHandler
13060                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13061                                        msg.arg1 = verificationId;
13062                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13063                                    }
13064                                }, null, 0, null, null);
13065
13066                        /*
13067                         * We don't want the copy to proceed until verification
13068                         * succeeds, so null out this field.
13069                         */
13070                        mArgs = null;
13071                    }
13072                } else {
13073                    /*
13074                     * No package verification is enabled, so immediately start
13075                     * the remote call to initiate copy using temporary file.
13076                     */
13077                    ret = args.copyApk(mContainerService, true);
13078                }
13079            }
13080
13081            mRet = ret;
13082        }
13083
13084        @Override
13085        void handleReturnCode() {
13086            // If mArgs is null, then MCS couldn't be reached. When it
13087            // reconnects, it will try again to install. At that point, this
13088            // will succeed.
13089            if (mArgs != null) {
13090                processPendingInstall(mArgs, mRet);
13091            }
13092        }
13093
13094        @Override
13095        void handleServiceError() {
13096            mArgs = createInstallArgs(this);
13097            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13098        }
13099
13100        public boolean isForwardLocked() {
13101            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13102        }
13103    }
13104
13105    /**
13106     * Used during creation of InstallArgs
13107     *
13108     * @param installFlags package installation flags
13109     * @return true if should be installed on external storage
13110     */
13111    private static boolean installOnExternalAsec(int installFlags) {
13112        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13113            return false;
13114        }
13115        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13116            return true;
13117        }
13118        return false;
13119    }
13120
13121    /**
13122     * Used during creation of InstallArgs
13123     *
13124     * @param installFlags package installation flags
13125     * @return true if should be installed as forward locked
13126     */
13127    private static boolean installForwardLocked(int installFlags) {
13128        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13129    }
13130
13131    private InstallArgs createInstallArgs(InstallParams params) {
13132        if (params.move != null) {
13133            return new MoveInstallArgs(params);
13134        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13135            return new AsecInstallArgs(params);
13136        } else {
13137            return new FileInstallArgs(params);
13138        }
13139    }
13140
13141    /**
13142     * Create args that describe an existing installed package. Typically used
13143     * when cleaning up old installs, or used as a move source.
13144     */
13145    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13146            String resourcePath, String[] instructionSets) {
13147        final boolean isInAsec;
13148        if (installOnExternalAsec(installFlags)) {
13149            /* Apps on SD card are always in ASEC containers. */
13150            isInAsec = true;
13151        } else if (installForwardLocked(installFlags)
13152                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13153            /*
13154             * Forward-locked apps are only in ASEC containers if they're the
13155             * new style
13156             */
13157            isInAsec = true;
13158        } else {
13159            isInAsec = false;
13160        }
13161
13162        if (isInAsec) {
13163            return new AsecInstallArgs(codePath, instructionSets,
13164                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13165        } else {
13166            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13167        }
13168    }
13169
13170    static abstract class InstallArgs {
13171        /** @see InstallParams#origin */
13172        final OriginInfo origin;
13173        /** @see InstallParams#move */
13174        final MoveInfo move;
13175
13176        final IPackageInstallObserver2 observer;
13177        // Always refers to PackageManager flags only
13178        final int installFlags;
13179        final String installerPackageName;
13180        final String volumeUuid;
13181        final UserHandle user;
13182        final String abiOverride;
13183        final String[] installGrantPermissions;
13184        /** If non-null, drop an async trace when the install completes */
13185        final String traceMethod;
13186        final int traceCookie;
13187        final Certificate[][] certificates;
13188
13189        // The list of instruction sets supported by this app. This is currently
13190        // only used during the rmdex() phase to clean up resources. We can get rid of this
13191        // if we move dex files under the common app path.
13192        /* nullable */ String[] instructionSets;
13193
13194        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13195                int installFlags, String installerPackageName, String volumeUuid,
13196                UserHandle user, String[] instructionSets,
13197                String abiOverride, String[] installGrantPermissions,
13198                String traceMethod, int traceCookie, Certificate[][] certificates) {
13199            this.origin = origin;
13200            this.move = move;
13201            this.installFlags = installFlags;
13202            this.observer = observer;
13203            this.installerPackageName = installerPackageName;
13204            this.volumeUuid = volumeUuid;
13205            this.user = user;
13206            this.instructionSets = instructionSets;
13207            this.abiOverride = abiOverride;
13208            this.installGrantPermissions = installGrantPermissions;
13209            this.traceMethod = traceMethod;
13210            this.traceCookie = traceCookie;
13211            this.certificates = certificates;
13212        }
13213
13214        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13215        abstract int doPreInstall(int status);
13216
13217        /**
13218         * Rename package into final resting place. All paths on the given
13219         * scanned package should be updated to reflect the rename.
13220         */
13221        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13222        abstract int doPostInstall(int status, int uid);
13223
13224        /** @see PackageSettingBase#codePathString */
13225        abstract String getCodePath();
13226        /** @see PackageSettingBase#resourcePathString */
13227        abstract String getResourcePath();
13228
13229        // Need installer lock especially for dex file removal.
13230        abstract void cleanUpResourcesLI();
13231        abstract boolean doPostDeleteLI(boolean delete);
13232
13233        /**
13234         * Called before the source arguments are copied. This is used mostly
13235         * for MoveParams when it needs to read the source file to put it in the
13236         * destination.
13237         */
13238        int doPreCopy() {
13239            return PackageManager.INSTALL_SUCCEEDED;
13240        }
13241
13242        /**
13243         * Called after the source arguments are copied. This is used mostly for
13244         * MoveParams when it needs to read the source file to put it in the
13245         * destination.
13246         */
13247        int doPostCopy(int uid) {
13248            return PackageManager.INSTALL_SUCCEEDED;
13249        }
13250
13251        protected boolean isFwdLocked() {
13252            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13253        }
13254
13255        protected boolean isExternalAsec() {
13256            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13257        }
13258
13259        protected boolean isEphemeral() {
13260            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13261        }
13262
13263        UserHandle getUser() {
13264            return user;
13265        }
13266    }
13267
13268    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13269        if (!allCodePaths.isEmpty()) {
13270            if (instructionSets == null) {
13271                throw new IllegalStateException("instructionSet == null");
13272            }
13273            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13274            for (String codePath : allCodePaths) {
13275                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13276                    try {
13277                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13278                    } catch (InstallerException ignored) {
13279                    }
13280                }
13281            }
13282        }
13283    }
13284
13285    /**
13286     * Logic to handle installation of non-ASEC applications, including copying
13287     * and renaming logic.
13288     */
13289    class FileInstallArgs extends InstallArgs {
13290        private File codeFile;
13291        private File resourceFile;
13292
13293        // Example topology:
13294        // /data/app/com.example/base.apk
13295        // /data/app/com.example/split_foo.apk
13296        // /data/app/com.example/lib/arm/libfoo.so
13297        // /data/app/com.example/lib/arm64/libfoo.so
13298        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13299
13300        /** New install */
13301        FileInstallArgs(InstallParams params) {
13302            super(params.origin, params.move, params.observer, params.installFlags,
13303                    params.installerPackageName, params.volumeUuid,
13304                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13305                    params.grantedRuntimePermissions,
13306                    params.traceMethod, params.traceCookie, params.certificates);
13307            if (isFwdLocked()) {
13308                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13309            }
13310        }
13311
13312        /** Existing install */
13313        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13314            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13315                    null, null, null, 0, null /*certificates*/);
13316            this.codeFile = (codePath != null) ? new File(codePath) : null;
13317            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13318        }
13319
13320        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13321            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13322            try {
13323                return doCopyApk(imcs, temp);
13324            } finally {
13325                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13326            }
13327        }
13328
13329        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13330            if (origin.staged) {
13331                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13332                codeFile = origin.file;
13333                resourceFile = origin.file;
13334                return PackageManager.INSTALL_SUCCEEDED;
13335            }
13336
13337            try {
13338                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13339                final File tempDir =
13340                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13341                codeFile = tempDir;
13342                resourceFile = tempDir;
13343            } catch (IOException e) {
13344                Slog.w(TAG, "Failed to create copy file: " + e);
13345                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13346            }
13347
13348            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13349                @Override
13350                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13351                    if (!FileUtils.isValidExtFilename(name)) {
13352                        throw new IllegalArgumentException("Invalid filename: " + name);
13353                    }
13354                    try {
13355                        final File file = new File(codeFile, name);
13356                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13357                                O_RDWR | O_CREAT, 0644);
13358                        Os.chmod(file.getAbsolutePath(), 0644);
13359                        return new ParcelFileDescriptor(fd);
13360                    } catch (ErrnoException e) {
13361                        throw new RemoteException("Failed to open: " + e.getMessage());
13362                    }
13363                }
13364            };
13365
13366            int ret = PackageManager.INSTALL_SUCCEEDED;
13367            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13368            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13369                Slog.e(TAG, "Failed to copy package");
13370                return ret;
13371            }
13372
13373            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13374            NativeLibraryHelper.Handle handle = null;
13375            try {
13376                handle = NativeLibraryHelper.Handle.create(codeFile);
13377                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13378                        abiOverride);
13379            } catch (IOException e) {
13380                Slog.e(TAG, "Copying native libraries failed", e);
13381                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13382            } finally {
13383                IoUtils.closeQuietly(handle);
13384            }
13385
13386            return ret;
13387        }
13388
13389        int doPreInstall(int status) {
13390            if (status != PackageManager.INSTALL_SUCCEEDED) {
13391                cleanUp();
13392            }
13393            return status;
13394        }
13395
13396        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13397            if (status != PackageManager.INSTALL_SUCCEEDED) {
13398                cleanUp();
13399                return false;
13400            }
13401
13402            final File targetDir = codeFile.getParentFile();
13403            final File beforeCodeFile = codeFile;
13404            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13405
13406            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13407            try {
13408                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13409            } catch (ErrnoException e) {
13410                Slog.w(TAG, "Failed to rename", e);
13411                return false;
13412            }
13413
13414            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13415                Slog.w(TAG, "Failed to restorecon");
13416                return false;
13417            }
13418
13419            // Reflect the rename internally
13420            codeFile = afterCodeFile;
13421            resourceFile = afterCodeFile;
13422
13423            // Reflect the rename in scanned details
13424            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13425            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13426                    afterCodeFile, pkg.baseCodePath));
13427            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13428                    afterCodeFile, pkg.splitCodePaths));
13429
13430            // Reflect the rename in app info
13431            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13432            pkg.setApplicationInfoCodePath(pkg.codePath);
13433            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13434            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13435            pkg.setApplicationInfoResourcePath(pkg.codePath);
13436            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13437            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13438
13439            return true;
13440        }
13441
13442        int doPostInstall(int status, int uid) {
13443            if (status != PackageManager.INSTALL_SUCCEEDED) {
13444                cleanUp();
13445            }
13446            return status;
13447        }
13448
13449        @Override
13450        String getCodePath() {
13451            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13452        }
13453
13454        @Override
13455        String getResourcePath() {
13456            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13457        }
13458
13459        private boolean cleanUp() {
13460            if (codeFile == null || !codeFile.exists()) {
13461                return false;
13462            }
13463
13464            removeCodePathLI(codeFile);
13465
13466            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13467                resourceFile.delete();
13468            }
13469
13470            return true;
13471        }
13472
13473        void cleanUpResourcesLI() {
13474            // Try enumerating all code paths before deleting
13475            List<String> allCodePaths = Collections.EMPTY_LIST;
13476            if (codeFile != null && codeFile.exists()) {
13477                try {
13478                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13479                    allCodePaths = pkg.getAllCodePaths();
13480                } catch (PackageParserException e) {
13481                    // Ignored; we tried our best
13482                }
13483            }
13484
13485            cleanUp();
13486            removeDexFiles(allCodePaths, instructionSets);
13487        }
13488
13489        boolean doPostDeleteLI(boolean delete) {
13490            // XXX err, shouldn't we respect the delete flag?
13491            cleanUpResourcesLI();
13492            return true;
13493        }
13494    }
13495
13496    private boolean isAsecExternal(String cid) {
13497        final String asecPath = PackageHelper.getSdFilesystem(cid);
13498        return !asecPath.startsWith(mAsecInternalPath);
13499    }
13500
13501    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13502            PackageManagerException {
13503        if (copyRet < 0) {
13504            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13505                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13506                throw new PackageManagerException(copyRet, message);
13507            }
13508        }
13509    }
13510
13511    /**
13512     * Extract the MountService "container ID" from the full code path of an
13513     * .apk.
13514     */
13515    static String cidFromCodePath(String fullCodePath) {
13516        int eidx = fullCodePath.lastIndexOf("/");
13517        String subStr1 = fullCodePath.substring(0, eidx);
13518        int sidx = subStr1.lastIndexOf("/");
13519        return subStr1.substring(sidx+1, eidx);
13520    }
13521
13522    /**
13523     * Logic to handle installation of ASEC applications, including copying and
13524     * renaming logic.
13525     */
13526    class AsecInstallArgs extends InstallArgs {
13527        static final String RES_FILE_NAME = "pkg.apk";
13528        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13529
13530        String cid;
13531        String packagePath;
13532        String resourcePath;
13533
13534        /** New install */
13535        AsecInstallArgs(InstallParams params) {
13536            super(params.origin, params.move, params.observer, params.installFlags,
13537                    params.installerPackageName, params.volumeUuid,
13538                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13539                    params.grantedRuntimePermissions,
13540                    params.traceMethod, params.traceCookie, params.certificates);
13541        }
13542
13543        /** Existing install */
13544        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13545                        boolean isExternal, boolean isForwardLocked) {
13546            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13547              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13548                    instructionSets, null, null, null, 0, null /*certificates*/);
13549            // Hackily pretend we're still looking at a full code path
13550            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13551                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13552            }
13553
13554            // Extract cid from fullCodePath
13555            int eidx = fullCodePath.lastIndexOf("/");
13556            String subStr1 = fullCodePath.substring(0, eidx);
13557            int sidx = subStr1.lastIndexOf("/");
13558            cid = subStr1.substring(sidx+1, eidx);
13559            setMountPath(subStr1);
13560        }
13561
13562        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13563            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13564              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13565                    instructionSets, null, null, null, 0, null /*certificates*/);
13566            this.cid = cid;
13567            setMountPath(PackageHelper.getSdDir(cid));
13568        }
13569
13570        void createCopyFile() {
13571            cid = mInstallerService.allocateExternalStageCidLegacy();
13572        }
13573
13574        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13575            if (origin.staged && origin.cid != null) {
13576                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13577                cid = origin.cid;
13578                setMountPath(PackageHelper.getSdDir(cid));
13579                return PackageManager.INSTALL_SUCCEEDED;
13580            }
13581
13582            if (temp) {
13583                createCopyFile();
13584            } else {
13585                /*
13586                 * Pre-emptively destroy the container since it's destroyed if
13587                 * copying fails due to it existing anyway.
13588                 */
13589                PackageHelper.destroySdDir(cid);
13590            }
13591
13592            final String newMountPath = imcs.copyPackageToContainer(
13593                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13594                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13595
13596            if (newMountPath != null) {
13597                setMountPath(newMountPath);
13598                return PackageManager.INSTALL_SUCCEEDED;
13599            } else {
13600                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13601            }
13602        }
13603
13604        @Override
13605        String getCodePath() {
13606            return packagePath;
13607        }
13608
13609        @Override
13610        String getResourcePath() {
13611            return resourcePath;
13612        }
13613
13614        int doPreInstall(int status) {
13615            if (status != PackageManager.INSTALL_SUCCEEDED) {
13616                // Destroy container
13617                PackageHelper.destroySdDir(cid);
13618            } else {
13619                boolean mounted = PackageHelper.isContainerMounted(cid);
13620                if (!mounted) {
13621                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13622                            Process.SYSTEM_UID);
13623                    if (newMountPath != null) {
13624                        setMountPath(newMountPath);
13625                    } else {
13626                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13627                    }
13628                }
13629            }
13630            return status;
13631        }
13632
13633        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13634            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13635            String newMountPath = null;
13636            if (PackageHelper.isContainerMounted(cid)) {
13637                // Unmount the container
13638                if (!PackageHelper.unMountSdDir(cid)) {
13639                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13640                    return false;
13641                }
13642            }
13643            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13644                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13645                        " which might be stale. Will try to clean up.");
13646                // Clean up the stale container and proceed to recreate.
13647                if (!PackageHelper.destroySdDir(newCacheId)) {
13648                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13649                    return false;
13650                }
13651                // Successfully cleaned up stale container. Try to rename again.
13652                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13653                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13654                            + " inspite of cleaning it up.");
13655                    return false;
13656                }
13657            }
13658            if (!PackageHelper.isContainerMounted(newCacheId)) {
13659                Slog.w(TAG, "Mounting container " + newCacheId);
13660                newMountPath = PackageHelper.mountSdDir(newCacheId,
13661                        getEncryptKey(), Process.SYSTEM_UID);
13662            } else {
13663                newMountPath = PackageHelper.getSdDir(newCacheId);
13664            }
13665            if (newMountPath == null) {
13666                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13667                return false;
13668            }
13669            Log.i(TAG, "Succesfully renamed " + cid +
13670                    " to " + newCacheId +
13671                    " at new path: " + newMountPath);
13672            cid = newCacheId;
13673
13674            final File beforeCodeFile = new File(packagePath);
13675            setMountPath(newMountPath);
13676            final File afterCodeFile = new File(packagePath);
13677
13678            // Reflect the rename in scanned details
13679            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13680            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13681                    afterCodeFile, pkg.baseCodePath));
13682            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13683                    afterCodeFile, pkg.splitCodePaths));
13684
13685            // Reflect the rename in app info
13686            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13687            pkg.setApplicationInfoCodePath(pkg.codePath);
13688            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13689            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13690            pkg.setApplicationInfoResourcePath(pkg.codePath);
13691            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13692            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13693
13694            return true;
13695        }
13696
13697        private void setMountPath(String mountPath) {
13698            final File mountFile = new File(mountPath);
13699
13700            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13701            if (monolithicFile.exists()) {
13702                packagePath = monolithicFile.getAbsolutePath();
13703                if (isFwdLocked()) {
13704                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13705                } else {
13706                    resourcePath = packagePath;
13707                }
13708            } else {
13709                packagePath = mountFile.getAbsolutePath();
13710                resourcePath = packagePath;
13711            }
13712        }
13713
13714        int doPostInstall(int status, int uid) {
13715            if (status != PackageManager.INSTALL_SUCCEEDED) {
13716                cleanUp();
13717            } else {
13718                final int groupOwner;
13719                final String protectedFile;
13720                if (isFwdLocked()) {
13721                    groupOwner = UserHandle.getSharedAppGid(uid);
13722                    protectedFile = RES_FILE_NAME;
13723                } else {
13724                    groupOwner = -1;
13725                    protectedFile = null;
13726                }
13727
13728                if (uid < Process.FIRST_APPLICATION_UID
13729                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13730                    Slog.e(TAG, "Failed to finalize " + cid);
13731                    PackageHelper.destroySdDir(cid);
13732                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13733                }
13734
13735                boolean mounted = PackageHelper.isContainerMounted(cid);
13736                if (!mounted) {
13737                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13738                }
13739            }
13740            return status;
13741        }
13742
13743        private void cleanUp() {
13744            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13745
13746            // Destroy secure container
13747            PackageHelper.destroySdDir(cid);
13748        }
13749
13750        private List<String> getAllCodePaths() {
13751            final File codeFile = new File(getCodePath());
13752            if (codeFile != null && codeFile.exists()) {
13753                try {
13754                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13755                    return pkg.getAllCodePaths();
13756                } catch (PackageParserException e) {
13757                    // Ignored; we tried our best
13758                }
13759            }
13760            return Collections.EMPTY_LIST;
13761        }
13762
13763        void cleanUpResourcesLI() {
13764            // Enumerate all code paths before deleting
13765            cleanUpResourcesLI(getAllCodePaths());
13766        }
13767
13768        private void cleanUpResourcesLI(List<String> allCodePaths) {
13769            cleanUp();
13770            removeDexFiles(allCodePaths, instructionSets);
13771        }
13772
13773        String getPackageName() {
13774            return getAsecPackageName(cid);
13775        }
13776
13777        boolean doPostDeleteLI(boolean delete) {
13778            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13779            final List<String> allCodePaths = getAllCodePaths();
13780            boolean mounted = PackageHelper.isContainerMounted(cid);
13781            if (mounted) {
13782                // Unmount first
13783                if (PackageHelper.unMountSdDir(cid)) {
13784                    mounted = false;
13785                }
13786            }
13787            if (!mounted && delete) {
13788                cleanUpResourcesLI(allCodePaths);
13789            }
13790            return !mounted;
13791        }
13792
13793        @Override
13794        int doPreCopy() {
13795            if (isFwdLocked()) {
13796                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13797                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13798                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13799                }
13800            }
13801
13802            return PackageManager.INSTALL_SUCCEEDED;
13803        }
13804
13805        @Override
13806        int doPostCopy(int uid) {
13807            if (isFwdLocked()) {
13808                if (uid < Process.FIRST_APPLICATION_UID
13809                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13810                                RES_FILE_NAME)) {
13811                    Slog.e(TAG, "Failed to finalize " + cid);
13812                    PackageHelper.destroySdDir(cid);
13813                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13814                }
13815            }
13816
13817            return PackageManager.INSTALL_SUCCEEDED;
13818        }
13819    }
13820
13821    /**
13822     * Logic to handle movement of existing installed applications.
13823     */
13824    class MoveInstallArgs extends InstallArgs {
13825        private File codeFile;
13826        private File resourceFile;
13827
13828        /** New install */
13829        MoveInstallArgs(InstallParams params) {
13830            super(params.origin, params.move, params.observer, params.installFlags,
13831                    params.installerPackageName, params.volumeUuid,
13832                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13833                    params.grantedRuntimePermissions,
13834                    params.traceMethod, params.traceCookie, params.certificates);
13835        }
13836
13837        int copyApk(IMediaContainerService imcs, boolean temp) {
13838            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13839                    + move.fromUuid + " to " + move.toUuid);
13840            synchronized (mInstaller) {
13841                try {
13842                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13843                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13844                } catch (InstallerException e) {
13845                    Slog.w(TAG, "Failed to move app", e);
13846                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13847                }
13848            }
13849
13850            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13851            resourceFile = codeFile;
13852            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13853
13854            return PackageManager.INSTALL_SUCCEEDED;
13855        }
13856
13857        int doPreInstall(int status) {
13858            if (status != PackageManager.INSTALL_SUCCEEDED) {
13859                cleanUp(move.toUuid);
13860            }
13861            return status;
13862        }
13863
13864        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13865            if (status != PackageManager.INSTALL_SUCCEEDED) {
13866                cleanUp(move.toUuid);
13867                return false;
13868            }
13869
13870            // Reflect the move in app info
13871            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13872            pkg.setApplicationInfoCodePath(pkg.codePath);
13873            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13874            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13875            pkg.setApplicationInfoResourcePath(pkg.codePath);
13876            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13877            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13878
13879            return true;
13880        }
13881
13882        int doPostInstall(int status, int uid) {
13883            if (status == PackageManager.INSTALL_SUCCEEDED) {
13884                cleanUp(move.fromUuid);
13885            } else {
13886                cleanUp(move.toUuid);
13887            }
13888            return status;
13889        }
13890
13891        @Override
13892        String getCodePath() {
13893            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13894        }
13895
13896        @Override
13897        String getResourcePath() {
13898            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13899        }
13900
13901        private boolean cleanUp(String volumeUuid) {
13902            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13903                    move.dataAppName);
13904            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13905            final int[] userIds = sUserManager.getUserIds();
13906            synchronized (mInstallLock) {
13907                // Clean up both app data and code
13908                // All package moves are frozen until finished
13909                for (int userId : userIds) {
13910                    try {
13911                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13912                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13913                    } catch (InstallerException e) {
13914                        Slog.w(TAG, String.valueOf(e));
13915                    }
13916                }
13917                removeCodePathLI(codeFile);
13918            }
13919            return true;
13920        }
13921
13922        void cleanUpResourcesLI() {
13923            throw new UnsupportedOperationException();
13924        }
13925
13926        boolean doPostDeleteLI(boolean delete) {
13927            throw new UnsupportedOperationException();
13928        }
13929    }
13930
13931    static String getAsecPackageName(String packageCid) {
13932        int idx = packageCid.lastIndexOf("-");
13933        if (idx == -1) {
13934            return packageCid;
13935        }
13936        return packageCid.substring(0, idx);
13937    }
13938
13939    // Utility method used to create code paths based on package name and available index.
13940    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13941        String idxStr = "";
13942        int idx = 1;
13943        // Fall back to default value of idx=1 if prefix is not
13944        // part of oldCodePath
13945        if (oldCodePath != null) {
13946            String subStr = oldCodePath;
13947            // Drop the suffix right away
13948            if (suffix != null && subStr.endsWith(suffix)) {
13949                subStr = subStr.substring(0, subStr.length() - suffix.length());
13950            }
13951            // If oldCodePath already contains prefix find out the
13952            // ending index to either increment or decrement.
13953            int sidx = subStr.lastIndexOf(prefix);
13954            if (sidx != -1) {
13955                subStr = subStr.substring(sidx + prefix.length());
13956                if (subStr != null) {
13957                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13958                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13959                    }
13960                    try {
13961                        idx = Integer.parseInt(subStr);
13962                        if (idx <= 1) {
13963                            idx++;
13964                        } else {
13965                            idx--;
13966                        }
13967                    } catch(NumberFormatException e) {
13968                    }
13969                }
13970            }
13971        }
13972        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13973        return prefix + idxStr;
13974    }
13975
13976    private File getNextCodePath(File targetDir, String packageName) {
13977        int suffix = 1;
13978        File result;
13979        do {
13980            result = new File(targetDir, packageName + "-" + suffix);
13981            suffix++;
13982        } while (result.exists());
13983        return result;
13984    }
13985
13986    // Utility method that returns the relative package path with respect
13987    // to the installation directory. Like say for /data/data/com.test-1.apk
13988    // string com.test-1 is returned.
13989    static String deriveCodePathName(String codePath) {
13990        if (codePath == null) {
13991            return null;
13992        }
13993        final File codeFile = new File(codePath);
13994        final String name = codeFile.getName();
13995        if (codeFile.isDirectory()) {
13996            return name;
13997        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13998            final int lastDot = name.lastIndexOf('.');
13999            return name.substring(0, lastDot);
14000        } else {
14001            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14002            return null;
14003        }
14004    }
14005
14006    static class PackageInstalledInfo {
14007        String name;
14008        int uid;
14009        // The set of users that originally had this package installed.
14010        int[] origUsers;
14011        // The set of users that now have this package installed.
14012        int[] newUsers;
14013        PackageParser.Package pkg;
14014        int returnCode;
14015        String returnMsg;
14016        PackageRemovedInfo removedInfo;
14017        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14018
14019        public void setError(int code, String msg) {
14020            setReturnCode(code);
14021            setReturnMessage(msg);
14022            Slog.w(TAG, msg);
14023        }
14024
14025        public void setError(String msg, PackageParserException e) {
14026            setReturnCode(e.error);
14027            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14028            Slog.w(TAG, msg, e);
14029        }
14030
14031        public void setError(String msg, PackageManagerException e) {
14032            returnCode = e.error;
14033            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14034            Slog.w(TAG, msg, e);
14035        }
14036
14037        public void setReturnCode(int returnCode) {
14038            this.returnCode = returnCode;
14039            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14040            for (int i = 0; i < childCount; i++) {
14041                addedChildPackages.valueAt(i).returnCode = returnCode;
14042            }
14043        }
14044
14045        private void setReturnMessage(String returnMsg) {
14046            this.returnMsg = returnMsg;
14047            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14048            for (int i = 0; i < childCount; i++) {
14049                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14050            }
14051        }
14052
14053        // In some error cases we want to convey more info back to the observer
14054        String origPackage;
14055        String origPermission;
14056    }
14057
14058    /*
14059     * Install a non-existing package.
14060     */
14061    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14062            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14063            PackageInstalledInfo res) {
14064        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14065
14066        // Remember this for later, in case we need to rollback this install
14067        String pkgName = pkg.packageName;
14068
14069        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14070
14071        synchronized(mPackages) {
14072            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14073                // A package with the same name is already installed, though
14074                // it has been renamed to an older name.  The package we
14075                // are trying to install should be installed as an update to
14076                // the existing one, but that has not been requested, so bail.
14077                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14078                        + " without first uninstalling package running as "
14079                        + mSettings.mRenamedPackages.get(pkgName));
14080                return;
14081            }
14082            if (mPackages.containsKey(pkgName)) {
14083                // Don't allow installation over an existing package with the same name.
14084                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14085                        + " without first uninstalling.");
14086                return;
14087            }
14088        }
14089
14090        try {
14091            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14092                    System.currentTimeMillis(), user);
14093
14094            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14095
14096            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14097                prepareAppDataAfterInstallLIF(newPackage);
14098
14099            } else {
14100                // Remove package from internal structures, but keep around any
14101                // data that might have already existed
14102                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14103                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14104            }
14105        } catch (PackageManagerException e) {
14106            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14107        }
14108
14109        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14110    }
14111
14112    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14113        // Can't rotate keys during boot or if sharedUser.
14114        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14115                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14116            return false;
14117        }
14118        // app is using upgradeKeySets; make sure all are valid
14119        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14120        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14121        for (int i = 0; i < upgradeKeySets.length; i++) {
14122            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14123                Slog.wtf(TAG, "Package "
14124                         + (oldPs.name != null ? oldPs.name : "<null>")
14125                         + " contains upgrade-key-set reference to unknown key-set: "
14126                         + upgradeKeySets[i]
14127                         + " reverting to signatures check.");
14128                return false;
14129            }
14130        }
14131        return true;
14132    }
14133
14134    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14135        // Upgrade keysets are being used.  Determine if new package has a superset of the
14136        // required keys.
14137        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14138        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14139        for (int i = 0; i < upgradeKeySets.length; i++) {
14140            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14141            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14142                return true;
14143            }
14144        }
14145        return false;
14146    }
14147
14148    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14149        try (DigestInputStream digestStream =
14150                new DigestInputStream(new FileInputStream(file), digest)) {
14151            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14152        }
14153    }
14154
14155    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14156            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14157        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14158
14159        final PackageParser.Package oldPackage;
14160        final String pkgName = pkg.packageName;
14161        final int[] allUsers;
14162        final int[] installedUsers;
14163
14164        synchronized(mPackages) {
14165            oldPackage = mPackages.get(pkgName);
14166            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14167
14168            // don't allow upgrade to target a release SDK from a pre-release SDK
14169            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14170                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14171            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14172                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14173            if (oldTargetsPreRelease
14174                    && !newTargetsPreRelease
14175                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14176                Slog.w(TAG, "Can't install package targeting released sdk");
14177                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14178                return;
14179            }
14180
14181            // don't allow an upgrade from full to ephemeral
14182            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14183            if (isEphemeral && !oldIsEphemeral) {
14184                // can't downgrade from full to ephemeral
14185                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14186                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14187                return;
14188            }
14189
14190            // verify signatures are valid
14191            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14192            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14193                if (!checkUpgradeKeySetLP(ps, pkg)) {
14194                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14195                            "New package not signed by keys specified by upgrade-keysets: "
14196                                    + pkgName);
14197                    return;
14198                }
14199            } else {
14200                // default to original signature matching
14201                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14202                        != PackageManager.SIGNATURE_MATCH) {
14203                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14204                            "New package has a different signature: " + pkgName);
14205                    return;
14206                }
14207            }
14208
14209            // don't allow a system upgrade unless the upgrade hash matches
14210            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14211                byte[] digestBytes = null;
14212                try {
14213                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14214                    updateDigest(digest, new File(pkg.baseCodePath));
14215                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14216                        for (String path : pkg.splitCodePaths) {
14217                            updateDigest(digest, new File(path));
14218                        }
14219                    }
14220                    digestBytes = digest.digest();
14221                } catch (NoSuchAlgorithmException | IOException e) {
14222                    res.setError(INSTALL_FAILED_INVALID_APK,
14223                            "Could not compute hash: " + pkgName);
14224                    return;
14225                }
14226                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14227                    res.setError(INSTALL_FAILED_INVALID_APK,
14228                            "New package fails restrict-update check: " + pkgName);
14229                    return;
14230                }
14231                // retain upgrade restriction
14232                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14233            }
14234
14235            // Check for shared user id changes
14236            String invalidPackageName =
14237                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14238            if (invalidPackageName != null) {
14239                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14240                        "Package " + invalidPackageName + " tried to change user "
14241                                + oldPackage.mSharedUserId);
14242                return;
14243            }
14244
14245            // In case of rollback, remember per-user/profile install state
14246            allUsers = sUserManager.getUserIds();
14247            installedUsers = ps.queryInstalledUsers(allUsers, true);
14248        }
14249
14250        // Update what is removed
14251        res.removedInfo = new PackageRemovedInfo();
14252        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14253        res.removedInfo.removedPackage = oldPackage.packageName;
14254        res.removedInfo.isUpdate = true;
14255        res.removedInfo.origUsers = installedUsers;
14256        final int childCount = (oldPackage.childPackages != null)
14257                ? oldPackage.childPackages.size() : 0;
14258        for (int i = 0; i < childCount; i++) {
14259            boolean childPackageUpdated = false;
14260            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14261            if (res.addedChildPackages != null) {
14262                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14263                if (childRes != null) {
14264                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14265                    childRes.removedInfo.removedPackage = childPkg.packageName;
14266                    childRes.removedInfo.isUpdate = true;
14267                    childPackageUpdated = true;
14268                }
14269            }
14270            if (!childPackageUpdated) {
14271                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14272                childRemovedRes.removedPackage = childPkg.packageName;
14273                childRemovedRes.isUpdate = false;
14274                childRemovedRes.dataRemoved = true;
14275                synchronized (mPackages) {
14276                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14277                    if (childPs != null) {
14278                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14279                    }
14280                }
14281                if (res.removedInfo.removedChildPackages == null) {
14282                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14283                }
14284                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14285            }
14286        }
14287
14288        boolean sysPkg = (isSystemApp(oldPackage));
14289        if (sysPkg) {
14290            // Set the system/privileged flags as needed
14291            final boolean privileged =
14292                    (oldPackage.applicationInfo.privateFlags
14293                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14294            final int systemPolicyFlags = policyFlags
14295                    | PackageParser.PARSE_IS_SYSTEM
14296                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14297
14298            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14299                    user, allUsers, installerPackageName, res);
14300        } else {
14301            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14302                    user, allUsers, installerPackageName, res);
14303        }
14304    }
14305
14306    public List<String> getPreviousCodePaths(String packageName) {
14307        final PackageSetting ps = mSettings.mPackages.get(packageName);
14308        final List<String> result = new ArrayList<String>();
14309        if (ps != null && ps.oldCodePaths != null) {
14310            result.addAll(ps.oldCodePaths);
14311        }
14312        return result;
14313    }
14314
14315    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14316            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14317            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14318        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14319                + deletedPackage);
14320
14321        String pkgName = deletedPackage.packageName;
14322        boolean deletedPkg = true;
14323        boolean addedPkg = false;
14324        boolean updatedSettings = false;
14325        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14326        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14327                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14328
14329        final long origUpdateTime = (pkg.mExtras != null)
14330                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14331
14332        // First delete the existing package while retaining the data directory
14333        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14334                res.removedInfo, true, pkg)) {
14335            // If the existing package wasn't successfully deleted
14336            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14337            deletedPkg = false;
14338        } else {
14339            // Successfully deleted the old package; proceed with replace.
14340
14341            // If deleted package lived in a container, give users a chance to
14342            // relinquish resources before killing.
14343            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14344                if (DEBUG_INSTALL) {
14345                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14346                }
14347                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14348                final ArrayList<String> pkgList = new ArrayList<String>(1);
14349                pkgList.add(deletedPackage.applicationInfo.packageName);
14350                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14351            }
14352
14353            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14354                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14355            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14356
14357            try {
14358                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14359                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14360                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14361
14362                // Update the in-memory copy of the previous code paths.
14363                PackageSetting ps = mSettings.mPackages.get(pkgName);
14364                if (!killApp) {
14365                    if (ps.oldCodePaths == null) {
14366                        ps.oldCodePaths = new ArraySet<>();
14367                    }
14368                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14369                    if (deletedPackage.splitCodePaths != null) {
14370                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14371                    }
14372                } else {
14373                    ps.oldCodePaths = null;
14374                }
14375                if (ps.childPackageNames != null) {
14376                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14377                        final String childPkgName = ps.childPackageNames.get(i);
14378                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14379                        childPs.oldCodePaths = ps.oldCodePaths;
14380                    }
14381                }
14382                prepareAppDataAfterInstallLIF(newPackage);
14383                addedPkg = true;
14384            } catch (PackageManagerException e) {
14385                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14386            }
14387        }
14388
14389        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14390            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14391
14392            // Revert all internal state mutations and added folders for the failed install
14393            if (addedPkg) {
14394                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14395                        res.removedInfo, true, null);
14396            }
14397
14398            // Restore the old package
14399            if (deletedPkg) {
14400                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14401                File restoreFile = new File(deletedPackage.codePath);
14402                // Parse old package
14403                boolean oldExternal = isExternal(deletedPackage);
14404                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14405                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14406                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14407                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14408                try {
14409                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14410                            null);
14411                } catch (PackageManagerException e) {
14412                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14413                            + e.getMessage());
14414                    return;
14415                }
14416
14417                synchronized (mPackages) {
14418                    // Ensure the installer package name up to date
14419                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14420
14421                    // Update permissions for restored package
14422                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14423
14424                    mSettings.writeLPr();
14425                }
14426
14427                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14428            }
14429        } else {
14430            synchronized (mPackages) {
14431                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14432                if (ps != null) {
14433                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14434                    if (res.removedInfo.removedChildPackages != null) {
14435                        final int childCount = res.removedInfo.removedChildPackages.size();
14436                        // Iterate in reverse as we may modify the collection
14437                        for (int i = childCount - 1; i >= 0; i--) {
14438                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14439                            if (res.addedChildPackages.containsKey(childPackageName)) {
14440                                res.removedInfo.removedChildPackages.removeAt(i);
14441                            } else {
14442                                PackageRemovedInfo childInfo = res.removedInfo
14443                                        .removedChildPackages.valueAt(i);
14444                                childInfo.removedForAllUsers = mPackages.get(
14445                                        childInfo.removedPackage) == null;
14446                            }
14447                        }
14448                    }
14449                }
14450            }
14451        }
14452    }
14453
14454    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14455            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14456            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14457        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14458                + ", old=" + deletedPackage);
14459
14460        final boolean disabledSystem;
14461
14462        // Remove existing system package
14463        removePackageLI(deletedPackage, true);
14464
14465        synchronized (mPackages) {
14466            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14467        }
14468        if (!disabledSystem) {
14469            // We didn't need to disable the .apk as a current system package,
14470            // which means we are replacing another update that is already
14471            // installed.  We need to make sure to delete the older one's .apk.
14472            res.removedInfo.args = createInstallArgsForExisting(0,
14473                    deletedPackage.applicationInfo.getCodePath(),
14474                    deletedPackage.applicationInfo.getResourcePath(),
14475                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14476        } else {
14477            res.removedInfo.args = null;
14478        }
14479
14480        // Successfully disabled the old package. Now proceed with re-installation
14481        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14482                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14483        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14484
14485        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14486        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14487                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14488
14489        PackageParser.Package newPackage = null;
14490        try {
14491            // Add the package to the internal data structures
14492            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14493
14494            // Set the update and install times
14495            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14496            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14497                    System.currentTimeMillis());
14498
14499            // Update the package dynamic state if succeeded
14500            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14501                // Now that the install succeeded make sure we remove data
14502                // directories for any child package the update removed.
14503                final int deletedChildCount = (deletedPackage.childPackages != null)
14504                        ? deletedPackage.childPackages.size() : 0;
14505                final int newChildCount = (newPackage.childPackages != null)
14506                        ? newPackage.childPackages.size() : 0;
14507                for (int i = 0; i < deletedChildCount; i++) {
14508                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14509                    boolean childPackageDeleted = true;
14510                    for (int j = 0; j < newChildCount; j++) {
14511                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14512                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14513                            childPackageDeleted = false;
14514                            break;
14515                        }
14516                    }
14517                    if (childPackageDeleted) {
14518                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14519                                deletedChildPkg.packageName);
14520                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14521                            PackageRemovedInfo removedChildRes = res.removedInfo
14522                                    .removedChildPackages.get(deletedChildPkg.packageName);
14523                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14524                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14525                        }
14526                    }
14527                }
14528
14529                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14530                prepareAppDataAfterInstallLIF(newPackage);
14531            }
14532        } catch (PackageManagerException e) {
14533            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14534            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14535        }
14536
14537        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14538            // Re installation failed. Restore old information
14539            // Remove new pkg information
14540            if (newPackage != null) {
14541                removeInstalledPackageLI(newPackage, true);
14542            }
14543            // Add back the old system package
14544            try {
14545                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14546            } catch (PackageManagerException e) {
14547                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14548            }
14549
14550            synchronized (mPackages) {
14551                if (disabledSystem) {
14552                    enableSystemPackageLPw(deletedPackage);
14553                }
14554
14555                // Ensure the installer package name up to date
14556                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14557
14558                // Update permissions for restored package
14559                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14560
14561                mSettings.writeLPr();
14562            }
14563
14564            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14565                    + " after failed upgrade");
14566        }
14567    }
14568
14569    /**
14570     * Checks whether the parent or any of the child packages have a change shared
14571     * user. For a package to be a valid update the shred users of the parent and
14572     * the children should match. We may later support changing child shared users.
14573     * @param oldPkg The updated package.
14574     * @param newPkg The update package.
14575     * @return The shared user that change between the versions.
14576     */
14577    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14578            PackageParser.Package newPkg) {
14579        // Check parent shared user
14580        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14581            return newPkg.packageName;
14582        }
14583        // Check child shared users
14584        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14585        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14586        for (int i = 0; i < newChildCount; i++) {
14587            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14588            // If this child was present, did it have the same shared user?
14589            for (int j = 0; j < oldChildCount; j++) {
14590                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14591                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14592                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14593                    return newChildPkg.packageName;
14594                }
14595            }
14596        }
14597        return null;
14598    }
14599
14600    private void removeNativeBinariesLI(PackageSetting ps) {
14601        // Remove the lib path for the parent package
14602        if (ps != null) {
14603            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14604            // Remove the lib path for the child packages
14605            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14606            for (int i = 0; i < childCount; i++) {
14607                PackageSetting childPs = null;
14608                synchronized (mPackages) {
14609                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14610                }
14611                if (childPs != null) {
14612                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14613                            .legacyNativeLibraryPathString);
14614                }
14615            }
14616        }
14617    }
14618
14619    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14620        // Enable the parent package
14621        mSettings.enableSystemPackageLPw(pkg.packageName);
14622        // Enable the child packages
14623        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14624        for (int i = 0; i < childCount; i++) {
14625            PackageParser.Package childPkg = pkg.childPackages.get(i);
14626            mSettings.enableSystemPackageLPw(childPkg.packageName);
14627        }
14628    }
14629
14630    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14631            PackageParser.Package newPkg) {
14632        // Disable the parent package (parent always replaced)
14633        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14634        // Disable the child packages
14635        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14636        for (int i = 0; i < childCount; i++) {
14637            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14638            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14639            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14640        }
14641        return disabled;
14642    }
14643
14644    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14645            String installerPackageName) {
14646        // Enable the parent package
14647        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14648        // Enable the child packages
14649        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14650        for (int i = 0; i < childCount; i++) {
14651            PackageParser.Package childPkg = pkg.childPackages.get(i);
14652            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14653        }
14654    }
14655
14656    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14657        // Collect all used permissions in the UID
14658        ArraySet<String> usedPermissions = new ArraySet<>();
14659        final int packageCount = su.packages.size();
14660        for (int i = 0; i < packageCount; i++) {
14661            PackageSetting ps = su.packages.valueAt(i);
14662            if (ps.pkg == null) {
14663                continue;
14664            }
14665            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14666            for (int j = 0; j < requestedPermCount; j++) {
14667                String permission = ps.pkg.requestedPermissions.get(j);
14668                BasePermission bp = mSettings.mPermissions.get(permission);
14669                if (bp != null) {
14670                    usedPermissions.add(permission);
14671                }
14672            }
14673        }
14674
14675        PermissionsState permissionsState = su.getPermissionsState();
14676        // Prune install permissions
14677        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14678        final int installPermCount = installPermStates.size();
14679        for (int i = installPermCount - 1; i >= 0;  i--) {
14680            PermissionState permissionState = installPermStates.get(i);
14681            if (!usedPermissions.contains(permissionState.getName())) {
14682                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14683                if (bp != null) {
14684                    permissionsState.revokeInstallPermission(bp);
14685                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14686                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14687                }
14688            }
14689        }
14690
14691        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14692
14693        // Prune runtime permissions
14694        for (int userId : allUserIds) {
14695            List<PermissionState> runtimePermStates = permissionsState
14696                    .getRuntimePermissionStates(userId);
14697            final int runtimePermCount = runtimePermStates.size();
14698            for (int i = runtimePermCount - 1; i >= 0; i--) {
14699                PermissionState permissionState = runtimePermStates.get(i);
14700                if (!usedPermissions.contains(permissionState.getName())) {
14701                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14702                    if (bp != null) {
14703                        permissionsState.revokeRuntimePermission(bp, userId);
14704                        permissionsState.updatePermissionFlags(bp, userId,
14705                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14706                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14707                                runtimePermissionChangedUserIds, userId);
14708                    }
14709                }
14710            }
14711        }
14712
14713        return runtimePermissionChangedUserIds;
14714    }
14715
14716    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14717            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14718        // Update the parent package setting
14719        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14720                res, user);
14721        // Update the child packages setting
14722        final int childCount = (newPackage.childPackages != null)
14723                ? newPackage.childPackages.size() : 0;
14724        for (int i = 0; i < childCount; i++) {
14725            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14726            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14727            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14728                    childRes.origUsers, childRes, user);
14729        }
14730    }
14731
14732    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14733            String installerPackageName, int[] allUsers, int[] installedForUsers,
14734            PackageInstalledInfo res, UserHandle user) {
14735        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14736
14737        String pkgName = newPackage.packageName;
14738        synchronized (mPackages) {
14739            //write settings. the installStatus will be incomplete at this stage.
14740            //note that the new package setting would have already been
14741            //added to mPackages. It hasn't been persisted yet.
14742            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14743            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14744            mSettings.writeLPr();
14745            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14746        }
14747
14748        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14749        synchronized (mPackages) {
14750            updatePermissionsLPw(newPackage.packageName, newPackage,
14751                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14752                            ? UPDATE_PERMISSIONS_ALL : 0));
14753            // For system-bundled packages, we assume that installing an upgraded version
14754            // of the package implies that the user actually wants to run that new code,
14755            // so we enable the package.
14756            PackageSetting ps = mSettings.mPackages.get(pkgName);
14757            final int userId = user.getIdentifier();
14758            if (ps != null) {
14759                if (isSystemApp(newPackage)) {
14760                    if (DEBUG_INSTALL) {
14761                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14762                    }
14763                    // Enable system package for requested users
14764                    if (res.origUsers != null) {
14765                        for (int origUserId : res.origUsers) {
14766                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14767                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14768                                        origUserId, installerPackageName);
14769                            }
14770                        }
14771                    }
14772                    // Also convey the prior install/uninstall state
14773                    if (allUsers != null && installedForUsers != null) {
14774                        for (int currentUserId : allUsers) {
14775                            final boolean installed = ArrayUtils.contains(
14776                                    installedForUsers, currentUserId);
14777                            if (DEBUG_INSTALL) {
14778                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14779                            }
14780                            ps.setInstalled(installed, currentUserId);
14781                        }
14782                        // these install state changes will be persisted in the
14783                        // upcoming call to mSettings.writeLPr().
14784                    }
14785                }
14786                // It's implied that when a user requests installation, they want the app to be
14787                // installed and enabled.
14788                if (userId != UserHandle.USER_ALL) {
14789                    ps.setInstalled(true, userId);
14790                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14791                }
14792            }
14793            res.name = pkgName;
14794            res.uid = newPackage.applicationInfo.uid;
14795            res.pkg = newPackage;
14796            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14797            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14798            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14799            //to update install status
14800            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14801            mSettings.writeLPr();
14802            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14803        }
14804
14805        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14806    }
14807
14808    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14809        try {
14810            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14811            installPackageLI(args, res);
14812        } finally {
14813            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14814        }
14815    }
14816
14817    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14818        final int installFlags = args.installFlags;
14819        final String installerPackageName = args.installerPackageName;
14820        final String volumeUuid = args.volumeUuid;
14821        final File tmpPackageFile = new File(args.getCodePath());
14822        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14823        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14824                || (args.volumeUuid != null));
14825        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14826        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14827        boolean replace = false;
14828        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14829        if (args.move != null) {
14830            // moving a complete application; perform an initial scan on the new install location
14831            scanFlags |= SCAN_INITIAL;
14832        }
14833        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14834            scanFlags |= SCAN_DONT_KILL_APP;
14835        }
14836
14837        // Result object to be returned
14838        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14839
14840        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14841
14842        // Sanity check
14843        if (ephemeral && (forwardLocked || onExternal)) {
14844            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14845                    + " external=" + onExternal);
14846            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14847            return;
14848        }
14849
14850        // Retrieve PackageSettings and parse package
14851        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14852                | PackageParser.PARSE_ENFORCE_CODE
14853                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14854                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14855                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14856                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14857        PackageParser pp = new PackageParser();
14858        pp.setSeparateProcesses(mSeparateProcesses);
14859        pp.setDisplayMetrics(mMetrics);
14860
14861        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14862        final PackageParser.Package pkg;
14863        try {
14864            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14865        } catch (PackageParserException e) {
14866            res.setError("Failed parse during installPackageLI", e);
14867            return;
14868        } finally {
14869            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14870        }
14871
14872        // If we are installing a clustered package add results for the children
14873        if (pkg.childPackages != null) {
14874            synchronized (mPackages) {
14875                final int childCount = pkg.childPackages.size();
14876                for (int i = 0; i < childCount; i++) {
14877                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14878                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14879                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14880                    childRes.pkg = childPkg;
14881                    childRes.name = childPkg.packageName;
14882                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14883                    if (childPs != null) {
14884                        childRes.origUsers = childPs.queryInstalledUsers(
14885                                sUserManager.getUserIds(), true);
14886                    }
14887                    if ((mPackages.containsKey(childPkg.packageName))) {
14888                        childRes.removedInfo = new PackageRemovedInfo();
14889                        childRes.removedInfo.removedPackage = childPkg.packageName;
14890                    }
14891                    if (res.addedChildPackages == null) {
14892                        res.addedChildPackages = new ArrayMap<>();
14893                    }
14894                    res.addedChildPackages.put(childPkg.packageName, childRes);
14895                }
14896            }
14897        }
14898
14899        // If package doesn't declare API override, mark that we have an install
14900        // time CPU ABI override.
14901        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14902            pkg.cpuAbiOverride = args.abiOverride;
14903        }
14904
14905        String pkgName = res.name = pkg.packageName;
14906        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14907            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14908                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14909                return;
14910            }
14911        }
14912
14913        try {
14914            // either use what we've been given or parse directly from the APK
14915            if (args.certificates != null) {
14916                try {
14917                    PackageParser.populateCertificates(pkg, args.certificates);
14918                } catch (PackageParserException e) {
14919                    // there was something wrong with the certificates we were given;
14920                    // try to pull them from the APK
14921                    PackageParser.collectCertificates(pkg, parseFlags);
14922                }
14923            } else {
14924                PackageParser.collectCertificates(pkg, parseFlags);
14925            }
14926        } catch (PackageParserException e) {
14927            res.setError("Failed collect during installPackageLI", e);
14928            return;
14929        }
14930
14931        // Get rid of all references to package scan path via parser.
14932        pp = null;
14933        String oldCodePath = null;
14934        boolean systemApp = false;
14935        synchronized (mPackages) {
14936            // Check if installing already existing package
14937            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14938                String oldName = mSettings.mRenamedPackages.get(pkgName);
14939                if (pkg.mOriginalPackages != null
14940                        && pkg.mOriginalPackages.contains(oldName)
14941                        && mPackages.containsKey(oldName)) {
14942                    // This package is derived from an original package,
14943                    // and this device has been updating from that original
14944                    // name.  We must continue using the original name, so
14945                    // rename the new package here.
14946                    pkg.setPackageName(oldName);
14947                    pkgName = pkg.packageName;
14948                    replace = true;
14949                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14950                            + oldName + " pkgName=" + pkgName);
14951                } else if (mPackages.containsKey(pkgName)) {
14952                    // This package, under its official name, already exists
14953                    // on the device; we should replace it.
14954                    replace = true;
14955                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14956                }
14957
14958                // Child packages are installed through the parent package
14959                if (pkg.parentPackage != null) {
14960                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14961                            "Package " + pkg.packageName + " is child of package "
14962                                    + pkg.parentPackage.parentPackage + ". Child packages "
14963                                    + "can be updated only through the parent package.");
14964                    return;
14965                }
14966
14967                if (replace) {
14968                    // Prevent apps opting out from runtime permissions
14969                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14970                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14971                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14972                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14973                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14974                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14975                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14976                                        + " doesn't support runtime permissions but the old"
14977                                        + " target SDK " + oldTargetSdk + " does.");
14978                        return;
14979                    }
14980
14981                    // Prevent installing of child packages
14982                    if (oldPackage.parentPackage != null) {
14983                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14984                                "Package " + pkg.packageName + " is child of package "
14985                                        + oldPackage.parentPackage + ". Child packages "
14986                                        + "can be updated only through the parent package.");
14987                        return;
14988                    }
14989                }
14990            }
14991
14992            PackageSetting ps = mSettings.mPackages.get(pkgName);
14993            if (ps != null) {
14994                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14995
14996                // Quick sanity check that we're signed correctly if updating;
14997                // we'll check this again later when scanning, but we want to
14998                // bail early here before tripping over redefined permissions.
14999                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15000                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15001                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15002                                + pkg.packageName + " upgrade keys do not match the "
15003                                + "previously installed version");
15004                        return;
15005                    }
15006                } else {
15007                    try {
15008                        verifySignaturesLP(ps, pkg);
15009                    } catch (PackageManagerException e) {
15010                        res.setError(e.error, e.getMessage());
15011                        return;
15012                    }
15013                }
15014
15015                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15016                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15017                    systemApp = (ps.pkg.applicationInfo.flags &
15018                            ApplicationInfo.FLAG_SYSTEM) != 0;
15019                }
15020                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15021            }
15022
15023            // Check whether the newly-scanned package wants to define an already-defined perm
15024            int N = pkg.permissions.size();
15025            for (int i = N-1; i >= 0; i--) {
15026                PackageParser.Permission perm = pkg.permissions.get(i);
15027                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15028                if (bp != null) {
15029                    // If the defining package is signed with our cert, it's okay.  This
15030                    // also includes the "updating the same package" case, of course.
15031                    // "updating same package" could also involve key-rotation.
15032                    final boolean sigsOk;
15033                    if (bp.sourcePackage.equals(pkg.packageName)
15034                            && (bp.packageSetting instanceof PackageSetting)
15035                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15036                                    scanFlags))) {
15037                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15038                    } else {
15039                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15040                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15041                    }
15042                    if (!sigsOk) {
15043                        // If the owning package is the system itself, we log but allow
15044                        // install to proceed; we fail the install on all other permission
15045                        // redefinitions.
15046                        if (!bp.sourcePackage.equals("android")) {
15047                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15048                                    + pkg.packageName + " attempting to redeclare permission "
15049                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15050                            res.origPermission = perm.info.name;
15051                            res.origPackage = bp.sourcePackage;
15052                            return;
15053                        } else {
15054                            Slog.w(TAG, "Package " + pkg.packageName
15055                                    + " attempting to redeclare system permission "
15056                                    + perm.info.name + "; ignoring new declaration");
15057                            pkg.permissions.remove(i);
15058                        }
15059                    }
15060                }
15061            }
15062        }
15063
15064        if (systemApp) {
15065            if (onExternal) {
15066                // Abort update; system app can't be replaced with app on sdcard
15067                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15068                        "Cannot install updates to system apps on sdcard");
15069                return;
15070            } else if (ephemeral) {
15071                // Abort update; system app can't be replaced with an ephemeral app
15072                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15073                        "Cannot update a system app with an ephemeral app");
15074                return;
15075            }
15076        }
15077
15078        if (args.move != null) {
15079            // We did an in-place move, so dex is ready to roll
15080            scanFlags |= SCAN_NO_DEX;
15081            scanFlags |= SCAN_MOVE;
15082
15083            synchronized (mPackages) {
15084                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15085                if (ps == null) {
15086                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15087                            "Missing settings for moved package " + pkgName);
15088                }
15089
15090                // We moved the entire application as-is, so bring over the
15091                // previously derived ABI information.
15092                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15093                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15094            }
15095
15096        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15097            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15098            scanFlags |= SCAN_NO_DEX;
15099
15100            try {
15101                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15102                    args.abiOverride : pkg.cpuAbiOverride);
15103                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15104                        true /* extract libs */);
15105            } catch (PackageManagerException pme) {
15106                Slog.e(TAG, "Error deriving application ABI", pme);
15107                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15108                return;
15109            }
15110
15111            // Shared libraries for the package need to be updated.
15112            synchronized (mPackages) {
15113                try {
15114                    updateSharedLibrariesLPw(pkg, null);
15115                } catch (PackageManagerException e) {
15116                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15117                }
15118            }
15119            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15120            // Do not run PackageDexOptimizer through the local performDexOpt
15121            // method because `pkg` may not be in `mPackages` yet.
15122            //
15123            // Also, don't fail application installs if the dexopt step fails.
15124            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15125                    null /* instructionSets */, false /* checkProfiles */,
15126                    getCompilerFilterForReason(REASON_INSTALL),
15127                    getOrCreateCompilerPackageStats(pkg));
15128            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15129
15130            // Notify BackgroundDexOptService that the package has been changed.
15131            // If this is an update of a package which used to fail to compile,
15132            // BDOS will remove it from its blacklist.
15133            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15134        }
15135
15136        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15137            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15138            return;
15139        }
15140
15141        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15142
15143        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15144                "installPackageLI")) {
15145            if (replace) {
15146                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15147                        installerPackageName, res);
15148            } else {
15149                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15150                        args.user, installerPackageName, volumeUuid, res);
15151            }
15152        }
15153        synchronized (mPackages) {
15154            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15155            if (ps != null) {
15156                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15157            }
15158
15159            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15160            for (int i = 0; i < childCount; i++) {
15161                PackageParser.Package childPkg = pkg.childPackages.get(i);
15162                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15163                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15164                if (childPs != null) {
15165                    childRes.newUsers = childPs.queryInstalledUsers(
15166                            sUserManager.getUserIds(), true);
15167                }
15168            }
15169        }
15170    }
15171
15172    private void startIntentFilterVerifications(int userId, boolean replacing,
15173            PackageParser.Package pkg) {
15174        if (mIntentFilterVerifierComponent == null) {
15175            Slog.w(TAG, "No IntentFilter verification will not be done as "
15176                    + "there is no IntentFilterVerifier available!");
15177            return;
15178        }
15179
15180        final int verifierUid = getPackageUid(
15181                mIntentFilterVerifierComponent.getPackageName(),
15182                MATCH_DEBUG_TRIAGED_MISSING,
15183                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15184
15185        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15186        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15187        mHandler.sendMessage(msg);
15188
15189        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15190        for (int i = 0; i < childCount; i++) {
15191            PackageParser.Package childPkg = pkg.childPackages.get(i);
15192            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15193            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15194            mHandler.sendMessage(msg);
15195        }
15196    }
15197
15198    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15199            PackageParser.Package pkg) {
15200        int size = pkg.activities.size();
15201        if (size == 0) {
15202            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15203                    "No activity, so no need to verify any IntentFilter!");
15204            return;
15205        }
15206
15207        final boolean hasDomainURLs = hasDomainURLs(pkg);
15208        if (!hasDomainURLs) {
15209            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15210                    "No domain URLs, so no need to verify any IntentFilter!");
15211            return;
15212        }
15213
15214        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15215                + " if any IntentFilter from the " + size
15216                + " Activities needs verification ...");
15217
15218        int count = 0;
15219        final String packageName = pkg.packageName;
15220
15221        synchronized (mPackages) {
15222            // If this is a new install and we see that we've already run verification for this
15223            // package, we have nothing to do: it means the state was restored from backup.
15224            if (!replacing) {
15225                IntentFilterVerificationInfo ivi =
15226                        mSettings.getIntentFilterVerificationLPr(packageName);
15227                if (ivi != null) {
15228                    if (DEBUG_DOMAIN_VERIFICATION) {
15229                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15230                                + ivi.getStatusString());
15231                    }
15232                    return;
15233                }
15234            }
15235
15236            // If any filters need to be verified, then all need to be.
15237            boolean needToVerify = false;
15238            for (PackageParser.Activity a : pkg.activities) {
15239                for (ActivityIntentInfo filter : a.intents) {
15240                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15241                        if (DEBUG_DOMAIN_VERIFICATION) {
15242                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15243                        }
15244                        needToVerify = true;
15245                        break;
15246                    }
15247                }
15248            }
15249
15250            if (needToVerify) {
15251                final int verificationId = mIntentFilterVerificationToken++;
15252                for (PackageParser.Activity a : pkg.activities) {
15253                    for (ActivityIntentInfo filter : a.intents) {
15254                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15255                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15256                                    "Verification needed for IntentFilter:" + filter.toString());
15257                            mIntentFilterVerifier.addOneIntentFilterVerification(
15258                                    verifierUid, userId, verificationId, filter, packageName);
15259                            count++;
15260                        }
15261                    }
15262                }
15263            }
15264        }
15265
15266        if (count > 0) {
15267            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15268                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15269                    +  " for userId:" + userId);
15270            mIntentFilterVerifier.startVerifications(userId);
15271        } else {
15272            if (DEBUG_DOMAIN_VERIFICATION) {
15273                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15274            }
15275        }
15276    }
15277
15278    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15279        final ComponentName cn  = filter.activity.getComponentName();
15280        final String packageName = cn.getPackageName();
15281
15282        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15283                packageName);
15284        if (ivi == null) {
15285            return true;
15286        }
15287        int status = ivi.getStatus();
15288        switch (status) {
15289            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15290            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15291                return true;
15292
15293            default:
15294                // Nothing to do
15295                return false;
15296        }
15297    }
15298
15299    private static boolean isMultiArch(ApplicationInfo info) {
15300        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15301    }
15302
15303    private static boolean isExternal(PackageParser.Package pkg) {
15304        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15305    }
15306
15307    private static boolean isExternal(PackageSetting ps) {
15308        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15309    }
15310
15311    private static boolean isEphemeral(PackageParser.Package pkg) {
15312        return pkg.applicationInfo.isEphemeralApp();
15313    }
15314
15315    private static boolean isEphemeral(PackageSetting ps) {
15316        return ps.pkg != null && isEphemeral(ps.pkg);
15317    }
15318
15319    private static boolean isSystemApp(PackageParser.Package pkg) {
15320        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15321    }
15322
15323    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15324        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15325    }
15326
15327    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15328        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15329    }
15330
15331    private static boolean isSystemApp(PackageSetting ps) {
15332        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15333    }
15334
15335    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15336        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15337    }
15338
15339    private int packageFlagsToInstallFlags(PackageSetting ps) {
15340        int installFlags = 0;
15341        if (isEphemeral(ps)) {
15342            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15343        }
15344        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15345            // This existing package was an external ASEC install when we have
15346            // the external flag without a UUID
15347            installFlags |= PackageManager.INSTALL_EXTERNAL;
15348        }
15349        if (ps.isForwardLocked()) {
15350            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15351        }
15352        return installFlags;
15353    }
15354
15355    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15356        if (isExternal(pkg)) {
15357            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15358                return StorageManager.UUID_PRIMARY_PHYSICAL;
15359            } else {
15360                return pkg.volumeUuid;
15361            }
15362        } else {
15363            return StorageManager.UUID_PRIVATE_INTERNAL;
15364        }
15365    }
15366
15367    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15368        if (isExternal(pkg)) {
15369            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15370                return mSettings.getExternalVersion();
15371            } else {
15372                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15373            }
15374        } else {
15375            return mSettings.getInternalVersion();
15376        }
15377    }
15378
15379    private void deleteTempPackageFiles() {
15380        final FilenameFilter filter = new FilenameFilter() {
15381            public boolean accept(File dir, String name) {
15382                return name.startsWith("vmdl") && name.endsWith(".tmp");
15383            }
15384        };
15385        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15386            file.delete();
15387        }
15388    }
15389
15390    @Override
15391    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15392            int flags) {
15393        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15394                flags);
15395    }
15396
15397    @Override
15398    public void deletePackage(final String packageName,
15399            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15400        mContext.enforceCallingOrSelfPermission(
15401                android.Manifest.permission.DELETE_PACKAGES, null);
15402        Preconditions.checkNotNull(packageName);
15403        Preconditions.checkNotNull(observer);
15404        final int uid = Binder.getCallingUid();
15405        if (!isOrphaned(packageName)
15406                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15407            try {
15408                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15409                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15410                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15411                observer.onUserActionRequired(intent);
15412            } catch (RemoteException re) {
15413            }
15414            return;
15415        }
15416        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15417        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15418        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15419            mContext.enforceCallingOrSelfPermission(
15420                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15421                    "deletePackage for user " + userId);
15422        }
15423
15424        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15425            try {
15426                observer.onPackageDeleted(packageName,
15427                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15428            } catch (RemoteException re) {
15429            }
15430            return;
15431        }
15432
15433        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15434            try {
15435                observer.onPackageDeleted(packageName,
15436                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15437            } catch (RemoteException re) {
15438            }
15439            return;
15440        }
15441
15442        if (DEBUG_REMOVE) {
15443            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15444                    + " deleteAllUsers: " + deleteAllUsers );
15445        }
15446        // Queue up an async operation since the package deletion may take a little while.
15447        mHandler.post(new Runnable() {
15448            public void run() {
15449                mHandler.removeCallbacks(this);
15450                int returnCode;
15451                if (!deleteAllUsers) {
15452                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15453                } else {
15454                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15455                    // If nobody is blocking uninstall, proceed with delete for all users
15456                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15457                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15458                    } else {
15459                        // Otherwise uninstall individually for users with blockUninstalls=false
15460                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15461                        for (int userId : users) {
15462                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15463                                returnCode = deletePackageX(packageName, userId, userFlags);
15464                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15465                                    Slog.w(TAG, "Package delete failed for user " + userId
15466                                            + ", returnCode " + returnCode);
15467                                }
15468                            }
15469                        }
15470                        // The app has only been marked uninstalled for certain users.
15471                        // We still need to report that delete was blocked
15472                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15473                    }
15474                }
15475                try {
15476                    observer.onPackageDeleted(packageName, returnCode, null);
15477                } catch (RemoteException e) {
15478                    Log.i(TAG, "Observer no longer exists.");
15479                } //end catch
15480            } //end run
15481        });
15482    }
15483
15484    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15485        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15486              || callingUid == Process.SYSTEM_UID) {
15487            return true;
15488        }
15489        final int callingUserId = UserHandle.getUserId(callingUid);
15490        // If the caller installed the pkgName, then allow it to silently uninstall.
15491        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15492            return true;
15493        }
15494
15495        // Allow package verifier to silently uninstall.
15496        if (mRequiredVerifierPackage != null &&
15497                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15498            return true;
15499        }
15500
15501        // Allow package uninstaller to silently uninstall.
15502        if (mRequiredUninstallerPackage != null &&
15503                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15504            return true;
15505        }
15506        return false;
15507    }
15508
15509    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15510        int[] result = EMPTY_INT_ARRAY;
15511        for (int userId : userIds) {
15512            if (getBlockUninstallForUser(packageName, userId)) {
15513                result = ArrayUtils.appendInt(result, userId);
15514            }
15515        }
15516        return result;
15517    }
15518
15519    @Override
15520    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15521        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15522    }
15523
15524    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15525        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15526                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15527        try {
15528            if (dpm != null) {
15529                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15530                        /* callingUserOnly =*/ false);
15531                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15532                        : deviceOwnerComponentName.getPackageName();
15533                // Does the package contains the device owner?
15534                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15535                // this check is probably not needed, since DO should be registered as a device
15536                // admin on some user too. (Original bug for this: b/17657954)
15537                if (packageName.equals(deviceOwnerPackageName)) {
15538                    return true;
15539                }
15540                // Does it contain a device admin for any user?
15541                int[] users;
15542                if (userId == UserHandle.USER_ALL) {
15543                    users = sUserManager.getUserIds();
15544                } else {
15545                    users = new int[]{userId};
15546                }
15547                for (int i = 0; i < users.length; ++i) {
15548                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15549                        return true;
15550                    }
15551                }
15552            }
15553        } catch (RemoteException e) {
15554        }
15555        return false;
15556    }
15557
15558    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15559        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15560    }
15561
15562    /**
15563     *  This method is an internal method that could be get invoked either
15564     *  to delete an installed package or to clean up a failed installation.
15565     *  After deleting an installed package, a broadcast is sent to notify any
15566     *  listeners that the package has been removed. For cleaning up a failed
15567     *  installation, the broadcast is not necessary since the package's
15568     *  installation wouldn't have sent the initial broadcast either
15569     *  The key steps in deleting a package are
15570     *  deleting the package information in internal structures like mPackages,
15571     *  deleting the packages base directories through installd
15572     *  updating mSettings to reflect current status
15573     *  persisting settings for later use
15574     *  sending a broadcast if necessary
15575     */
15576    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15577        final PackageRemovedInfo info = new PackageRemovedInfo();
15578        final boolean res;
15579
15580        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15581                ? UserHandle.USER_ALL : userId;
15582
15583        if (isPackageDeviceAdmin(packageName, removeUser)) {
15584            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15585            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15586        }
15587
15588        PackageSetting uninstalledPs = null;
15589
15590        // for the uninstall-updates case and restricted profiles, remember the per-
15591        // user handle installed state
15592        int[] allUsers;
15593        synchronized (mPackages) {
15594            uninstalledPs = mSettings.mPackages.get(packageName);
15595            if (uninstalledPs == null) {
15596                Slog.w(TAG, "Not removing non-existent package " + packageName);
15597                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15598            }
15599            allUsers = sUserManager.getUserIds();
15600            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15601        }
15602
15603        final int freezeUser;
15604        if (isUpdatedSystemApp(uninstalledPs)
15605                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15606            // We're downgrading a system app, which will apply to all users, so
15607            // freeze them all during the downgrade
15608            freezeUser = UserHandle.USER_ALL;
15609        } else {
15610            freezeUser = removeUser;
15611        }
15612
15613        synchronized (mInstallLock) {
15614            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15615            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15616                    deleteFlags, "deletePackageX")) {
15617                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15618                        deleteFlags | REMOVE_CHATTY, info, true, null);
15619            }
15620            synchronized (mPackages) {
15621                if (res) {
15622                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15623                }
15624            }
15625        }
15626
15627        if (res) {
15628            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15629            info.sendPackageRemovedBroadcasts(killApp);
15630            info.sendSystemPackageUpdatedBroadcasts();
15631            info.sendSystemPackageAppearedBroadcasts();
15632        }
15633        // Force a gc here.
15634        Runtime.getRuntime().gc();
15635        // Delete the resources here after sending the broadcast to let
15636        // other processes clean up before deleting resources.
15637        if (info.args != null) {
15638            synchronized (mInstallLock) {
15639                info.args.doPostDeleteLI(true);
15640            }
15641        }
15642
15643        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15644    }
15645
15646    class PackageRemovedInfo {
15647        String removedPackage;
15648        int uid = -1;
15649        int removedAppId = -1;
15650        int[] origUsers;
15651        int[] removedUsers = null;
15652        boolean isRemovedPackageSystemUpdate = false;
15653        boolean isUpdate;
15654        boolean dataRemoved;
15655        boolean removedForAllUsers;
15656        // Clean up resources deleted packages.
15657        InstallArgs args = null;
15658        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15659        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15660
15661        void sendPackageRemovedBroadcasts(boolean killApp) {
15662            sendPackageRemovedBroadcastInternal(killApp);
15663            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15664            for (int i = 0; i < childCount; i++) {
15665                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15666                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15667            }
15668        }
15669
15670        void sendSystemPackageUpdatedBroadcasts() {
15671            if (isRemovedPackageSystemUpdate) {
15672                sendSystemPackageUpdatedBroadcastsInternal();
15673                final int childCount = (removedChildPackages != null)
15674                        ? removedChildPackages.size() : 0;
15675                for (int i = 0; i < childCount; i++) {
15676                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15677                    if (childInfo.isRemovedPackageSystemUpdate) {
15678                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15679                    }
15680                }
15681            }
15682        }
15683
15684        void sendSystemPackageAppearedBroadcasts() {
15685            final int packageCount = (appearedChildPackages != null)
15686                    ? appearedChildPackages.size() : 0;
15687            for (int i = 0; i < packageCount; i++) {
15688                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15689                for (int userId : installedInfo.newUsers) {
15690                    sendPackageAddedForUser(installedInfo.name, true,
15691                            UserHandle.getAppId(installedInfo.uid), userId);
15692                }
15693            }
15694        }
15695
15696        private void sendSystemPackageUpdatedBroadcastsInternal() {
15697            Bundle extras = new Bundle(2);
15698            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15699            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15700            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15701                    extras, 0, null, null, null);
15702            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15703                    extras, 0, null, null, null);
15704            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15705                    null, 0, removedPackage, null, null);
15706        }
15707
15708        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15709            Bundle extras = new Bundle(2);
15710            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15711            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15712            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15713            if (isUpdate || isRemovedPackageSystemUpdate) {
15714                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15715            }
15716            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15717            if (removedPackage != null) {
15718                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15719                        extras, 0, null, null, removedUsers);
15720                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15721                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15722                            removedPackage, extras, 0, null, null, removedUsers);
15723                }
15724            }
15725            if (removedAppId >= 0) {
15726                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15727                        removedUsers);
15728            }
15729        }
15730    }
15731
15732    /*
15733     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15734     * flag is not set, the data directory is removed as well.
15735     * make sure this flag is set for partially installed apps. If not its meaningless to
15736     * delete a partially installed application.
15737     */
15738    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15739            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15740        String packageName = ps.name;
15741        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15742        // Retrieve object to delete permissions for shared user later on
15743        final PackageParser.Package deletedPkg;
15744        final PackageSetting deletedPs;
15745        // reader
15746        synchronized (mPackages) {
15747            deletedPkg = mPackages.get(packageName);
15748            deletedPs = mSettings.mPackages.get(packageName);
15749            if (outInfo != null) {
15750                outInfo.removedPackage = packageName;
15751                outInfo.removedUsers = deletedPs != null
15752                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15753                        : null;
15754            }
15755        }
15756
15757        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15758
15759        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15760            final PackageParser.Package resolvedPkg;
15761            if (deletedPkg != null) {
15762                resolvedPkg = deletedPkg;
15763            } else {
15764                // We don't have a parsed package when it lives on an ejected
15765                // adopted storage device, so fake something together
15766                resolvedPkg = new PackageParser.Package(ps.name);
15767                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15768            }
15769            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15770                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15771            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15772            if (outInfo != null) {
15773                outInfo.dataRemoved = true;
15774            }
15775            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15776        }
15777
15778        // writer
15779        synchronized (mPackages) {
15780            if (deletedPs != null) {
15781                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15782                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15783                    clearDefaultBrowserIfNeeded(packageName);
15784                    if (outInfo != null) {
15785                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15786                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15787                    }
15788                    updatePermissionsLPw(deletedPs.name, null, 0);
15789                    if (deletedPs.sharedUser != null) {
15790                        // Remove permissions associated with package. Since runtime
15791                        // permissions are per user we have to kill the removed package
15792                        // or packages running under the shared user of the removed
15793                        // package if revoking the permissions requested only by the removed
15794                        // package is successful and this causes a change in gids.
15795                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15796                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15797                                    userId);
15798                            if (userIdToKill == UserHandle.USER_ALL
15799                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15800                                // If gids changed for this user, kill all affected packages.
15801                                mHandler.post(new Runnable() {
15802                                    @Override
15803                                    public void run() {
15804                                        // This has to happen with no lock held.
15805                                        killApplication(deletedPs.name, deletedPs.appId,
15806                                                KILL_APP_REASON_GIDS_CHANGED);
15807                                    }
15808                                });
15809                                break;
15810                            }
15811                        }
15812                    }
15813                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15814                }
15815                // make sure to preserve per-user disabled state if this removal was just
15816                // a downgrade of a system app to the factory package
15817                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15818                    if (DEBUG_REMOVE) {
15819                        Slog.d(TAG, "Propagating install state across downgrade");
15820                    }
15821                    for (int userId : allUserHandles) {
15822                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15823                        if (DEBUG_REMOVE) {
15824                            Slog.d(TAG, "    user " + userId + " => " + installed);
15825                        }
15826                        ps.setInstalled(installed, userId);
15827                    }
15828                }
15829            }
15830            // can downgrade to reader
15831            if (writeSettings) {
15832                // Save settings now
15833                mSettings.writeLPr();
15834            }
15835        }
15836        if (outInfo != null) {
15837            // A user ID was deleted here. Go through all users and remove it
15838            // from KeyStore.
15839            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15840        }
15841    }
15842
15843    static boolean locationIsPrivileged(File path) {
15844        try {
15845            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15846                    .getCanonicalPath();
15847            return path.getCanonicalPath().startsWith(privilegedAppDir);
15848        } catch (IOException e) {
15849            Slog.e(TAG, "Unable to access code path " + path);
15850        }
15851        return false;
15852    }
15853
15854    /*
15855     * Tries to delete system package.
15856     */
15857    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15858            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15859            boolean writeSettings) {
15860        if (deletedPs.parentPackageName != null) {
15861            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15862            return false;
15863        }
15864
15865        final boolean applyUserRestrictions
15866                = (allUserHandles != null) && (outInfo.origUsers != null);
15867        final PackageSetting disabledPs;
15868        // Confirm if the system package has been updated
15869        // An updated system app can be deleted. This will also have to restore
15870        // the system pkg from system partition
15871        // reader
15872        synchronized (mPackages) {
15873            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15874        }
15875
15876        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15877                + " disabledPs=" + disabledPs);
15878
15879        if (disabledPs == null) {
15880            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15881            return false;
15882        } else if (DEBUG_REMOVE) {
15883            Slog.d(TAG, "Deleting system pkg from data partition");
15884        }
15885
15886        if (DEBUG_REMOVE) {
15887            if (applyUserRestrictions) {
15888                Slog.d(TAG, "Remembering install states:");
15889                for (int userId : allUserHandles) {
15890                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15891                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15892                }
15893            }
15894        }
15895
15896        // Delete the updated package
15897        outInfo.isRemovedPackageSystemUpdate = true;
15898        if (outInfo.removedChildPackages != null) {
15899            final int childCount = (deletedPs.childPackageNames != null)
15900                    ? deletedPs.childPackageNames.size() : 0;
15901            for (int i = 0; i < childCount; i++) {
15902                String childPackageName = deletedPs.childPackageNames.get(i);
15903                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15904                        .contains(childPackageName)) {
15905                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15906                            childPackageName);
15907                    if (childInfo != null) {
15908                        childInfo.isRemovedPackageSystemUpdate = true;
15909                    }
15910                }
15911            }
15912        }
15913
15914        if (disabledPs.versionCode < deletedPs.versionCode) {
15915            // Delete data for downgrades
15916            flags &= ~PackageManager.DELETE_KEEP_DATA;
15917        } else {
15918            // Preserve data by setting flag
15919            flags |= PackageManager.DELETE_KEEP_DATA;
15920        }
15921
15922        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15923                outInfo, writeSettings, disabledPs.pkg);
15924        if (!ret) {
15925            return false;
15926        }
15927
15928        // writer
15929        synchronized (mPackages) {
15930            // Reinstate the old system package
15931            enableSystemPackageLPw(disabledPs.pkg);
15932            // Remove any native libraries from the upgraded package.
15933            removeNativeBinariesLI(deletedPs);
15934        }
15935
15936        // Install the system package
15937        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15938        int parseFlags = mDefParseFlags
15939                | PackageParser.PARSE_MUST_BE_APK
15940                | PackageParser.PARSE_IS_SYSTEM
15941                | PackageParser.PARSE_IS_SYSTEM_DIR;
15942        if (locationIsPrivileged(disabledPs.codePath)) {
15943            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15944        }
15945
15946        final PackageParser.Package newPkg;
15947        try {
15948            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15949        } catch (PackageManagerException e) {
15950            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15951                    + e.getMessage());
15952            return false;
15953        }
15954        try {
15955            // update shared libraries for the newly re-installed system package
15956            updateSharedLibrariesLPw(newPkg, null);
15957        } catch (PackageManagerException e) {
15958            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
15959        }
15960
15961        prepareAppDataAfterInstallLIF(newPkg);
15962
15963        // writer
15964        synchronized (mPackages) {
15965            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15966
15967            // Propagate the permissions state as we do not want to drop on the floor
15968            // runtime permissions. The update permissions method below will take
15969            // care of removing obsolete permissions and grant install permissions.
15970            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15971            updatePermissionsLPw(newPkg.packageName, newPkg,
15972                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15973
15974            if (applyUserRestrictions) {
15975                if (DEBUG_REMOVE) {
15976                    Slog.d(TAG, "Propagating install state across reinstall");
15977                }
15978                for (int userId : allUserHandles) {
15979                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15980                    if (DEBUG_REMOVE) {
15981                        Slog.d(TAG, "    user " + userId + " => " + installed);
15982                    }
15983                    ps.setInstalled(installed, userId);
15984
15985                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15986                }
15987                // Regardless of writeSettings we need to ensure that this restriction
15988                // state propagation is persisted
15989                mSettings.writeAllUsersPackageRestrictionsLPr();
15990            }
15991            // can downgrade to reader here
15992            if (writeSettings) {
15993                mSettings.writeLPr();
15994            }
15995        }
15996        return true;
15997    }
15998
15999    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16000            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16001            PackageRemovedInfo outInfo, boolean writeSettings,
16002            PackageParser.Package replacingPackage) {
16003        synchronized (mPackages) {
16004            if (outInfo != null) {
16005                outInfo.uid = ps.appId;
16006            }
16007
16008            if (outInfo != null && outInfo.removedChildPackages != null) {
16009                final int childCount = (ps.childPackageNames != null)
16010                        ? ps.childPackageNames.size() : 0;
16011                for (int i = 0; i < childCount; i++) {
16012                    String childPackageName = ps.childPackageNames.get(i);
16013                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16014                    if (childPs == null) {
16015                        return false;
16016                    }
16017                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16018                            childPackageName);
16019                    if (childInfo != null) {
16020                        childInfo.uid = childPs.appId;
16021                    }
16022                }
16023            }
16024        }
16025
16026        // Delete package data from internal structures and also remove data if flag is set
16027        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16028
16029        // Delete the child packages data
16030        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16031        for (int i = 0; i < childCount; i++) {
16032            PackageSetting childPs;
16033            synchronized (mPackages) {
16034                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16035            }
16036            if (childPs != null) {
16037                PackageRemovedInfo childOutInfo = (outInfo != null
16038                        && outInfo.removedChildPackages != null)
16039                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16040                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16041                        && (replacingPackage != null
16042                        && !replacingPackage.hasChildPackage(childPs.name))
16043                        ? flags & ~DELETE_KEEP_DATA : flags;
16044                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16045                        deleteFlags, writeSettings);
16046            }
16047        }
16048
16049        // Delete application code and resources only for parent packages
16050        if (ps.parentPackageName == null) {
16051            if (deleteCodeAndResources && (outInfo != null)) {
16052                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16053                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16054                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16055            }
16056        }
16057
16058        return true;
16059    }
16060
16061    @Override
16062    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16063            int userId) {
16064        mContext.enforceCallingOrSelfPermission(
16065                android.Manifest.permission.DELETE_PACKAGES, null);
16066        synchronized (mPackages) {
16067            PackageSetting ps = mSettings.mPackages.get(packageName);
16068            if (ps == null) {
16069                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16070                return false;
16071            }
16072            if (!ps.getInstalled(userId)) {
16073                // Can't block uninstall for an app that is not installed or enabled.
16074                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16075                return false;
16076            }
16077            ps.setBlockUninstall(blockUninstall, userId);
16078            mSettings.writePackageRestrictionsLPr(userId);
16079        }
16080        return true;
16081    }
16082
16083    @Override
16084    public boolean getBlockUninstallForUser(String packageName, int userId) {
16085        synchronized (mPackages) {
16086            PackageSetting ps = mSettings.mPackages.get(packageName);
16087            if (ps == null) {
16088                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16089                return false;
16090            }
16091            return ps.getBlockUninstall(userId);
16092        }
16093    }
16094
16095    @Override
16096    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16097        int callingUid = Binder.getCallingUid();
16098        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16099            throw new SecurityException(
16100                    "setRequiredForSystemUser can only be run by the system or root");
16101        }
16102        synchronized (mPackages) {
16103            PackageSetting ps = mSettings.mPackages.get(packageName);
16104            if (ps == null) {
16105                Log.w(TAG, "Package doesn't exist: " + packageName);
16106                return false;
16107            }
16108            if (systemUserApp) {
16109                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16110            } else {
16111                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16112            }
16113            mSettings.writeLPr();
16114        }
16115        return true;
16116    }
16117
16118    /*
16119     * This method handles package deletion in general
16120     */
16121    private boolean deletePackageLIF(String packageName, UserHandle user,
16122            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16123            PackageRemovedInfo outInfo, boolean writeSettings,
16124            PackageParser.Package replacingPackage) {
16125        if (packageName == null) {
16126            Slog.w(TAG, "Attempt to delete null packageName.");
16127            return false;
16128        }
16129
16130        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16131
16132        PackageSetting ps;
16133
16134        synchronized (mPackages) {
16135            ps = mSettings.mPackages.get(packageName);
16136            if (ps == null) {
16137                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16138                return false;
16139            }
16140
16141            if (ps.parentPackageName != null && (!isSystemApp(ps)
16142                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16143                if (DEBUG_REMOVE) {
16144                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16145                            + ((user == null) ? UserHandle.USER_ALL : user));
16146                }
16147                final int removedUserId = (user != null) ? user.getIdentifier()
16148                        : UserHandle.USER_ALL;
16149                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16150                    return false;
16151                }
16152                markPackageUninstalledForUserLPw(ps, user);
16153                scheduleWritePackageRestrictionsLocked(user);
16154                return true;
16155            }
16156        }
16157
16158        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16159                && user.getIdentifier() != UserHandle.USER_ALL)) {
16160            // The caller is asking that the package only be deleted for a single
16161            // user.  To do this, we just mark its uninstalled state and delete
16162            // its data. If this is a system app, we only allow this to happen if
16163            // they have set the special DELETE_SYSTEM_APP which requests different
16164            // semantics than normal for uninstalling system apps.
16165            markPackageUninstalledForUserLPw(ps, user);
16166
16167            if (!isSystemApp(ps)) {
16168                // Do not uninstall the APK if an app should be cached
16169                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16170                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16171                    // Other user still have this package installed, so all
16172                    // we need to do is clear this user's data and save that
16173                    // it is uninstalled.
16174                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16175                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16176                        return false;
16177                    }
16178                    scheduleWritePackageRestrictionsLocked(user);
16179                    return true;
16180                } else {
16181                    // We need to set it back to 'installed' so the uninstall
16182                    // broadcasts will be sent correctly.
16183                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16184                    ps.setInstalled(true, user.getIdentifier());
16185                }
16186            } else {
16187                // This is a system app, so we assume that the
16188                // other users still have this package installed, so all
16189                // we need to do is clear this user's data and save that
16190                // it is uninstalled.
16191                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16192                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16193                    return false;
16194                }
16195                scheduleWritePackageRestrictionsLocked(user);
16196                return true;
16197            }
16198        }
16199
16200        // If we are deleting a composite package for all users, keep track
16201        // of result for each child.
16202        if (ps.childPackageNames != null && outInfo != null) {
16203            synchronized (mPackages) {
16204                final int childCount = ps.childPackageNames.size();
16205                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16206                for (int i = 0; i < childCount; i++) {
16207                    String childPackageName = ps.childPackageNames.get(i);
16208                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16209                    childInfo.removedPackage = childPackageName;
16210                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16211                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16212                    if (childPs != null) {
16213                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16214                    }
16215                }
16216            }
16217        }
16218
16219        boolean ret = false;
16220        if (isSystemApp(ps)) {
16221            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16222            // When an updated system application is deleted we delete the existing resources
16223            // as well and fall back to existing code in system partition
16224            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16225        } else {
16226            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16227            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16228                    outInfo, writeSettings, replacingPackage);
16229        }
16230
16231        // Take a note whether we deleted the package for all users
16232        if (outInfo != null) {
16233            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16234            if (outInfo.removedChildPackages != null) {
16235                synchronized (mPackages) {
16236                    final int childCount = outInfo.removedChildPackages.size();
16237                    for (int i = 0; i < childCount; i++) {
16238                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16239                        if (childInfo != null) {
16240                            childInfo.removedForAllUsers = mPackages.get(
16241                                    childInfo.removedPackage) == null;
16242                        }
16243                    }
16244                }
16245            }
16246            // If we uninstalled an update to a system app there may be some
16247            // child packages that appeared as they are declared in the system
16248            // app but were not declared in the update.
16249            if (isSystemApp(ps)) {
16250                synchronized (mPackages) {
16251                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16252                    final int childCount = (updatedPs.childPackageNames != null)
16253                            ? updatedPs.childPackageNames.size() : 0;
16254                    for (int i = 0; i < childCount; i++) {
16255                        String childPackageName = updatedPs.childPackageNames.get(i);
16256                        if (outInfo.removedChildPackages == null
16257                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16258                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16259                            if (childPs == null) {
16260                                continue;
16261                            }
16262                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16263                            installRes.name = childPackageName;
16264                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16265                            installRes.pkg = mPackages.get(childPackageName);
16266                            installRes.uid = childPs.pkg.applicationInfo.uid;
16267                            if (outInfo.appearedChildPackages == null) {
16268                                outInfo.appearedChildPackages = new ArrayMap<>();
16269                            }
16270                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16271                        }
16272                    }
16273                }
16274            }
16275        }
16276
16277        return ret;
16278    }
16279
16280    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16281        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16282                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16283        for (int nextUserId : userIds) {
16284            if (DEBUG_REMOVE) {
16285                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16286            }
16287            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16288                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16289                    false /*hidden*/, false /*suspended*/, null, null, null,
16290                    false /*blockUninstall*/,
16291                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16292        }
16293    }
16294
16295    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16296            PackageRemovedInfo outInfo) {
16297        final PackageParser.Package pkg;
16298        synchronized (mPackages) {
16299            pkg = mPackages.get(ps.name);
16300        }
16301
16302        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16303                : new int[] {userId};
16304        for (int nextUserId : userIds) {
16305            if (DEBUG_REMOVE) {
16306                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16307                        + nextUserId);
16308            }
16309
16310            destroyAppDataLIF(pkg, userId,
16311                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16312            destroyAppProfilesLIF(pkg, userId);
16313            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16314            schedulePackageCleaning(ps.name, nextUserId, false);
16315            synchronized (mPackages) {
16316                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16317                    scheduleWritePackageRestrictionsLocked(nextUserId);
16318                }
16319                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16320            }
16321        }
16322
16323        if (outInfo != null) {
16324            outInfo.removedPackage = ps.name;
16325            outInfo.removedAppId = ps.appId;
16326            outInfo.removedUsers = userIds;
16327        }
16328
16329        return true;
16330    }
16331
16332    private final class ClearStorageConnection implements ServiceConnection {
16333        IMediaContainerService mContainerService;
16334
16335        @Override
16336        public void onServiceConnected(ComponentName name, IBinder service) {
16337            synchronized (this) {
16338                mContainerService = IMediaContainerService.Stub.asInterface(service);
16339                notifyAll();
16340            }
16341        }
16342
16343        @Override
16344        public void onServiceDisconnected(ComponentName name) {
16345        }
16346    }
16347
16348    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16349        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16350
16351        final boolean mounted;
16352        if (Environment.isExternalStorageEmulated()) {
16353            mounted = true;
16354        } else {
16355            final String status = Environment.getExternalStorageState();
16356
16357            mounted = status.equals(Environment.MEDIA_MOUNTED)
16358                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16359        }
16360
16361        if (!mounted) {
16362            return;
16363        }
16364
16365        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16366        int[] users;
16367        if (userId == UserHandle.USER_ALL) {
16368            users = sUserManager.getUserIds();
16369        } else {
16370            users = new int[] { userId };
16371        }
16372        final ClearStorageConnection conn = new ClearStorageConnection();
16373        if (mContext.bindServiceAsUser(
16374                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16375            try {
16376                for (int curUser : users) {
16377                    long timeout = SystemClock.uptimeMillis() + 5000;
16378                    synchronized (conn) {
16379                        long now;
16380                        while (conn.mContainerService == null &&
16381                                (now = SystemClock.uptimeMillis()) < timeout) {
16382                            try {
16383                                conn.wait(timeout - now);
16384                            } catch (InterruptedException e) {
16385                            }
16386                        }
16387                    }
16388                    if (conn.mContainerService == null) {
16389                        return;
16390                    }
16391
16392                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16393                    clearDirectory(conn.mContainerService,
16394                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16395                    if (allData) {
16396                        clearDirectory(conn.mContainerService,
16397                                userEnv.buildExternalStorageAppDataDirs(packageName));
16398                        clearDirectory(conn.mContainerService,
16399                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16400                    }
16401                }
16402            } finally {
16403                mContext.unbindService(conn);
16404            }
16405        }
16406    }
16407
16408    @Override
16409    public void clearApplicationProfileData(String packageName) {
16410        enforceSystemOrRoot("Only the system can clear all profile data");
16411
16412        final PackageParser.Package pkg;
16413        synchronized (mPackages) {
16414            pkg = mPackages.get(packageName);
16415        }
16416
16417        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16418            synchronized (mInstallLock) {
16419                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16420                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16421                        true /* removeBaseMarker */);
16422            }
16423        }
16424    }
16425
16426    @Override
16427    public void clearApplicationUserData(final String packageName,
16428            final IPackageDataObserver observer, final int userId) {
16429        mContext.enforceCallingOrSelfPermission(
16430                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16431
16432        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16433                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16434
16435        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16436            throw new SecurityException("Cannot clear data for a protected package: "
16437                    + packageName);
16438        }
16439        // Queue up an async operation since the package deletion may take a little while.
16440        mHandler.post(new Runnable() {
16441            public void run() {
16442                mHandler.removeCallbacks(this);
16443                final boolean succeeded;
16444                try (PackageFreezer freezer = freezePackage(packageName,
16445                        "clearApplicationUserData")) {
16446                    synchronized (mInstallLock) {
16447                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16448                    }
16449                    clearExternalStorageDataSync(packageName, userId, true);
16450                }
16451                if (succeeded) {
16452                    // invoke DeviceStorageMonitor's update method to clear any notifications
16453                    DeviceStorageMonitorInternal dsm = LocalServices
16454                            .getService(DeviceStorageMonitorInternal.class);
16455                    if (dsm != null) {
16456                        dsm.checkMemory();
16457                    }
16458                }
16459                if(observer != null) {
16460                    try {
16461                        observer.onRemoveCompleted(packageName, succeeded);
16462                    } catch (RemoteException e) {
16463                        Log.i(TAG, "Observer no longer exists.");
16464                    }
16465                } //end if observer
16466            } //end run
16467        });
16468    }
16469
16470    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16471        if (packageName == null) {
16472            Slog.w(TAG, "Attempt to delete null packageName.");
16473            return false;
16474        }
16475
16476        // Try finding details about the requested package
16477        PackageParser.Package pkg;
16478        synchronized (mPackages) {
16479            pkg = mPackages.get(packageName);
16480            if (pkg == null) {
16481                final PackageSetting ps = mSettings.mPackages.get(packageName);
16482                if (ps != null) {
16483                    pkg = ps.pkg;
16484                }
16485            }
16486
16487            if (pkg == null) {
16488                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16489                return false;
16490            }
16491
16492            PackageSetting ps = (PackageSetting) pkg.mExtras;
16493            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16494        }
16495
16496        clearAppDataLIF(pkg, userId,
16497                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16498
16499        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16500        removeKeystoreDataIfNeeded(userId, appId);
16501
16502        UserManagerInternal umInternal = getUserManagerInternal();
16503        final int flags;
16504        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16505            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16506        } else if (umInternal.isUserRunning(userId)) {
16507            flags = StorageManager.FLAG_STORAGE_DE;
16508        } else {
16509            flags = 0;
16510        }
16511        prepareAppDataContentsLIF(pkg, userId, flags);
16512
16513        return true;
16514    }
16515
16516    /**
16517     * Reverts user permission state changes (permissions and flags) in
16518     * all packages for a given user.
16519     *
16520     * @param userId The device user for which to do a reset.
16521     */
16522    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16523        final int packageCount = mPackages.size();
16524        for (int i = 0; i < packageCount; i++) {
16525            PackageParser.Package pkg = mPackages.valueAt(i);
16526            PackageSetting ps = (PackageSetting) pkg.mExtras;
16527            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16528        }
16529    }
16530
16531    private void resetNetworkPolicies(int userId) {
16532        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16533    }
16534
16535    /**
16536     * Reverts user permission state changes (permissions and flags).
16537     *
16538     * @param ps The package for which to reset.
16539     * @param userId The device user for which to do a reset.
16540     */
16541    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16542            final PackageSetting ps, final int userId) {
16543        if (ps.pkg == null) {
16544            return;
16545        }
16546
16547        // These are flags that can change base on user actions.
16548        final int userSettableMask = FLAG_PERMISSION_USER_SET
16549                | FLAG_PERMISSION_USER_FIXED
16550                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16551                | FLAG_PERMISSION_REVIEW_REQUIRED;
16552
16553        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16554                | FLAG_PERMISSION_POLICY_FIXED;
16555
16556        boolean writeInstallPermissions = false;
16557        boolean writeRuntimePermissions = false;
16558
16559        final int permissionCount = ps.pkg.requestedPermissions.size();
16560        for (int i = 0; i < permissionCount; i++) {
16561            String permission = ps.pkg.requestedPermissions.get(i);
16562
16563            BasePermission bp = mSettings.mPermissions.get(permission);
16564            if (bp == null) {
16565                continue;
16566            }
16567
16568            // If shared user we just reset the state to which only this app contributed.
16569            if (ps.sharedUser != null) {
16570                boolean used = false;
16571                final int packageCount = ps.sharedUser.packages.size();
16572                for (int j = 0; j < packageCount; j++) {
16573                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16574                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16575                            && pkg.pkg.requestedPermissions.contains(permission)) {
16576                        used = true;
16577                        break;
16578                    }
16579                }
16580                if (used) {
16581                    continue;
16582                }
16583            }
16584
16585            PermissionsState permissionsState = ps.getPermissionsState();
16586
16587            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16588
16589            // Always clear the user settable flags.
16590            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16591                    bp.name) != null;
16592            // If permission review is enabled and this is a legacy app, mark the
16593            // permission as requiring a review as this is the initial state.
16594            int flags = 0;
16595            if (Build.PERMISSIONS_REVIEW_REQUIRED
16596                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16597                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16598            }
16599            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16600                if (hasInstallState) {
16601                    writeInstallPermissions = true;
16602                } else {
16603                    writeRuntimePermissions = true;
16604                }
16605            }
16606
16607            // Below is only runtime permission handling.
16608            if (!bp.isRuntime()) {
16609                continue;
16610            }
16611
16612            // Never clobber system or policy.
16613            if ((oldFlags & policyOrSystemFlags) != 0) {
16614                continue;
16615            }
16616
16617            // If this permission was granted by default, make sure it is.
16618            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16619                if (permissionsState.grantRuntimePermission(bp, userId)
16620                        != PERMISSION_OPERATION_FAILURE) {
16621                    writeRuntimePermissions = true;
16622                }
16623            // If permission review is enabled the permissions for a legacy apps
16624            // are represented as constantly granted runtime ones, so don't revoke.
16625            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16626                // Otherwise, reset the permission.
16627                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16628                switch (revokeResult) {
16629                    case PERMISSION_OPERATION_SUCCESS:
16630                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16631                        writeRuntimePermissions = true;
16632                        final int appId = ps.appId;
16633                        mHandler.post(new Runnable() {
16634                            @Override
16635                            public void run() {
16636                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16637                            }
16638                        });
16639                    } break;
16640                }
16641            }
16642        }
16643
16644        // Synchronously write as we are taking permissions away.
16645        if (writeRuntimePermissions) {
16646            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16647        }
16648
16649        // Synchronously write as we are taking permissions away.
16650        if (writeInstallPermissions) {
16651            mSettings.writeLPr();
16652        }
16653    }
16654
16655    /**
16656     * Remove entries from the keystore daemon. Will only remove it if the
16657     * {@code appId} is valid.
16658     */
16659    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16660        if (appId < 0) {
16661            return;
16662        }
16663
16664        final KeyStore keyStore = KeyStore.getInstance();
16665        if (keyStore != null) {
16666            if (userId == UserHandle.USER_ALL) {
16667                for (final int individual : sUserManager.getUserIds()) {
16668                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16669                }
16670            } else {
16671                keyStore.clearUid(UserHandle.getUid(userId, appId));
16672            }
16673        } else {
16674            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16675        }
16676    }
16677
16678    @Override
16679    public void deleteApplicationCacheFiles(final String packageName,
16680            final IPackageDataObserver observer) {
16681        final int userId = UserHandle.getCallingUserId();
16682        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16683    }
16684
16685    @Override
16686    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16687            final IPackageDataObserver observer) {
16688        mContext.enforceCallingOrSelfPermission(
16689                android.Manifest.permission.DELETE_CACHE_FILES, null);
16690        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16691                /* requireFullPermission= */ true, /* checkShell= */ false,
16692                "delete application cache files");
16693
16694        final PackageParser.Package pkg;
16695        synchronized (mPackages) {
16696            pkg = mPackages.get(packageName);
16697        }
16698
16699        // Queue up an async operation since the package deletion may take a little while.
16700        mHandler.post(new Runnable() {
16701            public void run() {
16702                synchronized (mInstallLock) {
16703                    final int flags = StorageManager.FLAG_STORAGE_DE
16704                            | StorageManager.FLAG_STORAGE_CE;
16705                    // We're only clearing cache files, so we don't care if the
16706                    // app is unfrozen and still able to run
16707                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16708                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16709                }
16710                clearExternalStorageDataSync(packageName, userId, false);
16711                if (observer != null) {
16712                    try {
16713                        observer.onRemoveCompleted(packageName, true);
16714                    } catch (RemoteException e) {
16715                        Log.i(TAG, "Observer no longer exists.");
16716                    }
16717                }
16718            }
16719        });
16720    }
16721
16722    @Override
16723    public void getPackageSizeInfo(final String packageName, int userHandle,
16724            final IPackageStatsObserver observer) {
16725        mContext.enforceCallingOrSelfPermission(
16726                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16727        if (packageName == null) {
16728            throw new IllegalArgumentException("Attempt to get size of null packageName");
16729        }
16730
16731        PackageStats stats = new PackageStats(packageName, userHandle);
16732
16733        /*
16734         * Queue up an async operation since the package measurement may take a
16735         * little while.
16736         */
16737        Message msg = mHandler.obtainMessage(INIT_COPY);
16738        msg.obj = new MeasureParams(stats, observer);
16739        mHandler.sendMessage(msg);
16740    }
16741
16742    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16743        final PackageSetting ps;
16744        synchronized (mPackages) {
16745            ps = mSettings.mPackages.get(packageName);
16746            if (ps == null) {
16747                Slog.w(TAG, "Failed to find settings for " + packageName);
16748                return false;
16749            }
16750        }
16751        try {
16752            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16753                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16754                    ps.getCeDataInode(userId), ps.codePathString, stats);
16755        } catch (InstallerException e) {
16756            Slog.w(TAG, String.valueOf(e));
16757            return false;
16758        }
16759
16760        // For now, ignore code size of packages on system partition
16761        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16762            stats.codeSize = 0;
16763        }
16764
16765        return true;
16766    }
16767
16768    private int getUidTargetSdkVersionLockedLPr(int uid) {
16769        Object obj = mSettings.getUserIdLPr(uid);
16770        if (obj instanceof SharedUserSetting) {
16771            final SharedUserSetting sus = (SharedUserSetting) obj;
16772            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16773            final Iterator<PackageSetting> it = sus.packages.iterator();
16774            while (it.hasNext()) {
16775                final PackageSetting ps = it.next();
16776                if (ps.pkg != null) {
16777                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16778                    if (v < vers) vers = v;
16779                }
16780            }
16781            return vers;
16782        } else if (obj instanceof PackageSetting) {
16783            final PackageSetting ps = (PackageSetting) obj;
16784            if (ps.pkg != null) {
16785                return ps.pkg.applicationInfo.targetSdkVersion;
16786            }
16787        }
16788        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16789    }
16790
16791    @Override
16792    public void addPreferredActivity(IntentFilter filter, int match,
16793            ComponentName[] set, ComponentName activity, int userId) {
16794        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16795                "Adding preferred");
16796    }
16797
16798    private void addPreferredActivityInternal(IntentFilter filter, int match,
16799            ComponentName[] set, ComponentName activity, boolean always, int userId,
16800            String opname) {
16801        // writer
16802        int callingUid = Binder.getCallingUid();
16803        enforceCrossUserPermission(callingUid, userId,
16804                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16805        if (filter.countActions() == 0) {
16806            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16807            return;
16808        }
16809        synchronized (mPackages) {
16810            if (mContext.checkCallingOrSelfPermission(
16811                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16812                    != PackageManager.PERMISSION_GRANTED) {
16813                if (getUidTargetSdkVersionLockedLPr(callingUid)
16814                        < Build.VERSION_CODES.FROYO) {
16815                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16816                            + callingUid);
16817                    return;
16818                }
16819                mContext.enforceCallingOrSelfPermission(
16820                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16821            }
16822
16823            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16824            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16825                    + userId + ":");
16826            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16827            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16828            scheduleWritePackageRestrictionsLocked(userId);
16829            postPreferredActivityChangedBroadcast(userId);
16830        }
16831    }
16832
16833    private void postPreferredActivityChangedBroadcast(int userId) {
16834        mHandler.post(() -> {
16835            final IActivityManager am = ActivityManagerNative.getDefault();
16836            if (am == null) {
16837                return;
16838            }
16839
16840            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16841            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16842            try {
16843                am.broadcastIntent(null, intent, null, null,
16844                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
16845                        null, false, false, userId);
16846            } catch (RemoteException e) {
16847            }
16848        });
16849    }
16850
16851    @Override
16852    public void replacePreferredActivity(IntentFilter filter, int match,
16853            ComponentName[] set, ComponentName activity, int userId) {
16854        if (filter.countActions() != 1) {
16855            throw new IllegalArgumentException(
16856                    "replacePreferredActivity expects filter to have only 1 action.");
16857        }
16858        if (filter.countDataAuthorities() != 0
16859                || filter.countDataPaths() != 0
16860                || filter.countDataSchemes() > 1
16861                || filter.countDataTypes() != 0) {
16862            throw new IllegalArgumentException(
16863                    "replacePreferredActivity expects filter to have no data authorities, " +
16864                    "paths, or types; and at most one scheme.");
16865        }
16866
16867        final int callingUid = Binder.getCallingUid();
16868        enforceCrossUserPermission(callingUid, userId,
16869                true /* requireFullPermission */, false /* checkShell */,
16870                "replace preferred activity");
16871        synchronized (mPackages) {
16872            if (mContext.checkCallingOrSelfPermission(
16873                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16874                    != PackageManager.PERMISSION_GRANTED) {
16875                if (getUidTargetSdkVersionLockedLPr(callingUid)
16876                        < Build.VERSION_CODES.FROYO) {
16877                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16878                            + Binder.getCallingUid());
16879                    return;
16880                }
16881                mContext.enforceCallingOrSelfPermission(
16882                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16883            }
16884
16885            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16886            if (pir != null) {
16887                // Get all of the existing entries that exactly match this filter.
16888                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16889                if (existing != null && existing.size() == 1) {
16890                    PreferredActivity cur = existing.get(0);
16891                    if (DEBUG_PREFERRED) {
16892                        Slog.i(TAG, "Checking replace of preferred:");
16893                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16894                        if (!cur.mPref.mAlways) {
16895                            Slog.i(TAG, "  -- CUR; not mAlways!");
16896                        } else {
16897                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16898                            Slog.i(TAG, "  -- CUR: mSet="
16899                                    + Arrays.toString(cur.mPref.mSetComponents));
16900                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16901                            Slog.i(TAG, "  -- NEW: mMatch="
16902                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16903                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16904                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16905                        }
16906                    }
16907                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16908                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16909                            && cur.mPref.sameSet(set)) {
16910                        // Setting the preferred activity to what it happens to be already
16911                        if (DEBUG_PREFERRED) {
16912                            Slog.i(TAG, "Replacing with same preferred activity "
16913                                    + cur.mPref.mShortComponent + " for user "
16914                                    + userId + ":");
16915                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16916                        }
16917                        return;
16918                    }
16919                }
16920
16921                if (existing != null) {
16922                    if (DEBUG_PREFERRED) {
16923                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16924                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16925                    }
16926                    for (int i = 0; i < existing.size(); i++) {
16927                        PreferredActivity pa = existing.get(i);
16928                        if (DEBUG_PREFERRED) {
16929                            Slog.i(TAG, "Removing existing preferred activity "
16930                                    + pa.mPref.mComponent + ":");
16931                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16932                        }
16933                        pir.removeFilter(pa);
16934                    }
16935                }
16936            }
16937            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16938                    "Replacing preferred");
16939        }
16940    }
16941
16942    @Override
16943    public void clearPackagePreferredActivities(String packageName) {
16944        final int uid = Binder.getCallingUid();
16945        // writer
16946        synchronized (mPackages) {
16947            PackageParser.Package pkg = mPackages.get(packageName);
16948            if (pkg == null || pkg.applicationInfo.uid != uid) {
16949                if (mContext.checkCallingOrSelfPermission(
16950                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16951                        != PackageManager.PERMISSION_GRANTED) {
16952                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16953                            < Build.VERSION_CODES.FROYO) {
16954                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16955                                + Binder.getCallingUid());
16956                        return;
16957                    }
16958                    mContext.enforceCallingOrSelfPermission(
16959                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16960                }
16961            }
16962
16963            int user = UserHandle.getCallingUserId();
16964            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16965                scheduleWritePackageRestrictionsLocked(user);
16966            }
16967        }
16968    }
16969
16970    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16971    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16972        ArrayList<PreferredActivity> removed = null;
16973        boolean changed = false;
16974        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16975            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16976            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16977            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16978                continue;
16979            }
16980            Iterator<PreferredActivity> it = pir.filterIterator();
16981            while (it.hasNext()) {
16982                PreferredActivity pa = it.next();
16983                // Mark entry for removal only if it matches the package name
16984                // and the entry is of type "always".
16985                if (packageName == null ||
16986                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16987                                && pa.mPref.mAlways)) {
16988                    if (removed == null) {
16989                        removed = new ArrayList<PreferredActivity>();
16990                    }
16991                    removed.add(pa);
16992                }
16993            }
16994            if (removed != null) {
16995                for (int j=0; j<removed.size(); j++) {
16996                    PreferredActivity pa = removed.get(j);
16997                    pir.removeFilter(pa);
16998                }
16999                changed = true;
17000            }
17001        }
17002        if (changed) {
17003            postPreferredActivityChangedBroadcast(userId);
17004        }
17005        return changed;
17006    }
17007
17008    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17009    private void clearIntentFilterVerificationsLPw(int userId) {
17010        final int packageCount = mPackages.size();
17011        for (int i = 0; i < packageCount; i++) {
17012            PackageParser.Package pkg = mPackages.valueAt(i);
17013            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17014        }
17015    }
17016
17017    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17018    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17019        if (userId == UserHandle.USER_ALL) {
17020            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17021                    sUserManager.getUserIds())) {
17022                for (int oneUserId : sUserManager.getUserIds()) {
17023                    scheduleWritePackageRestrictionsLocked(oneUserId);
17024                }
17025            }
17026        } else {
17027            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17028                scheduleWritePackageRestrictionsLocked(userId);
17029            }
17030        }
17031    }
17032
17033    void clearDefaultBrowserIfNeeded(String packageName) {
17034        for (int oneUserId : sUserManager.getUserIds()) {
17035            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17036            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17037            if (packageName.equals(defaultBrowserPackageName)) {
17038                setDefaultBrowserPackageName(null, oneUserId);
17039            }
17040        }
17041    }
17042
17043    @Override
17044    public void resetApplicationPreferences(int userId) {
17045        mContext.enforceCallingOrSelfPermission(
17046                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17047        final long identity = Binder.clearCallingIdentity();
17048        // writer
17049        try {
17050            synchronized (mPackages) {
17051                clearPackagePreferredActivitiesLPw(null, userId);
17052                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17053                // TODO: We have to reset the default SMS and Phone. This requires
17054                // significant refactoring to keep all default apps in the package
17055                // manager (cleaner but more work) or have the services provide
17056                // callbacks to the package manager to request a default app reset.
17057                applyFactoryDefaultBrowserLPw(userId);
17058                clearIntentFilterVerificationsLPw(userId);
17059                primeDomainVerificationsLPw(userId);
17060                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17061                scheduleWritePackageRestrictionsLocked(userId);
17062            }
17063            resetNetworkPolicies(userId);
17064        } finally {
17065            Binder.restoreCallingIdentity(identity);
17066        }
17067    }
17068
17069    @Override
17070    public int getPreferredActivities(List<IntentFilter> outFilters,
17071            List<ComponentName> outActivities, String packageName) {
17072
17073        int num = 0;
17074        final int userId = UserHandle.getCallingUserId();
17075        // reader
17076        synchronized (mPackages) {
17077            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17078            if (pir != null) {
17079                final Iterator<PreferredActivity> it = pir.filterIterator();
17080                while (it.hasNext()) {
17081                    final PreferredActivity pa = it.next();
17082                    if (packageName == null
17083                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17084                                    && pa.mPref.mAlways)) {
17085                        if (outFilters != null) {
17086                            outFilters.add(new IntentFilter(pa));
17087                        }
17088                        if (outActivities != null) {
17089                            outActivities.add(pa.mPref.mComponent);
17090                        }
17091                    }
17092                }
17093            }
17094        }
17095
17096        return num;
17097    }
17098
17099    @Override
17100    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17101            int userId) {
17102        int callingUid = Binder.getCallingUid();
17103        if (callingUid != Process.SYSTEM_UID) {
17104            throw new SecurityException(
17105                    "addPersistentPreferredActivity can only be run by the system");
17106        }
17107        if (filter.countActions() == 0) {
17108            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17109            return;
17110        }
17111        synchronized (mPackages) {
17112            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17113                    ":");
17114            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17115            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17116                    new PersistentPreferredActivity(filter, activity));
17117            scheduleWritePackageRestrictionsLocked(userId);
17118            postPreferredActivityChangedBroadcast(userId);
17119        }
17120    }
17121
17122    @Override
17123    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17124        int callingUid = Binder.getCallingUid();
17125        if (callingUid != Process.SYSTEM_UID) {
17126            throw new SecurityException(
17127                    "clearPackagePersistentPreferredActivities can only be run by the system");
17128        }
17129        ArrayList<PersistentPreferredActivity> removed = null;
17130        boolean changed = false;
17131        synchronized (mPackages) {
17132            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17133                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17134                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17135                        .valueAt(i);
17136                if (userId != thisUserId) {
17137                    continue;
17138                }
17139                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17140                while (it.hasNext()) {
17141                    PersistentPreferredActivity ppa = it.next();
17142                    // Mark entry for removal only if it matches the package name.
17143                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17144                        if (removed == null) {
17145                            removed = new ArrayList<PersistentPreferredActivity>();
17146                        }
17147                        removed.add(ppa);
17148                    }
17149                }
17150                if (removed != null) {
17151                    for (int j=0; j<removed.size(); j++) {
17152                        PersistentPreferredActivity ppa = removed.get(j);
17153                        ppir.removeFilter(ppa);
17154                    }
17155                    changed = true;
17156                }
17157            }
17158
17159            if (changed) {
17160                scheduleWritePackageRestrictionsLocked(userId);
17161                postPreferredActivityChangedBroadcast(userId);
17162            }
17163        }
17164    }
17165
17166    /**
17167     * Common machinery for picking apart a restored XML blob and passing
17168     * it to a caller-supplied functor to be applied to the running system.
17169     */
17170    private void restoreFromXml(XmlPullParser parser, int userId,
17171            String expectedStartTag, BlobXmlRestorer functor)
17172            throws IOException, XmlPullParserException {
17173        int type;
17174        while ((type = parser.next()) != XmlPullParser.START_TAG
17175                && type != XmlPullParser.END_DOCUMENT) {
17176        }
17177        if (type != XmlPullParser.START_TAG) {
17178            // oops didn't find a start tag?!
17179            if (DEBUG_BACKUP) {
17180                Slog.e(TAG, "Didn't find start tag during restore");
17181            }
17182            return;
17183        }
17184Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17185        // this is supposed to be TAG_PREFERRED_BACKUP
17186        if (!expectedStartTag.equals(parser.getName())) {
17187            if (DEBUG_BACKUP) {
17188                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17189            }
17190            return;
17191        }
17192
17193        // skip interfering stuff, then we're aligned with the backing implementation
17194        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17195Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17196        functor.apply(parser, userId);
17197    }
17198
17199    private interface BlobXmlRestorer {
17200        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17201    }
17202
17203    /**
17204     * Non-Binder method, support for the backup/restore mechanism: write the
17205     * full set of preferred activities in its canonical XML format.  Returns the
17206     * XML output as a byte array, or null if there is none.
17207     */
17208    @Override
17209    public byte[] getPreferredActivityBackup(int userId) {
17210        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17211            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17212        }
17213
17214        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17215        try {
17216            final XmlSerializer serializer = new FastXmlSerializer();
17217            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17218            serializer.startDocument(null, true);
17219            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17220
17221            synchronized (mPackages) {
17222                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17223            }
17224
17225            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17226            serializer.endDocument();
17227            serializer.flush();
17228        } catch (Exception e) {
17229            if (DEBUG_BACKUP) {
17230                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17231            }
17232            return null;
17233        }
17234
17235        return dataStream.toByteArray();
17236    }
17237
17238    @Override
17239    public void restorePreferredActivities(byte[] backup, int userId) {
17240        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17241            throw new SecurityException("Only the system may call restorePreferredActivities()");
17242        }
17243
17244        try {
17245            final XmlPullParser parser = Xml.newPullParser();
17246            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17247            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17248                    new BlobXmlRestorer() {
17249                        @Override
17250                        public void apply(XmlPullParser parser, int userId)
17251                                throws XmlPullParserException, IOException {
17252                            synchronized (mPackages) {
17253                                mSettings.readPreferredActivitiesLPw(parser, userId);
17254                            }
17255                        }
17256                    } );
17257        } catch (Exception e) {
17258            if (DEBUG_BACKUP) {
17259                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17260            }
17261        }
17262    }
17263
17264    /**
17265     * Non-Binder method, support for the backup/restore mechanism: write the
17266     * default browser (etc) settings in its canonical XML format.  Returns the default
17267     * browser XML representation as a byte array, or null if there is none.
17268     */
17269    @Override
17270    public byte[] getDefaultAppsBackup(int userId) {
17271        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17272            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17273        }
17274
17275        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17276        try {
17277            final XmlSerializer serializer = new FastXmlSerializer();
17278            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17279            serializer.startDocument(null, true);
17280            serializer.startTag(null, TAG_DEFAULT_APPS);
17281
17282            synchronized (mPackages) {
17283                mSettings.writeDefaultAppsLPr(serializer, userId);
17284            }
17285
17286            serializer.endTag(null, TAG_DEFAULT_APPS);
17287            serializer.endDocument();
17288            serializer.flush();
17289        } catch (Exception e) {
17290            if (DEBUG_BACKUP) {
17291                Slog.e(TAG, "Unable to write default apps for backup", e);
17292            }
17293            return null;
17294        }
17295
17296        return dataStream.toByteArray();
17297    }
17298
17299    @Override
17300    public void restoreDefaultApps(byte[] backup, int userId) {
17301        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17302            throw new SecurityException("Only the system may call restoreDefaultApps()");
17303        }
17304
17305        try {
17306            final XmlPullParser parser = Xml.newPullParser();
17307            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17308            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17309                    new BlobXmlRestorer() {
17310                        @Override
17311                        public void apply(XmlPullParser parser, int userId)
17312                                throws XmlPullParserException, IOException {
17313                            synchronized (mPackages) {
17314                                mSettings.readDefaultAppsLPw(parser, userId);
17315                            }
17316                        }
17317                    } );
17318        } catch (Exception e) {
17319            if (DEBUG_BACKUP) {
17320                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17321            }
17322        }
17323    }
17324
17325    @Override
17326    public byte[] getIntentFilterVerificationBackup(int userId) {
17327        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17328            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17329        }
17330
17331        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17332        try {
17333            final XmlSerializer serializer = new FastXmlSerializer();
17334            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17335            serializer.startDocument(null, true);
17336            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17337
17338            synchronized (mPackages) {
17339                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17340            }
17341
17342            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17343            serializer.endDocument();
17344            serializer.flush();
17345        } catch (Exception e) {
17346            if (DEBUG_BACKUP) {
17347                Slog.e(TAG, "Unable to write default apps for backup", e);
17348            }
17349            return null;
17350        }
17351
17352        return dataStream.toByteArray();
17353    }
17354
17355    @Override
17356    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17357        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17358            throw new SecurityException("Only the system may call restorePreferredActivities()");
17359        }
17360
17361        try {
17362            final XmlPullParser parser = Xml.newPullParser();
17363            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17364            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17365                    new BlobXmlRestorer() {
17366                        @Override
17367                        public void apply(XmlPullParser parser, int userId)
17368                                throws XmlPullParserException, IOException {
17369                            synchronized (mPackages) {
17370                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17371                                mSettings.writeLPr();
17372                            }
17373                        }
17374                    } );
17375        } catch (Exception e) {
17376            if (DEBUG_BACKUP) {
17377                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17378            }
17379        }
17380    }
17381
17382    @Override
17383    public byte[] getPermissionGrantBackup(int userId) {
17384        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17385            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17386        }
17387
17388        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17389        try {
17390            final XmlSerializer serializer = new FastXmlSerializer();
17391            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17392            serializer.startDocument(null, true);
17393            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17394
17395            synchronized (mPackages) {
17396                serializeRuntimePermissionGrantsLPr(serializer, userId);
17397            }
17398
17399            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17400            serializer.endDocument();
17401            serializer.flush();
17402        } catch (Exception e) {
17403            if (DEBUG_BACKUP) {
17404                Slog.e(TAG, "Unable to write default apps for backup", e);
17405            }
17406            return null;
17407        }
17408
17409        return dataStream.toByteArray();
17410    }
17411
17412    @Override
17413    public void restorePermissionGrants(byte[] backup, int userId) {
17414        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17415            throw new SecurityException("Only the system may call restorePermissionGrants()");
17416        }
17417
17418        try {
17419            final XmlPullParser parser = Xml.newPullParser();
17420            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17421            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17422                    new BlobXmlRestorer() {
17423                        @Override
17424                        public void apply(XmlPullParser parser, int userId)
17425                                throws XmlPullParserException, IOException {
17426                            synchronized (mPackages) {
17427                                processRestoredPermissionGrantsLPr(parser, userId);
17428                            }
17429                        }
17430                    } );
17431        } catch (Exception e) {
17432            if (DEBUG_BACKUP) {
17433                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17434            }
17435        }
17436    }
17437
17438    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17439            throws IOException {
17440        serializer.startTag(null, TAG_ALL_GRANTS);
17441
17442        final int N = mSettings.mPackages.size();
17443        for (int i = 0; i < N; i++) {
17444            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17445            boolean pkgGrantsKnown = false;
17446
17447            PermissionsState packagePerms = ps.getPermissionsState();
17448
17449            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17450                final int grantFlags = state.getFlags();
17451                // only look at grants that are not system/policy fixed
17452                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17453                    final boolean isGranted = state.isGranted();
17454                    // And only back up the user-twiddled state bits
17455                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17456                        final String packageName = mSettings.mPackages.keyAt(i);
17457                        if (!pkgGrantsKnown) {
17458                            serializer.startTag(null, TAG_GRANT);
17459                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17460                            pkgGrantsKnown = true;
17461                        }
17462
17463                        final boolean userSet =
17464                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17465                        final boolean userFixed =
17466                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17467                        final boolean revoke =
17468                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17469
17470                        serializer.startTag(null, TAG_PERMISSION);
17471                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17472                        if (isGranted) {
17473                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17474                        }
17475                        if (userSet) {
17476                            serializer.attribute(null, ATTR_USER_SET, "true");
17477                        }
17478                        if (userFixed) {
17479                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17480                        }
17481                        if (revoke) {
17482                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17483                        }
17484                        serializer.endTag(null, TAG_PERMISSION);
17485                    }
17486                }
17487            }
17488
17489            if (pkgGrantsKnown) {
17490                serializer.endTag(null, TAG_GRANT);
17491            }
17492        }
17493
17494        serializer.endTag(null, TAG_ALL_GRANTS);
17495    }
17496
17497    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17498            throws XmlPullParserException, IOException {
17499        String pkgName = null;
17500        int outerDepth = parser.getDepth();
17501        int type;
17502        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17503                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17504            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17505                continue;
17506            }
17507
17508            final String tagName = parser.getName();
17509            if (tagName.equals(TAG_GRANT)) {
17510                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17511                if (DEBUG_BACKUP) {
17512                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17513                }
17514            } else if (tagName.equals(TAG_PERMISSION)) {
17515
17516                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17517                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17518
17519                int newFlagSet = 0;
17520                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17521                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17522                }
17523                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17524                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17525                }
17526                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17527                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17528                }
17529                if (DEBUG_BACKUP) {
17530                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17531                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17532                }
17533                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17534                if (ps != null) {
17535                    // Already installed so we apply the grant immediately
17536                    if (DEBUG_BACKUP) {
17537                        Slog.v(TAG, "        + already installed; applying");
17538                    }
17539                    PermissionsState perms = ps.getPermissionsState();
17540                    BasePermission bp = mSettings.mPermissions.get(permName);
17541                    if (bp != null) {
17542                        if (isGranted) {
17543                            perms.grantRuntimePermission(bp, userId);
17544                        }
17545                        if (newFlagSet != 0) {
17546                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17547                        }
17548                    }
17549                } else {
17550                    // Need to wait for post-restore install to apply the grant
17551                    if (DEBUG_BACKUP) {
17552                        Slog.v(TAG, "        - not yet installed; saving for later");
17553                    }
17554                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17555                            isGranted, newFlagSet, userId);
17556                }
17557            } else {
17558                PackageManagerService.reportSettingsProblem(Log.WARN,
17559                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17560                XmlUtils.skipCurrentTag(parser);
17561            }
17562        }
17563
17564        scheduleWriteSettingsLocked();
17565        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17566    }
17567
17568    @Override
17569    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17570            int sourceUserId, int targetUserId, int flags) {
17571        mContext.enforceCallingOrSelfPermission(
17572                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17573        int callingUid = Binder.getCallingUid();
17574        enforceOwnerRights(ownerPackage, callingUid);
17575        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17576        if (intentFilter.countActions() == 0) {
17577            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17578            return;
17579        }
17580        synchronized (mPackages) {
17581            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17582                    ownerPackage, targetUserId, flags);
17583            CrossProfileIntentResolver resolver =
17584                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17585            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17586            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17587            if (existing != null) {
17588                int size = existing.size();
17589                for (int i = 0; i < size; i++) {
17590                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17591                        return;
17592                    }
17593                }
17594            }
17595            resolver.addFilter(newFilter);
17596            scheduleWritePackageRestrictionsLocked(sourceUserId);
17597        }
17598    }
17599
17600    @Override
17601    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17602        mContext.enforceCallingOrSelfPermission(
17603                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17604        int callingUid = Binder.getCallingUid();
17605        enforceOwnerRights(ownerPackage, callingUid);
17606        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17607        synchronized (mPackages) {
17608            CrossProfileIntentResolver resolver =
17609                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17610            ArraySet<CrossProfileIntentFilter> set =
17611                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17612            for (CrossProfileIntentFilter filter : set) {
17613                if (filter.getOwnerPackage().equals(ownerPackage)) {
17614                    resolver.removeFilter(filter);
17615                }
17616            }
17617            scheduleWritePackageRestrictionsLocked(sourceUserId);
17618        }
17619    }
17620
17621    // Enforcing that callingUid is owning pkg on userId
17622    private void enforceOwnerRights(String pkg, int callingUid) {
17623        // The system owns everything.
17624        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17625            return;
17626        }
17627        int callingUserId = UserHandle.getUserId(callingUid);
17628        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17629        if (pi == null) {
17630            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17631                    + callingUserId);
17632        }
17633        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17634            throw new SecurityException("Calling uid " + callingUid
17635                    + " does not own package " + pkg);
17636        }
17637    }
17638
17639    @Override
17640    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17641        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17642    }
17643
17644    private Intent getHomeIntent() {
17645        Intent intent = new Intent(Intent.ACTION_MAIN);
17646        intent.addCategory(Intent.CATEGORY_HOME);
17647        intent.addCategory(Intent.CATEGORY_DEFAULT);
17648        return intent;
17649    }
17650
17651    private IntentFilter getHomeFilter() {
17652        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17653        filter.addCategory(Intent.CATEGORY_HOME);
17654        filter.addCategory(Intent.CATEGORY_DEFAULT);
17655        return filter;
17656    }
17657
17658    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17659            int userId) {
17660        Intent intent  = getHomeIntent();
17661        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17662                PackageManager.GET_META_DATA, userId);
17663        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17664                true, false, false, userId);
17665
17666        allHomeCandidates.clear();
17667        if (list != null) {
17668            for (ResolveInfo ri : list) {
17669                allHomeCandidates.add(ri);
17670            }
17671        }
17672        return (preferred == null || preferred.activityInfo == null)
17673                ? null
17674                : new ComponentName(preferred.activityInfo.packageName,
17675                        preferred.activityInfo.name);
17676    }
17677
17678    @Override
17679    public void setHomeActivity(ComponentName comp, int userId) {
17680        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17681        getHomeActivitiesAsUser(homeActivities, userId);
17682
17683        boolean found = false;
17684
17685        final int size = homeActivities.size();
17686        final ComponentName[] set = new ComponentName[size];
17687        for (int i = 0; i < size; i++) {
17688            final ResolveInfo candidate = homeActivities.get(i);
17689            final ActivityInfo info = candidate.activityInfo;
17690            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17691            set[i] = activityName;
17692            if (!found && activityName.equals(comp)) {
17693                found = true;
17694            }
17695        }
17696        if (!found) {
17697            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17698                    + userId);
17699        }
17700        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17701                set, comp, userId);
17702    }
17703
17704    private @Nullable String getSetupWizardPackageName() {
17705        final Intent intent = new Intent(Intent.ACTION_MAIN);
17706        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17707
17708        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17709                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17710                        | MATCH_DISABLED_COMPONENTS,
17711                UserHandle.myUserId());
17712        if (matches.size() == 1) {
17713            return matches.get(0).getComponentInfo().packageName;
17714        } else {
17715            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17716                    + ": matches=" + matches);
17717            return null;
17718        }
17719    }
17720
17721    @Override
17722    public void setApplicationEnabledSetting(String appPackageName,
17723            int newState, int flags, int userId, String callingPackage) {
17724        if (!sUserManager.exists(userId)) return;
17725        if (callingPackage == null) {
17726            callingPackage = Integer.toString(Binder.getCallingUid());
17727        }
17728        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17729    }
17730
17731    @Override
17732    public void setComponentEnabledSetting(ComponentName componentName,
17733            int newState, int flags, int userId) {
17734        if (!sUserManager.exists(userId)) return;
17735        setEnabledSetting(componentName.getPackageName(),
17736                componentName.getClassName(), newState, flags, userId, null);
17737    }
17738
17739    private void setEnabledSetting(final String packageName, String className, int newState,
17740            final int flags, int userId, String callingPackage) {
17741        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17742              || newState == COMPONENT_ENABLED_STATE_ENABLED
17743              || newState == COMPONENT_ENABLED_STATE_DISABLED
17744              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17745              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17746            throw new IllegalArgumentException("Invalid new component state: "
17747                    + newState);
17748        }
17749        PackageSetting pkgSetting;
17750        final int uid = Binder.getCallingUid();
17751        final int permission;
17752        if (uid == Process.SYSTEM_UID) {
17753            permission = PackageManager.PERMISSION_GRANTED;
17754        } else {
17755            permission = mContext.checkCallingOrSelfPermission(
17756                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17757        }
17758        enforceCrossUserPermission(uid, userId,
17759                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17760        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17761        boolean sendNow = false;
17762        boolean isApp = (className == null);
17763        String componentName = isApp ? packageName : className;
17764        int packageUid = -1;
17765        ArrayList<String> components;
17766
17767        // writer
17768        synchronized (mPackages) {
17769            pkgSetting = mSettings.mPackages.get(packageName);
17770            if (pkgSetting == null) {
17771                if (className == null) {
17772                    throw new IllegalArgumentException("Unknown package: " + packageName);
17773                }
17774                throw new IllegalArgumentException(
17775                        "Unknown component: " + packageName + "/" + className);
17776            }
17777        }
17778
17779        // Limit who can change which apps
17780        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17781            // Don't allow apps that don't have permission to modify other apps
17782            if (!allowedByPermission) {
17783                throw new SecurityException(
17784                        "Permission Denial: attempt to change component state from pid="
17785                        + Binder.getCallingPid()
17786                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17787            }
17788            // Don't allow changing protected packages.
17789            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17790                throw new SecurityException("Cannot disable a protected package: " + packageName);
17791            }
17792        }
17793
17794        synchronized (mPackages) {
17795            if (uid == Process.SHELL_UID) {
17796                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17797                int oldState = pkgSetting.getEnabled(userId);
17798                if (className == null
17799                    &&
17800                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17801                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17802                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17803                    &&
17804                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17805                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17806                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17807                    // ok
17808                } else {
17809                    throw new SecurityException(
17810                            "Shell cannot change component state for " + packageName + "/"
17811                            + className + " to " + newState);
17812                }
17813            }
17814            if (className == null) {
17815                // We're dealing with an application/package level state change
17816                if (pkgSetting.getEnabled(userId) == newState) {
17817                    // Nothing to do
17818                    return;
17819                }
17820                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17821                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17822                    // Don't care about who enables an app.
17823                    callingPackage = null;
17824                }
17825                pkgSetting.setEnabled(newState, userId, callingPackage);
17826                // pkgSetting.pkg.mSetEnabled = newState;
17827            } else {
17828                // We're dealing with a component level state change
17829                // First, verify that this is a valid class name.
17830                PackageParser.Package pkg = pkgSetting.pkg;
17831                if (pkg == null || !pkg.hasComponentClassName(className)) {
17832                    if (pkg != null &&
17833                            pkg.applicationInfo.targetSdkVersion >=
17834                                    Build.VERSION_CODES.JELLY_BEAN) {
17835                        throw new IllegalArgumentException("Component class " + className
17836                                + " does not exist in " + packageName);
17837                    } else {
17838                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17839                                + className + " does not exist in " + packageName);
17840                    }
17841                }
17842                switch (newState) {
17843                case COMPONENT_ENABLED_STATE_ENABLED:
17844                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17845                        return;
17846                    }
17847                    break;
17848                case COMPONENT_ENABLED_STATE_DISABLED:
17849                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17850                        return;
17851                    }
17852                    break;
17853                case COMPONENT_ENABLED_STATE_DEFAULT:
17854                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17855                        return;
17856                    }
17857                    break;
17858                default:
17859                    Slog.e(TAG, "Invalid new component state: " + newState);
17860                    return;
17861                }
17862            }
17863            scheduleWritePackageRestrictionsLocked(userId);
17864            components = mPendingBroadcasts.get(userId, packageName);
17865            final boolean newPackage = components == null;
17866            if (newPackage) {
17867                components = new ArrayList<String>();
17868            }
17869            if (!components.contains(componentName)) {
17870                components.add(componentName);
17871            }
17872            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17873                sendNow = true;
17874                // Purge entry from pending broadcast list if another one exists already
17875                // since we are sending one right away.
17876                mPendingBroadcasts.remove(userId, packageName);
17877            } else {
17878                if (newPackage) {
17879                    mPendingBroadcasts.put(userId, packageName, components);
17880                }
17881                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17882                    // Schedule a message
17883                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17884                }
17885            }
17886        }
17887
17888        long callingId = Binder.clearCallingIdentity();
17889        try {
17890            if (sendNow) {
17891                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17892                sendPackageChangedBroadcast(packageName,
17893                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17894            }
17895        } finally {
17896            Binder.restoreCallingIdentity(callingId);
17897        }
17898    }
17899
17900    @Override
17901    public void flushPackageRestrictionsAsUser(int userId) {
17902        if (!sUserManager.exists(userId)) {
17903            return;
17904        }
17905        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17906                false /* checkShell */, "flushPackageRestrictions");
17907        synchronized (mPackages) {
17908            mSettings.writePackageRestrictionsLPr(userId);
17909            mDirtyUsers.remove(userId);
17910            if (mDirtyUsers.isEmpty()) {
17911                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17912            }
17913        }
17914    }
17915
17916    private void sendPackageChangedBroadcast(String packageName,
17917            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17918        if (DEBUG_INSTALL)
17919            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17920                    + componentNames);
17921        Bundle extras = new Bundle(4);
17922        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17923        String nameList[] = new String[componentNames.size()];
17924        componentNames.toArray(nameList);
17925        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17926        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17927        extras.putInt(Intent.EXTRA_UID, packageUid);
17928        // If this is not reporting a change of the overall package, then only send it
17929        // to registered receivers.  We don't want to launch a swath of apps for every
17930        // little component state change.
17931        final int flags = !componentNames.contains(packageName)
17932                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17933        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17934                new int[] {UserHandle.getUserId(packageUid)});
17935    }
17936
17937    @Override
17938    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17939        if (!sUserManager.exists(userId)) return;
17940        final int uid = Binder.getCallingUid();
17941        final int permission = mContext.checkCallingOrSelfPermission(
17942                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17943        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17944        enforceCrossUserPermission(uid, userId,
17945                true /* requireFullPermission */, true /* checkShell */, "stop package");
17946        // writer
17947        synchronized (mPackages) {
17948            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17949                    allowedByPermission, uid, userId)) {
17950                scheduleWritePackageRestrictionsLocked(userId);
17951            }
17952        }
17953    }
17954
17955    @Override
17956    public String getInstallerPackageName(String packageName) {
17957        // reader
17958        synchronized (mPackages) {
17959            return mSettings.getInstallerPackageNameLPr(packageName);
17960        }
17961    }
17962
17963    public boolean isOrphaned(String packageName) {
17964        // reader
17965        synchronized (mPackages) {
17966            return mSettings.isOrphaned(packageName);
17967        }
17968    }
17969
17970    @Override
17971    public int getApplicationEnabledSetting(String packageName, int userId) {
17972        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17973        int uid = Binder.getCallingUid();
17974        enforceCrossUserPermission(uid, userId,
17975                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17976        // reader
17977        synchronized (mPackages) {
17978            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17979        }
17980    }
17981
17982    @Override
17983    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17984        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17985        int uid = Binder.getCallingUid();
17986        enforceCrossUserPermission(uid, userId,
17987                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17988        // reader
17989        synchronized (mPackages) {
17990            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17991        }
17992    }
17993
17994    @Override
17995    public void enterSafeMode() {
17996        enforceSystemOrRoot("Only the system can request entering safe mode");
17997
17998        if (!mSystemReady) {
17999            mSafeMode = true;
18000        }
18001    }
18002
18003    @Override
18004    public void systemReady() {
18005        mSystemReady = true;
18006
18007        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18008        // disabled after already being started.
18009        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18010                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18011
18012        // Read the compatibilty setting when the system is ready.
18013        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18014                mContext.getContentResolver(),
18015                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18016        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18017        if (DEBUG_SETTINGS) {
18018            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18019        }
18020
18021        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18022
18023        synchronized (mPackages) {
18024            // Verify that all of the preferred activity components actually
18025            // exist.  It is possible for applications to be updated and at
18026            // that point remove a previously declared activity component that
18027            // had been set as a preferred activity.  We try to clean this up
18028            // the next time we encounter that preferred activity, but it is
18029            // possible for the user flow to never be able to return to that
18030            // situation so here we do a sanity check to make sure we haven't
18031            // left any junk around.
18032            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18033            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18034                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18035                removed.clear();
18036                for (PreferredActivity pa : pir.filterSet()) {
18037                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18038                        removed.add(pa);
18039                    }
18040                }
18041                if (removed.size() > 0) {
18042                    for (int r=0; r<removed.size(); r++) {
18043                        PreferredActivity pa = removed.get(r);
18044                        Slog.w(TAG, "Removing dangling preferred activity: "
18045                                + pa.mPref.mComponent);
18046                        pir.removeFilter(pa);
18047                    }
18048                    mSettings.writePackageRestrictionsLPr(
18049                            mSettings.mPreferredActivities.keyAt(i));
18050                }
18051            }
18052
18053            for (int userId : UserManagerService.getInstance().getUserIds()) {
18054                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18055                    grantPermissionsUserIds = ArrayUtils.appendInt(
18056                            grantPermissionsUserIds, userId);
18057                }
18058            }
18059        }
18060        sUserManager.systemReady();
18061
18062        // If we upgraded grant all default permissions before kicking off.
18063        for (int userId : grantPermissionsUserIds) {
18064            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18065        }
18066
18067        // If we did not grant default permissions, we preload from this the
18068        // default permission exceptions lazily to ensure we don't hit the
18069        // disk on a new user creation.
18070        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18071            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18072        }
18073
18074        // Kick off any messages waiting for system ready
18075        if (mPostSystemReadyMessages != null) {
18076            for (Message msg : mPostSystemReadyMessages) {
18077                msg.sendToTarget();
18078            }
18079            mPostSystemReadyMessages = null;
18080        }
18081
18082        // Watch for external volumes that come and go over time
18083        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18084        storage.registerListener(mStorageListener);
18085
18086        mInstallerService.systemReady();
18087        mPackageDexOptimizer.systemReady();
18088
18089        MountServiceInternal mountServiceInternal = LocalServices.getService(
18090                MountServiceInternal.class);
18091        mountServiceInternal.addExternalStoragePolicy(
18092                new MountServiceInternal.ExternalStorageMountPolicy() {
18093            @Override
18094            public int getMountMode(int uid, String packageName) {
18095                if (Process.isIsolated(uid)) {
18096                    return Zygote.MOUNT_EXTERNAL_NONE;
18097                }
18098                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18099                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18100                }
18101                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18102                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18103                }
18104                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18105                    return Zygote.MOUNT_EXTERNAL_READ;
18106                }
18107                return Zygote.MOUNT_EXTERNAL_WRITE;
18108            }
18109
18110            @Override
18111            public boolean hasExternalStorage(int uid, String packageName) {
18112                return true;
18113            }
18114        });
18115
18116        // Now that we're mostly running, clean up stale users and apps
18117        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18118        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18119    }
18120
18121    @Override
18122    public boolean isSafeMode() {
18123        return mSafeMode;
18124    }
18125
18126    @Override
18127    public boolean hasSystemUidErrors() {
18128        return mHasSystemUidErrors;
18129    }
18130
18131    static String arrayToString(int[] array) {
18132        StringBuffer buf = new StringBuffer(128);
18133        buf.append('[');
18134        if (array != null) {
18135            for (int i=0; i<array.length; i++) {
18136                if (i > 0) buf.append(", ");
18137                buf.append(array[i]);
18138            }
18139        }
18140        buf.append(']');
18141        return buf.toString();
18142    }
18143
18144    static class DumpState {
18145        public static final int DUMP_LIBS = 1 << 0;
18146        public static final int DUMP_FEATURES = 1 << 1;
18147        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18148        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18149        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18150        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18151        public static final int DUMP_PERMISSIONS = 1 << 6;
18152        public static final int DUMP_PACKAGES = 1 << 7;
18153        public static final int DUMP_SHARED_USERS = 1 << 8;
18154        public static final int DUMP_MESSAGES = 1 << 9;
18155        public static final int DUMP_PROVIDERS = 1 << 10;
18156        public static final int DUMP_VERIFIERS = 1 << 11;
18157        public static final int DUMP_PREFERRED = 1 << 12;
18158        public static final int DUMP_PREFERRED_XML = 1 << 13;
18159        public static final int DUMP_KEYSETS = 1 << 14;
18160        public static final int DUMP_VERSION = 1 << 15;
18161        public static final int DUMP_INSTALLS = 1 << 16;
18162        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18163        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18164        public static final int DUMP_FROZEN = 1 << 19;
18165        public static final int DUMP_DEXOPT = 1 << 20;
18166        public static final int DUMP_COMPILER_STATS = 1 << 21;
18167
18168        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18169
18170        private int mTypes;
18171
18172        private int mOptions;
18173
18174        private boolean mTitlePrinted;
18175
18176        private SharedUserSetting mSharedUser;
18177
18178        public boolean isDumping(int type) {
18179            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18180                return true;
18181            }
18182
18183            return (mTypes & type) != 0;
18184        }
18185
18186        public void setDump(int type) {
18187            mTypes |= type;
18188        }
18189
18190        public boolean isOptionEnabled(int option) {
18191            return (mOptions & option) != 0;
18192        }
18193
18194        public void setOptionEnabled(int option) {
18195            mOptions |= option;
18196        }
18197
18198        public boolean onTitlePrinted() {
18199            final boolean printed = mTitlePrinted;
18200            mTitlePrinted = true;
18201            return printed;
18202        }
18203
18204        public boolean getTitlePrinted() {
18205            return mTitlePrinted;
18206        }
18207
18208        public void setTitlePrinted(boolean enabled) {
18209            mTitlePrinted = enabled;
18210        }
18211
18212        public SharedUserSetting getSharedUser() {
18213            return mSharedUser;
18214        }
18215
18216        public void setSharedUser(SharedUserSetting user) {
18217            mSharedUser = user;
18218        }
18219    }
18220
18221    @Override
18222    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18223            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18224        (new PackageManagerShellCommand(this)).exec(
18225                this, in, out, err, args, resultReceiver);
18226    }
18227
18228    @Override
18229    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18230        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18231                != PackageManager.PERMISSION_GRANTED) {
18232            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18233                    + Binder.getCallingPid()
18234                    + ", uid=" + Binder.getCallingUid()
18235                    + " without permission "
18236                    + android.Manifest.permission.DUMP);
18237            return;
18238        }
18239
18240        DumpState dumpState = new DumpState();
18241        boolean fullPreferred = false;
18242        boolean checkin = false;
18243
18244        String packageName = null;
18245        ArraySet<String> permissionNames = null;
18246
18247        int opti = 0;
18248        while (opti < args.length) {
18249            String opt = args[opti];
18250            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18251                break;
18252            }
18253            opti++;
18254
18255            if ("-a".equals(opt)) {
18256                // Right now we only know how to print all.
18257            } else if ("-h".equals(opt)) {
18258                pw.println("Package manager dump options:");
18259                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18260                pw.println("    --checkin: dump for a checkin");
18261                pw.println("    -f: print details of intent filters");
18262                pw.println("    -h: print this help");
18263                pw.println("  cmd may be one of:");
18264                pw.println("    l[ibraries]: list known shared libraries");
18265                pw.println("    f[eatures]: list device features");
18266                pw.println("    k[eysets]: print known keysets");
18267                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18268                pw.println("    perm[issions]: dump permissions");
18269                pw.println("    permission [name ...]: dump declaration and use of given permission");
18270                pw.println("    pref[erred]: print preferred package settings");
18271                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18272                pw.println("    prov[iders]: dump content providers");
18273                pw.println("    p[ackages]: dump installed packages");
18274                pw.println("    s[hared-users]: dump shared user IDs");
18275                pw.println("    m[essages]: print collected runtime messages");
18276                pw.println("    v[erifiers]: print package verifier info");
18277                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18278                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18279                pw.println("    version: print database version info");
18280                pw.println("    write: write current settings now");
18281                pw.println("    installs: details about install sessions");
18282                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18283                pw.println("    dexopt: dump dexopt state");
18284                pw.println("    compiler-stats: dump compiler statistics");
18285                pw.println("    <package.name>: info about given package");
18286                return;
18287            } else if ("--checkin".equals(opt)) {
18288                checkin = true;
18289            } else if ("-f".equals(opt)) {
18290                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18291            } else {
18292                pw.println("Unknown argument: " + opt + "; use -h for help");
18293            }
18294        }
18295
18296        // Is the caller requesting to dump a particular piece of data?
18297        if (opti < args.length) {
18298            String cmd = args[opti];
18299            opti++;
18300            // Is this a package name?
18301            if ("android".equals(cmd) || cmd.contains(".")) {
18302                packageName = cmd;
18303                // When dumping a single package, we always dump all of its
18304                // filter information since the amount of data will be reasonable.
18305                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18306            } else if ("check-permission".equals(cmd)) {
18307                if (opti >= args.length) {
18308                    pw.println("Error: check-permission missing permission argument");
18309                    return;
18310                }
18311                String perm = args[opti];
18312                opti++;
18313                if (opti >= args.length) {
18314                    pw.println("Error: check-permission missing package argument");
18315                    return;
18316                }
18317                String pkg = args[opti];
18318                opti++;
18319                int user = UserHandle.getUserId(Binder.getCallingUid());
18320                if (opti < args.length) {
18321                    try {
18322                        user = Integer.parseInt(args[opti]);
18323                    } catch (NumberFormatException e) {
18324                        pw.println("Error: check-permission user argument is not a number: "
18325                                + args[opti]);
18326                        return;
18327                    }
18328                }
18329                pw.println(checkPermission(perm, pkg, user));
18330                return;
18331            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18332                dumpState.setDump(DumpState.DUMP_LIBS);
18333            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18334                dumpState.setDump(DumpState.DUMP_FEATURES);
18335            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18336                if (opti >= args.length) {
18337                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18338                            | DumpState.DUMP_SERVICE_RESOLVERS
18339                            | DumpState.DUMP_RECEIVER_RESOLVERS
18340                            | DumpState.DUMP_CONTENT_RESOLVERS);
18341                } else {
18342                    while (opti < args.length) {
18343                        String name = args[opti];
18344                        if ("a".equals(name) || "activity".equals(name)) {
18345                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18346                        } else if ("s".equals(name) || "service".equals(name)) {
18347                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18348                        } else if ("r".equals(name) || "receiver".equals(name)) {
18349                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18350                        } else if ("c".equals(name) || "content".equals(name)) {
18351                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18352                        } else {
18353                            pw.println("Error: unknown resolver table type: " + name);
18354                            return;
18355                        }
18356                        opti++;
18357                    }
18358                }
18359            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18360                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18361            } else if ("permission".equals(cmd)) {
18362                if (opti >= args.length) {
18363                    pw.println("Error: permission requires permission name");
18364                    return;
18365                }
18366                permissionNames = new ArraySet<>();
18367                while (opti < args.length) {
18368                    permissionNames.add(args[opti]);
18369                    opti++;
18370                }
18371                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18372                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18373            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18374                dumpState.setDump(DumpState.DUMP_PREFERRED);
18375            } else if ("preferred-xml".equals(cmd)) {
18376                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18377                if (opti < args.length && "--full".equals(args[opti])) {
18378                    fullPreferred = true;
18379                    opti++;
18380                }
18381            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18382                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18383            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18384                dumpState.setDump(DumpState.DUMP_PACKAGES);
18385            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18386                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18387            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18388                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18389            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18390                dumpState.setDump(DumpState.DUMP_MESSAGES);
18391            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18392                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18393            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18394                    || "intent-filter-verifiers".equals(cmd)) {
18395                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18396            } else if ("version".equals(cmd)) {
18397                dumpState.setDump(DumpState.DUMP_VERSION);
18398            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18399                dumpState.setDump(DumpState.DUMP_KEYSETS);
18400            } else if ("installs".equals(cmd)) {
18401                dumpState.setDump(DumpState.DUMP_INSTALLS);
18402            } else if ("frozen".equals(cmd)) {
18403                dumpState.setDump(DumpState.DUMP_FROZEN);
18404            } else if ("dexopt".equals(cmd)) {
18405                dumpState.setDump(DumpState.DUMP_DEXOPT);
18406            } else if ("compiler-stats".equals(cmd)) {
18407                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18408            } else if ("write".equals(cmd)) {
18409                synchronized (mPackages) {
18410                    mSettings.writeLPr();
18411                    pw.println("Settings written.");
18412                    return;
18413                }
18414            }
18415        }
18416
18417        if (checkin) {
18418            pw.println("vers,1");
18419        }
18420
18421        // reader
18422        synchronized (mPackages) {
18423            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18424                if (!checkin) {
18425                    if (dumpState.onTitlePrinted())
18426                        pw.println();
18427                    pw.println("Database versions:");
18428                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18429                }
18430            }
18431
18432            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18433                if (!checkin) {
18434                    if (dumpState.onTitlePrinted())
18435                        pw.println();
18436                    pw.println("Verifiers:");
18437                    pw.print("  Required: ");
18438                    pw.print(mRequiredVerifierPackage);
18439                    pw.print(" (uid=");
18440                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18441                            UserHandle.USER_SYSTEM));
18442                    pw.println(")");
18443                } else if (mRequiredVerifierPackage != null) {
18444                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18445                    pw.print(",");
18446                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18447                            UserHandle.USER_SYSTEM));
18448                }
18449            }
18450
18451            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18452                    packageName == null) {
18453                if (mIntentFilterVerifierComponent != null) {
18454                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18455                    if (!checkin) {
18456                        if (dumpState.onTitlePrinted())
18457                            pw.println();
18458                        pw.println("Intent Filter Verifier:");
18459                        pw.print("  Using: ");
18460                        pw.print(verifierPackageName);
18461                        pw.print(" (uid=");
18462                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18463                                UserHandle.USER_SYSTEM));
18464                        pw.println(")");
18465                    } else if (verifierPackageName != null) {
18466                        pw.print("ifv,"); pw.print(verifierPackageName);
18467                        pw.print(",");
18468                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18469                                UserHandle.USER_SYSTEM));
18470                    }
18471                } else {
18472                    pw.println();
18473                    pw.println("No Intent Filter Verifier available!");
18474                }
18475            }
18476
18477            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18478                boolean printedHeader = false;
18479                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18480                while (it.hasNext()) {
18481                    String name = it.next();
18482                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18483                    if (!checkin) {
18484                        if (!printedHeader) {
18485                            if (dumpState.onTitlePrinted())
18486                                pw.println();
18487                            pw.println("Libraries:");
18488                            printedHeader = true;
18489                        }
18490                        pw.print("  ");
18491                    } else {
18492                        pw.print("lib,");
18493                    }
18494                    pw.print(name);
18495                    if (!checkin) {
18496                        pw.print(" -> ");
18497                    }
18498                    if (ent.path != null) {
18499                        if (!checkin) {
18500                            pw.print("(jar) ");
18501                            pw.print(ent.path);
18502                        } else {
18503                            pw.print(",jar,");
18504                            pw.print(ent.path);
18505                        }
18506                    } else {
18507                        if (!checkin) {
18508                            pw.print("(apk) ");
18509                            pw.print(ent.apk);
18510                        } else {
18511                            pw.print(",apk,");
18512                            pw.print(ent.apk);
18513                        }
18514                    }
18515                    pw.println();
18516                }
18517            }
18518
18519            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18520                if (dumpState.onTitlePrinted())
18521                    pw.println();
18522                if (!checkin) {
18523                    pw.println("Features:");
18524                }
18525
18526                for (FeatureInfo feat : mAvailableFeatures.values()) {
18527                    if (checkin) {
18528                        pw.print("feat,");
18529                        pw.print(feat.name);
18530                        pw.print(",");
18531                        pw.println(feat.version);
18532                    } else {
18533                        pw.print("  ");
18534                        pw.print(feat.name);
18535                        if (feat.version > 0) {
18536                            pw.print(" version=");
18537                            pw.print(feat.version);
18538                        }
18539                        pw.println();
18540                    }
18541                }
18542            }
18543
18544            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18545                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18546                        : "Activity Resolver Table:", "  ", packageName,
18547                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18548                    dumpState.setTitlePrinted(true);
18549                }
18550            }
18551            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18552                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18553                        : "Receiver Resolver Table:", "  ", packageName,
18554                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18555                    dumpState.setTitlePrinted(true);
18556                }
18557            }
18558            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18559                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18560                        : "Service Resolver Table:", "  ", packageName,
18561                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18562                    dumpState.setTitlePrinted(true);
18563                }
18564            }
18565            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18566                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18567                        : "Provider Resolver Table:", "  ", packageName,
18568                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18569                    dumpState.setTitlePrinted(true);
18570                }
18571            }
18572
18573            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18574                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18575                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18576                    int user = mSettings.mPreferredActivities.keyAt(i);
18577                    if (pir.dump(pw,
18578                            dumpState.getTitlePrinted()
18579                                ? "\nPreferred Activities User " + user + ":"
18580                                : "Preferred Activities User " + user + ":", "  ",
18581                            packageName, true, false)) {
18582                        dumpState.setTitlePrinted(true);
18583                    }
18584                }
18585            }
18586
18587            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18588                pw.flush();
18589                FileOutputStream fout = new FileOutputStream(fd);
18590                BufferedOutputStream str = new BufferedOutputStream(fout);
18591                XmlSerializer serializer = new FastXmlSerializer();
18592                try {
18593                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18594                    serializer.startDocument(null, true);
18595                    serializer.setFeature(
18596                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18597                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18598                    serializer.endDocument();
18599                    serializer.flush();
18600                } catch (IllegalArgumentException e) {
18601                    pw.println("Failed writing: " + e);
18602                } catch (IllegalStateException e) {
18603                    pw.println("Failed writing: " + e);
18604                } catch (IOException e) {
18605                    pw.println("Failed writing: " + e);
18606                }
18607            }
18608
18609            if (!checkin
18610                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18611                    && packageName == null) {
18612                pw.println();
18613                int count = mSettings.mPackages.size();
18614                if (count == 0) {
18615                    pw.println("No applications!");
18616                    pw.println();
18617                } else {
18618                    final String prefix = "  ";
18619                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18620                    if (allPackageSettings.size() == 0) {
18621                        pw.println("No domain preferred apps!");
18622                        pw.println();
18623                    } else {
18624                        pw.println("App verification status:");
18625                        pw.println();
18626                        count = 0;
18627                        for (PackageSetting ps : allPackageSettings) {
18628                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18629                            if (ivi == null || ivi.getPackageName() == null) continue;
18630                            pw.println(prefix + "Package: " + ivi.getPackageName());
18631                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18632                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18633                            pw.println();
18634                            count++;
18635                        }
18636                        if (count == 0) {
18637                            pw.println(prefix + "No app verification established.");
18638                            pw.println();
18639                        }
18640                        for (int userId : sUserManager.getUserIds()) {
18641                            pw.println("App linkages for user " + userId + ":");
18642                            pw.println();
18643                            count = 0;
18644                            for (PackageSetting ps : allPackageSettings) {
18645                                final long status = ps.getDomainVerificationStatusForUser(userId);
18646                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18647                                    continue;
18648                                }
18649                                pw.println(prefix + "Package: " + ps.name);
18650                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18651                                String statusStr = IntentFilterVerificationInfo.
18652                                        getStatusStringFromValue(status);
18653                                pw.println(prefix + "Status:  " + statusStr);
18654                                pw.println();
18655                                count++;
18656                            }
18657                            if (count == 0) {
18658                                pw.println(prefix + "No configured app linkages.");
18659                                pw.println();
18660                            }
18661                        }
18662                    }
18663                }
18664            }
18665
18666            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18667                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18668                if (packageName == null && permissionNames == null) {
18669                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18670                        if (iperm == 0) {
18671                            if (dumpState.onTitlePrinted())
18672                                pw.println();
18673                            pw.println("AppOp Permissions:");
18674                        }
18675                        pw.print("  AppOp Permission ");
18676                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18677                        pw.println(":");
18678                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18679                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18680                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18681                        }
18682                    }
18683                }
18684            }
18685
18686            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18687                boolean printedSomething = false;
18688                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18689                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18690                        continue;
18691                    }
18692                    if (!printedSomething) {
18693                        if (dumpState.onTitlePrinted())
18694                            pw.println();
18695                        pw.println("Registered ContentProviders:");
18696                        printedSomething = true;
18697                    }
18698                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18699                    pw.print("    "); pw.println(p.toString());
18700                }
18701                printedSomething = false;
18702                for (Map.Entry<String, PackageParser.Provider> entry :
18703                        mProvidersByAuthority.entrySet()) {
18704                    PackageParser.Provider p = entry.getValue();
18705                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18706                        continue;
18707                    }
18708                    if (!printedSomething) {
18709                        if (dumpState.onTitlePrinted())
18710                            pw.println();
18711                        pw.println("ContentProvider Authorities:");
18712                        printedSomething = true;
18713                    }
18714                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18715                    pw.print("    "); pw.println(p.toString());
18716                    if (p.info != null && p.info.applicationInfo != null) {
18717                        final String appInfo = p.info.applicationInfo.toString();
18718                        pw.print("      applicationInfo="); pw.println(appInfo);
18719                    }
18720                }
18721            }
18722
18723            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18724                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18725            }
18726
18727            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18728                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18729            }
18730
18731            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18732                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18733            }
18734
18735            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18736                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18737            }
18738
18739            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18740                // XXX should handle packageName != null by dumping only install data that
18741                // the given package is involved with.
18742                if (dumpState.onTitlePrinted()) pw.println();
18743                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18744            }
18745
18746            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18747                // XXX should handle packageName != null by dumping only install data that
18748                // the given package is involved with.
18749                if (dumpState.onTitlePrinted()) pw.println();
18750
18751                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18752                ipw.println();
18753                ipw.println("Frozen packages:");
18754                ipw.increaseIndent();
18755                if (mFrozenPackages.size() == 0) {
18756                    ipw.println("(none)");
18757                } else {
18758                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18759                        ipw.println(mFrozenPackages.valueAt(i));
18760                    }
18761                }
18762                ipw.decreaseIndent();
18763            }
18764
18765            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18766                if (dumpState.onTitlePrinted()) pw.println();
18767                dumpDexoptStateLPr(pw, packageName);
18768            }
18769
18770            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18771                if (dumpState.onTitlePrinted()) pw.println();
18772                dumpCompilerStatsLPr(pw, packageName);
18773            }
18774
18775            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18776                if (dumpState.onTitlePrinted()) pw.println();
18777                mSettings.dumpReadMessagesLPr(pw, dumpState);
18778
18779                pw.println();
18780                pw.println("Package warning messages:");
18781                BufferedReader in = null;
18782                String line = null;
18783                try {
18784                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18785                    while ((line = in.readLine()) != null) {
18786                        if (line.contains("ignored: updated version")) continue;
18787                        pw.println(line);
18788                    }
18789                } catch (IOException ignored) {
18790                } finally {
18791                    IoUtils.closeQuietly(in);
18792                }
18793            }
18794
18795            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18796                BufferedReader in = null;
18797                String line = null;
18798                try {
18799                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18800                    while ((line = in.readLine()) != null) {
18801                        if (line.contains("ignored: updated version")) continue;
18802                        pw.print("msg,");
18803                        pw.println(line);
18804                    }
18805                } catch (IOException ignored) {
18806                } finally {
18807                    IoUtils.closeQuietly(in);
18808                }
18809            }
18810        }
18811    }
18812
18813    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18814        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18815        ipw.println();
18816        ipw.println("Dexopt state:");
18817        ipw.increaseIndent();
18818        Collection<PackageParser.Package> packages = null;
18819        if (packageName != null) {
18820            PackageParser.Package targetPackage = mPackages.get(packageName);
18821            if (targetPackage != null) {
18822                packages = Collections.singletonList(targetPackage);
18823            } else {
18824                ipw.println("Unable to find package: " + packageName);
18825                return;
18826            }
18827        } else {
18828            packages = mPackages.values();
18829        }
18830
18831        for (PackageParser.Package pkg : packages) {
18832            ipw.println("[" + pkg.packageName + "]");
18833            ipw.increaseIndent();
18834            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18835            ipw.decreaseIndent();
18836        }
18837    }
18838
18839    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
18840        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18841        ipw.println();
18842        ipw.println("Compiler stats:");
18843        ipw.increaseIndent();
18844        Collection<PackageParser.Package> packages = null;
18845        if (packageName != null) {
18846            PackageParser.Package targetPackage = mPackages.get(packageName);
18847            if (targetPackage != null) {
18848                packages = Collections.singletonList(targetPackage);
18849            } else {
18850                ipw.println("Unable to find package: " + packageName);
18851                return;
18852            }
18853        } else {
18854            packages = mPackages.values();
18855        }
18856
18857        for (PackageParser.Package pkg : packages) {
18858            ipw.println("[" + pkg.packageName + "]");
18859            ipw.increaseIndent();
18860
18861            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
18862            if (stats == null) {
18863                ipw.println("(No recorded stats)");
18864            } else {
18865                stats.dump(ipw);
18866            }
18867            ipw.decreaseIndent();
18868        }
18869    }
18870
18871    private String dumpDomainString(String packageName) {
18872        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18873                .getList();
18874        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18875
18876        ArraySet<String> result = new ArraySet<>();
18877        if (iviList.size() > 0) {
18878            for (IntentFilterVerificationInfo ivi : iviList) {
18879                for (String host : ivi.getDomains()) {
18880                    result.add(host);
18881                }
18882            }
18883        }
18884        if (filters != null && filters.size() > 0) {
18885            for (IntentFilter filter : filters) {
18886                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18887                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18888                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18889                    result.addAll(filter.getHostsList());
18890                }
18891            }
18892        }
18893
18894        StringBuilder sb = new StringBuilder(result.size() * 16);
18895        for (String domain : result) {
18896            if (sb.length() > 0) sb.append(" ");
18897            sb.append(domain);
18898        }
18899        return sb.toString();
18900    }
18901
18902    // ------- apps on sdcard specific code -------
18903    static final boolean DEBUG_SD_INSTALL = false;
18904
18905    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18906
18907    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18908
18909    private boolean mMediaMounted = false;
18910
18911    static String getEncryptKey() {
18912        try {
18913            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18914                    SD_ENCRYPTION_KEYSTORE_NAME);
18915            if (sdEncKey == null) {
18916                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18917                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18918                if (sdEncKey == null) {
18919                    Slog.e(TAG, "Failed to create encryption keys");
18920                    return null;
18921                }
18922            }
18923            return sdEncKey;
18924        } catch (NoSuchAlgorithmException nsae) {
18925            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18926            return null;
18927        } catch (IOException ioe) {
18928            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18929            return null;
18930        }
18931    }
18932
18933    /*
18934     * Update media status on PackageManager.
18935     */
18936    @Override
18937    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18938        int callingUid = Binder.getCallingUid();
18939        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18940            throw new SecurityException("Media status can only be updated by the system");
18941        }
18942        // reader; this apparently protects mMediaMounted, but should probably
18943        // be a different lock in that case.
18944        synchronized (mPackages) {
18945            Log.i(TAG, "Updating external media status from "
18946                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18947                    + (mediaStatus ? "mounted" : "unmounted"));
18948            if (DEBUG_SD_INSTALL)
18949                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18950                        + ", mMediaMounted=" + mMediaMounted);
18951            if (mediaStatus == mMediaMounted) {
18952                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18953                        : 0, -1);
18954                mHandler.sendMessage(msg);
18955                return;
18956            }
18957            mMediaMounted = mediaStatus;
18958        }
18959        // Queue up an async operation since the package installation may take a
18960        // little while.
18961        mHandler.post(new Runnable() {
18962            public void run() {
18963                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18964            }
18965        });
18966    }
18967
18968    /**
18969     * Called by MountService when the initial ASECs to scan are available.
18970     * Should block until all the ASEC containers are finished being scanned.
18971     */
18972    public void scanAvailableAsecs() {
18973        updateExternalMediaStatusInner(true, false, false);
18974    }
18975
18976    /*
18977     * Collect information of applications on external media, map them against
18978     * existing containers and update information based on current mount status.
18979     * Please note that we always have to report status if reportStatus has been
18980     * set to true especially when unloading packages.
18981     */
18982    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18983            boolean externalStorage) {
18984        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18985        int[] uidArr = EmptyArray.INT;
18986
18987        final String[] list = PackageHelper.getSecureContainerList();
18988        if (ArrayUtils.isEmpty(list)) {
18989            Log.i(TAG, "No secure containers found");
18990        } else {
18991            // Process list of secure containers and categorize them
18992            // as active or stale based on their package internal state.
18993
18994            // reader
18995            synchronized (mPackages) {
18996                for (String cid : list) {
18997                    // Leave stages untouched for now; installer service owns them
18998                    if (PackageInstallerService.isStageName(cid)) continue;
18999
19000                    if (DEBUG_SD_INSTALL)
19001                        Log.i(TAG, "Processing container " + cid);
19002                    String pkgName = getAsecPackageName(cid);
19003                    if (pkgName == null) {
19004                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19005                        continue;
19006                    }
19007                    if (DEBUG_SD_INSTALL)
19008                        Log.i(TAG, "Looking for pkg : " + pkgName);
19009
19010                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19011                    if (ps == null) {
19012                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19013                        continue;
19014                    }
19015
19016                    /*
19017                     * Skip packages that are not external if we're unmounting
19018                     * external storage.
19019                     */
19020                    if (externalStorage && !isMounted && !isExternal(ps)) {
19021                        continue;
19022                    }
19023
19024                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19025                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19026                    // The package status is changed only if the code path
19027                    // matches between settings and the container id.
19028                    if (ps.codePathString != null
19029                            && ps.codePathString.startsWith(args.getCodePath())) {
19030                        if (DEBUG_SD_INSTALL) {
19031                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19032                                    + " at code path: " + ps.codePathString);
19033                        }
19034
19035                        // We do have a valid package installed on sdcard
19036                        processCids.put(args, ps.codePathString);
19037                        final int uid = ps.appId;
19038                        if (uid != -1) {
19039                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19040                        }
19041                    } else {
19042                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19043                                + ps.codePathString);
19044                    }
19045                }
19046            }
19047
19048            Arrays.sort(uidArr);
19049        }
19050
19051        // Process packages with valid entries.
19052        if (isMounted) {
19053            if (DEBUG_SD_INSTALL)
19054                Log.i(TAG, "Loading packages");
19055            loadMediaPackages(processCids, uidArr, externalStorage);
19056            startCleaningPackages();
19057            mInstallerService.onSecureContainersAvailable();
19058        } else {
19059            if (DEBUG_SD_INSTALL)
19060                Log.i(TAG, "Unloading packages");
19061            unloadMediaPackages(processCids, uidArr, reportStatus);
19062        }
19063    }
19064
19065    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19066            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19067        final int size = infos.size();
19068        final String[] packageNames = new String[size];
19069        final int[] packageUids = new int[size];
19070        for (int i = 0; i < size; i++) {
19071            final ApplicationInfo info = infos.get(i);
19072            packageNames[i] = info.packageName;
19073            packageUids[i] = info.uid;
19074        }
19075        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19076                finishedReceiver);
19077    }
19078
19079    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19080            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19081        sendResourcesChangedBroadcast(mediaStatus, replacing,
19082                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19083    }
19084
19085    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19086            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19087        int size = pkgList.length;
19088        if (size > 0) {
19089            // Send broadcasts here
19090            Bundle extras = new Bundle();
19091            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19092            if (uidArr != null) {
19093                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19094            }
19095            if (replacing) {
19096                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19097            }
19098            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19099                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19100            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19101        }
19102    }
19103
19104   /*
19105     * Look at potentially valid container ids from processCids If package
19106     * information doesn't match the one on record or package scanning fails,
19107     * the cid is added to list of removeCids. We currently don't delete stale
19108     * containers.
19109     */
19110    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19111            boolean externalStorage) {
19112        ArrayList<String> pkgList = new ArrayList<String>();
19113        Set<AsecInstallArgs> keys = processCids.keySet();
19114
19115        for (AsecInstallArgs args : keys) {
19116            String codePath = processCids.get(args);
19117            if (DEBUG_SD_INSTALL)
19118                Log.i(TAG, "Loading container : " + args.cid);
19119            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19120            try {
19121                // Make sure there are no container errors first.
19122                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19123                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19124                            + " when installing from sdcard");
19125                    continue;
19126                }
19127                // Check code path here.
19128                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19129                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19130                            + " does not match one in settings " + codePath);
19131                    continue;
19132                }
19133                // Parse package
19134                int parseFlags = mDefParseFlags;
19135                if (args.isExternalAsec()) {
19136                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19137                }
19138                if (args.isFwdLocked()) {
19139                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19140                }
19141
19142                synchronized (mInstallLock) {
19143                    PackageParser.Package pkg = null;
19144                    try {
19145                        // Sadly we don't know the package name yet to freeze it
19146                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19147                                SCAN_IGNORE_FROZEN, 0, null);
19148                    } catch (PackageManagerException e) {
19149                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19150                    }
19151                    // Scan the package
19152                    if (pkg != null) {
19153                        /*
19154                         * TODO why is the lock being held? doPostInstall is
19155                         * called in other places without the lock. This needs
19156                         * to be straightened out.
19157                         */
19158                        // writer
19159                        synchronized (mPackages) {
19160                            retCode = PackageManager.INSTALL_SUCCEEDED;
19161                            pkgList.add(pkg.packageName);
19162                            // Post process args
19163                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19164                                    pkg.applicationInfo.uid);
19165                        }
19166                    } else {
19167                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19168                    }
19169                }
19170
19171            } finally {
19172                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19173                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19174                }
19175            }
19176        }
19177        // writer
19178        synchronized (mPackages) {
19179            // If the platform SDK has changed since the last time we booted,
19180            // we need to re-grant app permission to catch any new ones that
19181            // appear. This is really a hack, and means that apps can in some
19182            // cases get permissions that the user didn't initially explicitly
19183            // allow... it would be nice to have some better way to handle
19184            // this situation.
19185            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19186                    : mSettings.getInternalVersion();
19187            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19188                    : StorageManager.UUID_PRIVATE_INTERNAL;
19189
19190            int updateFlags = UPDATE_PERMISSIONS_ALL;
19191            if (ver.sdkVersion != mSdkVersion) {
19192                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19193                        + mSdkVersion + "; regranting permissions for external");
19194                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19195            }
19196            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19197
19198            // Yay, everything is now upgraded
19199            ver.forceCurrent();
19200
19201            // can downgrade to reader
19202            // Persist settings
19203            mSettings.writeLPr();
19204        }
19205        // Send a broadcast to let everyone know we are done processing
19206        if (pkgList.size() > 0) {
19207            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19208        }
19209    }
19210
19211   /*
19212     * Utility method to unload a list of specified containers
19213     */
19214    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19215        // Just unmount all valid containers.
19216        for (AsecInstallArgs arg : cidArgs) {
19217            synchronized (mInstallLock) {
19218                arg.doPostDeleteLI(false);
19219           }
19220       }
19221   }
19222
19223    /*
19224     * Unload packages mounted on external media. This involves deleting package
19225     * data from internal structures, sending broadcasts about disabled packages,
19226     * gc'ing to free up references, unmounting all secure containers
19227     * corresponding to packages on external media, and posting a
19228     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19229     * that we always have to post this message if status has been requested no
19230     * matter what.
19231     */
19232    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19233            final boolean reportStatus) {
19234        if (DEBUG_SD_INSTALL)
19235            Log.i(TAG, "unloading media packages");
19236        ArrayList<String> pkgList = new ArrayList<String>();
19237        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19238        final Set<AsecInstallArgs> keys = processCids.keySet();
19239        for (AsecInstallArgs args : keys) {
19240            String pkgName = args.getPackageName();
19241            if (DEBUG_SD_INSTALL)
19242                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19243            // Delete package internally
19244            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19245            synchronized (mInstallLock) {
19246                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19247                final boolean res;
19248                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19249                        "unloadMediaPackages")) {
19250                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19251                            null);
19252                }
19253                if (res) {
19254                    pkgList.add(pkgName);
19255                } else {
19256                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19257                    failedList.add(args);
19258                }
19259            }
19260        }
19261
19262        // reader
19263        synchronized (mPackages) {
19264            // We didn't update the settings after removing each package;
19265            // write them now for all packages.
19266            mSettings.writeLPr();
19267        }
19268
19269        // We have to absolutely send UPDATED_MEDIA_STATUS only
19270        // after confirming that all the receivers processed the ordered
19271        // broadcast when packages get disabled, force a gc to clean things up.
19272        // and unload all the containers.
19273        if (pkgList.size() > 0) {
19274            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19275                    new IIntentReceiver.Stub() {
19276                public void performReceive(Intent intent, int resultCode, String data,
19277                        Bundle extras, boolean ordered, boolean sticky,
19278                        int sendingUser) throws RemoteException {
19279                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19280                            reportStatus ? 1 : 0, 1, keys);
19281                    mHandler.sendMessage(msg);
19282                }
19283            });
19284        } else {
19285            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19286                    keys);
19287            mHandler.sendMessage(msg);
19288        }
19289    }
19290
19291    private void loadPrivatePackages(final VolumeInfo vol) {
19292        mHandler.post(new Runnable() {
19293            @Override
19294            public void run() {
19295                loadPrivatePackagesInner(vol);
19296            }
19297        });
19298    }
19299
19300    private void loadPrivatePackagesInner(VolumeInfo vol) {
19301        final String volumeUuid = vol.fsUuid;
19302        if (TextUtils.isEmpty(volumeUuid)) {
19303            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19304            return;
19305        }
19306
19307        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19308        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19309        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19310
19311        final VersionInfo ver;
19312        final List<PackageSetting> packages;
19313        synchronized (mPackages) {
19314            ver = mSettings.findOrCreateVersion(volumeUuid);
19315            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19316        }
19317
19318        for (PackageSetting ps : packages) {
19319            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19320            synchronized (mInstallLock) {
19321                final PackageParser.Package pkg;
19322                try {
19323                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19324                    loaded.add(pkg.applicationInfo);
19325
19326                } catch (PackageManagerException e) {
19327                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19328                }
19329
19330                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19331                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19332                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19333                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19334                }
19335            }
19336        }
19337
19338        // Reconcile app data for all started/unlocked users
19339        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19340        final UserManager um = mContext.getSystemService(UserManager.class);
19341        UserManagerInternal umInternal = getUserManagerInternal();
19342        for (UserInfo user : um.getUsers()) {
19343            final int flags;
19344            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19345                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19346            } else if (umInternal.isUserRunning(user.id)) {
19347                flags = StorageManager.FLAG_STORAGE_DE;
19348            } else {
19349                continue;
19350            }
19351
19352            try {
19353                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19354                synchronized (mInstallLock) {
19355                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19356                }
19357            } catch (IllegalStateException e) {
19358                // Device was probably ejected, and we'll process that event momentarily
19359                Slog.w(TAG, "Failed to prepare storage: " + e);
19360            }
19361        }
19362
19363        synchronized (mPackages) {
19364            int updateFlags = UPDATE_PERMISSIONS_ALL;
19365            if (ver.sdkVersion != mSdkVersion) {
19366                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19367                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19368                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19369            }
19370            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19371
19372            // Yay, everything is now upgraded
19373            ver.forceCurrent();
19374
19375            mSettings.writeLPr();
19376        }
19377
19378        for (PackageFreezer freezer : freezers) {
19379            freezer.close();
19380        }
19381
19382        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19383        sendResourcesChangedBroadcast(true, false, loaded, null);
19384    }
19385
19386    private void unloadPrivatePackages(final VolumeInfo vol) {
19387        mHandler.post(new Runnable() {
19388            @Override
19389            public void run() {
19390                unloadPrivatePackagesInner(vol);
19391            }
19392        });
19393    }
19394
19395    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19396        final String volumeUuid = vol.fsUuid;
19397        if (TextUtils.isEmpty(volumeUuid)) {
19398            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19399            return;
19400        }
19401
19402        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19403        synchronized (mInstallLock) {
19404        synchronized (mPackages) {
19405            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19406            for (PackageSetting ps : packages) {
19407                if (ps.pkg == null) continue;
19408
19409                final ApplicationInfo info = ps.pkg.applicationInfo;
19410                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19411                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19412
19413                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19414                        "unloadPrivatePackagesInner")) {
19415                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19416                            false, null)) {
19417                        unloaded.add(info);
19418                    } else {
19419                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19420                    }
19421                }
19422
19423                // Try very hard to release any references to this package
19424                // so we don't risk the system server being killed due to
19425                // open FDs
19426                AttributeCache.instance().removePackage(ps.name);
19427            }
19428
19429            mSettings.writeLPr();
19430        }
19431        }
19432
19433        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19434        sendResourcesChangedBroadcast(false, false, unloaded, null);
19435
19436        // Try very hard to release any references to this path so we don't risk
19437        // the system server being killed due to open FDs
19438        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19439
19440        for (int i = 0; i < 3; i++) {
19441            System.gc();
19442            System.runFinalization();
19443        }
19444    }
19445
19446    /**
19447     * Prepare storage areas for given user on all mounted devices.
19448     */
19449    void prepareUserData(int userId, int userSerial, int flags) {
19450        synchronized (mInstallLock) {
19451            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19452            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19453                final String volumeUuid = vol.getFsUuid();
19454                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19455            }
19456        }
19457    }
19458
19459    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19460            boolean allowRecover) {
19461        // Prepare storage and verify that serial numbers are consistent; if
19462        // there's a mismatch we need to destroy to avoid leaking data
19463        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19464        try {
19465            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19466
19467            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19468                UserManagerService.enforceSerialNumber(
19469                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19470                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19471                    UserManagerService.enforceSerialNumber(
19472                            Environment.getDataSystemDeDirectory(userId), userSerial);
19473                }
19474            }
19475            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19476                UserManagerService.enforceSerialNumber(
19477                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19478                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19479                    UserManagerService.enforceSerialNumber(
19480                            Environment.getDataSystemCeDirectory(userId), userSerial);
19481                }
19482            }
19483
19484            synchronized (mInstallLock) {
19485                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19486            }
19487        } catch (Exception e) {
19488            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19489                    + " because we failed to prepare: " + e);
19490            destroyUserDataLI(volumeUuid, userId,
19491                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19492
19493            if (allowRecover) {
19494                // Try one last time; if we fail again we're really in trouble
19495                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19496            }
19497        }
19498    }
19499
19500    /**
19501     * Destroy storage areas for given user on all mounted devices.
19502     */
19503    void destroyUserData(int userId, int flags) {
19504        synchronized (mInstallLock) {
19505            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19506            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19507                final String volumeUuid = vol.getFsUuid();
19508                destroyUserDataLI(volumeUuid, userId, flags);
19509            }
19510        }
19511    }
19512
19513    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19514        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19515        try {
19516            // Clean up app data, profile data, and media data
19517            mInstaller.destroyUserData(volumeUuid, userId, flags);
19518
19519            // Clean up system data
19520            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19521                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19522                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19523                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19524                }
19525                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19526                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19527                }
19528            }
19529
19530            // Data with special labels is now gone, so finish the job
19531            storage.destroyUserStorage(volumeUuid, userId, flags);
19532
19533        } catch (Exception e) {
19534            logCriticalInfo(Log.WARN,
19535                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19536        }
19537    }
19538
19539    /**
19540     * Examine all users present on given mounted volume, and destroy data
19541     * belonging to users that are no longer valid, or whose user ID has been
19542     * recycled.
19543     */
19544    private void reconcileUsers(String volumeUuid) {
19545        final List<File> files = new ArrayList<>();
19546        Collections.addAll(files, FileUtils
19547                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19548        Collections.addAll(files, FileUtils
19549                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19550        Collections.addAll(files, FileUtils
19551                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19552        Collections.addAll(files, FileUtils
19553                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19554        for (File file : files) {
19555            if (!file.isDirectory()) continue;
19556
19557            final int userId;
19558            final UserInfo info;
19559            try {
19560                userId = Integer.parseInt(file.getName());
19561                info = sUserManager.getUserInfo(userId);
19562            } catch (NumberFormatException e) {
19563                Slog.w(TAG, "Invalid user directory " + file);
19564                continue;
19565            }
19566
19567            boolean destroyUser = false;
19568            if (info == null) {
19569                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19570                        + " because no matching user was found");
19571                destroyUser = true;
19572            } else if (!mOnlyCore) {
19573                try {
19574                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19575                } catch (IOException e) {
19576                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19577                            + " because we failed to enforce serial number: " + e);
19578                    destroyUser = true;
19579                }
19580            }
19581
19582            if (destroyUser) {
19583                synchronized (mInstallLock) {
19584                    destroyUserDataLI(volumeUuid, userId,
19585                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19586                }
19587            }
19588        }
19589    }
19590
19591    private void assertPackageKnown(String volumeUuid, String packageName)
19592            throws PackageManagerException {
19593        synchronized (mPackages) {
19594            final PackageSetting ps = mSettings.mPackages.get(packageName);
19595            if (ps == null) {
19596                throw new PackageManagerException("Package " + packageName + " is unknown");
19597            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19598                throw new PackageManagerException(
19599                        "Package " + packageName + " found on unknown volume " + volumeUuid
19600                                + "; expected volume " + ps.volumeUuid);
19601            }
19602        }
19603    }
19604
19605    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19606            throws PackageManagerException {
19607        synchronized (mPackages) {
19608            final PackageSetting ps = mSettings.mPackages.get(packageName);
19609            if (ps == null) {
19610                throw new PackageManagerException("Package " + packageName + " is unknown");
19611            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19612                throw new PackageManagerException(
19613                        "Package " + packageName + " found on unknown volume " + volumeUuid
19614                                + "; expected volume " + ps.volumeUuid);
19615            } else if (!ps.getInstalled(userId)) {
19616                throw new PackageManagerException(
19617                        "Package " + packageName + " not installed for user " + userId);
19618            }
19619        }
19620    }
19621
19622    /**
19623     * Examine all apps present on given mounted volume, and destroy apps that
19624     * aren't expected, either due to uninstallation or reinstallation on
19625     * another volume.
19626     */
19627    private void reconcileApps(String volumeUuid) {
19628        final File[] files = FileUtils
19629                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19630        for (File file : files) {
19631            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19632                    && !PackageInstallerService.isStageName(file.getName());
19633            if (!isPackage) {
19634                // Ignore entries which are not packages
19635                continue;
19636            }
19637
19638            try {
19639                final PackageLite pkg = PackageParser.parsePackageLite(file,
19640                        PackageParser.PARSE_MUST_BE_APK);
19641                assertPackageKnown(volumeUuid, pkg.packageName);
19642
19643            } catch (PackageParserException | PackageManagerException e) {
19644                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19645                synchronized (mInstallLock) {
19646                    removeCodePathLI(file);
19647                }
19648            }
19649        }
19650    }
19651
19652    /**
19653     * Reconcile all app data for the given user.
19654     * <p>
19655     * Verifies that directories exist and that ownership and labeling is
19656     * correct for all installed apps on all mounted volumes.
19657     */
19658    void reconcileAppsData(int userId, int flags) {
19659        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19660        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19661            final String volumeUuid = vol.getFsUuid();
19662            synchronized (mInstallLock) {
19663                reconcileAppsDataLI(volumeUuid, userId, flags);
19664            }
19665        }
19666    }
19667
19668    /**
19669     * Reconcile all app data on given mounted volume.
19670     * <p>
19671     * Destroys app data that isn't expected, either due to uninstallation or
19672     * reinstallation on another volume.
19673     * <p>
19674     * Verifies that directories exist and that ownership and labeling is
19675     * correct for all installed apps.
19676     */
19677    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19678        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19679                + Integer.toHexString(flags));
19680
19681        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19682        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19683
19684        boolean restoreconNeeded = false;
19685
19686        // First look for stale data that doesn't belong, and check if things
19687        // have changed since we did our last restorecon
19688        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19689            if (StorageManager.isFileEncryptedNativeOrEmulated()
19690                    && !StorageManager.isUserKeyUnlocked(userId)) {
19691                throw new RuntimeException(
19692                        "Yikes, someone asked us to reconcile CE storage while " + userId
19693                                + " was still locked; this would have caused massive data loss!");
19694            }
19695
19696            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19697
19698            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19699            for (File file : files) {
19700                final String packageName = file.getName();
19701                try {
19702                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19703                } catch (PackageManagerException e) {
19704                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19705                    try {
19706                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19707                                StorageManager.FLAG_STORAGE_CE, 0);
19708                    } catch (InstallerException e2) {
19709                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19710                    }
19711                }
19712            }
19713        }
19714        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19715            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19716
19717            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19718            for (File file : files) {
19719                final String packageName = file.getName();
19720                try {
19721                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19722                } catch (PackageManagerException e) {
19723                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19724                    try {
19725                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19726                                StorageManager.FLAG_STORAGE_DE, 0);
19727                    } catch (InstallerException e2) {
19728                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19729                    }
19730                }
19731            }
19732        }
19733
19734        // Ensure that data directories are ready to roll for all packages
19735        // installed for this volume and user
19736        final List<PackageSetting> packages;
19737        synchronized (mPackages) {
19738            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19739        }
19740        int preparedCount = 0;
19741        for (PackageSetting ps : packages) {
19742            final String packageName = ps.name;
19743            if (ps.pkg == null) {
19744                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19745                // TODO: might be due to legacy ASEC apps; we should circle back
19746                // and reconcile again once they're scanned
19747                continue;
19748            }
19749
19750            if (ps.getInstalled(userId)) {
19751                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19752
19753                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19754                    // We may have just shuffled around app data directories, so
19755                    // prepare them one more time
19756                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19757                }
19758
19759                preparedCount++;
19760            }
19761        }
19762
19763        if (restoreconNeeded) {
19764            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19765                SELinuxMMAC.setRestoreconDone(ceDir);
19766            }
19767            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19768                SELinuxMMAC.setRestoreconDone(deDir);
19769            }
19770        }
19771
19772        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19773                + " packages; restoreconNeeded was " + restoreconNeeded);
19774    }
19775
19776    /**
19777     * Prepare app data for the given app just after it was installed or
19778     * upgraded. This method carefully only touches users that it's installed
19779     * for, and it forces a restorecon to handle any seinfo changes.
19780     * <p>
19781     * Verifies that directories exist and that ownership and labeling is
19782     * correct for all installed apps. If there is an ownership mismatch, it
19783     * will try recovering system apps by wiping data; third-party app data is
19784     * left intact.
19785     * <p>
19786     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19787     */
19788    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19789        final PackageSetting ps;
19790        synchronized (mPackages) {
19791            ps = mSettings.mPackages.get(pkg.packageName);
19792            mSettings.writeKernelMappingLPr(ps);
19793        }
19794
19795        final UserManager um = mContext.getSystemService(UserManager.class);
19796        UserManagerInternal umInternal = getUserManagerInternal();
19797        for (UserInfo user : um.getUsers()) {
19798            final int flags;
19799            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19800                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19801            } else if (umInternal.isUserRunning(user.id)) {
19802                flags = StorageManager.FLAG_STORAGE_DE;
19803            } else {
19804                continue;
19805            }
19806
19807            if (ps.getInstalled(user.id)) {
19808                // Whenever an app changes, force a restorecon of its data
19809                // TODO: when user data is locked, mark that we're still dirty
19810                prepareAppDataLIF(pkg, user.id, flags, true);
19811            }
19812        }
19813    }
19814
19815    /**
19816     * Prepare app data for the given app.
19817     * <p>
19818     * Verifies that directories exist and that ownership and labeling is
19819     * correct for all installed apps. If there is an ownership mismatch, this
19820     * will try recovering system apps by wiping data; third-party app data is
19821     * left intact.
19822     */
19823    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19824            boolean restoreconNeeded) {
19825        if (pkg == null) {
19826            Slog.wtf(TAG, "Package was null!", new Throwable());
19827            return;
19828        }
19829        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19830        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19831        for (int i = 0; i < childCount; i++) {
19832            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19833        }
19834    }
19835
19836    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19837            boolean restoreconNeeded) {
19838        if (DEBUG_APP_DATA) {
19839            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19840                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19841        }
19842
19843        final String volumeUuid = pkg.volumeUuid;
19844        final String packageName = pkg.packageName;
19845        final ApplicationInfo app = pkg.applicationInfo;
19846        final int appId = UserHandle.getAppId(app.uid);
19847
19848        Preconditions.checkNotNull(app.seinfo);
19849
19850        try {
19851            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19852                    appId, app.seinfo, app.targetSdkVersion);
19853        } catch (InstallerException e) {
19854            if (app.isSystemApp()) {
19855                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19856                        + ", but trying to recover: " + e);
19857                destroyAppDataLeafLIF(pkg, userId, flags);
19858                try {
19859                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19860                            appId, app.seinfo, app.targetSdkVersion);
19861                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19862                } catch (InstallerException e2) {
19863                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19864                }
19865            } else {
19866                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19867            }
19868        }
19869
19870        if (restoreconNeeded) {
19871            try {
19872                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19873                        app.seinfo);
19874            } catch (InstallerException e) {
19875                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19876            }
19877        }
19878
19879        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19880            try {
19881                // CE storage is unlocked right now, so read out the inode and
19882                // remember for use later when it's locked
19883                // TODO: mark this structure as dirty so we persist it!
19884                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19885                        StorageManager.FLAG_STORAGE_CE);
19886                synchronized (mPackages) {
19887                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19888                    if (ps != null) {
19889                        ps.setCeDataInode(ceDataInode, userId);
19890                    }
19891                }
19892            } catch (InstallerException e) {
19893                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19894            }
19895        }
19896
19897        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19898    }
19899
19900    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19901        if (pkg == null) {
19902            Slog.wtf(TAG, "Package was null!", new Throwable());
19903            return;
19904        }
19905        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19906        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19907        for (int i = 0; i < childCount; i++) {
19908            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19909        }
19910    }
19911
19912    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19913        final String volumeUuid = pkg.volumeUuid;
19914        final String packageName = pkg.packageName;
19915        final ApplicationInfo app = pkg.applicationInfo;
19916
19917        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19918            // Create a native library symlink only if we have native libraries
19919            // and if the native libraries are 32 bit libraries. We do not provide
19920            // this symlink for 64 bit libraries.
19921            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19922                final String nativeLibPath = app.nativeLibraryDir;
19923                try {
19924                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19925                            nativeLibPath, userId);
19926                } catch (InstallerException e) {
19927                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19928                }
19929            }
19930        }
19931    }
19932
19933    /**
19934     * For system apps on non-FBE devices, this method migrates any existing
19935     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19936     * requested by the app.
19937     */
19938    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19939        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19940                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19941            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19942                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19943            try {
19944                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19945                        storageTarget);
19946            } catch (InstallerException e) {
19947                logCriticalInfo(Log.WARN,
19948                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19949            }
19950            return true;
19951        } else {
19952            return false;
19953        }
19954    }
19955
19956    public PackageFreezer freezePackage(String packageName, String killReason) {
19957        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
19958    }
19959
19960    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
19961        return new PackageFreezer(packageName, userId, killReason);
19962    }
19963
19964    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19965            String killReason) {
19966        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
19967    }
19968
19969    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
19970            String killReason) {
19971        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19972            return new PackageFreezer();
19973        } else {
19974            return freezePackage(packageName, userId, killReason);
19975        }
19976    }
19977
19978    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19979            String killReason) {
19980        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
19981    }
19982
19983    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
19984            String killReason) {
19985        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19986            return new PackageFreezer();
19987        } else {
19988            return freezePackage(packageName, userId, killReason);
19989        }
19990    }
19991
19992    /**
19993     * Class that freezes and kills the given package upon creation, and
19994     * unfreezes it upon closing. This is typically used when doing surgery on
19995     * app code/data to prevent the app from running while you're working.
19996     */
19997    private class PackageFreezer implements AutoCloseable {
19998        private final String mPackageName;
19999        private final PackageFreezer[] mChildren;
20000
20001        private final boolean mWeFroze;
20002
20003        private final AtomicBoolean mClosed = new AtomicBoolean();
20004        private final CloseGuard mCloseGuard = CloseGuard.get();
20005
20006        /**
20007         * Create and return a stub freezer that doesn't actually do anything,
20008         * typically used when someone requested
20009         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20010         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20011         */
20012        public PackageFreezer() {
20013            mPackageName = null;
20014            mChildren = null;
20015            mWeFroze = false;
20016            mCloseGuard.open("close");
20017        }
20018
20019        public PackageFreezer(String packageName, int userId, String killReason) {
20020            synchronized (mPackages) {
20021                mPackageName = packageName;
20022                mWeFroze = mFrozenPackages.add(mPackageName);
20023
20024                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20025                if (ps != null) {
20026                    killApplication(ps.name, ps.appId, userId, killReason);
20027                }
20028
20029                final PackageParser.Package p = mPackages.get(packageName);
20030                if (p != null && p.childPackages != null) {
20031                    final int N = p.childPackages.size();
20032                    mChildren = new PackageFreezer[N];
20033                    for (int i = 0; i < N; i++) {
20034                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20035                                userId, killReason);
20036                    }
20037                } else {
20038                    mChildren = null;
20039                }
20040            }
20041            mCloseGuard.open("close");
20042        }
20043
20044        @Override
20045        protected void finalize() throws Throwable {
20046            try {
20047                mCloseGuard.warnIfOpen();
20048                close();
20049            } finally {
20050                super.finalize();
20051            }
20052        }
20053
20054        @Override
20055        public void close() {
20056            mCloseGuard.close();
20057            if (mClosed.compareAndSet(false, true)) {
20058                synchronized (mPackages) {
20059                    if (mWeFroze) {
20060                        mFrozenPackages.remove(mPackageName);
20061                    }
20062
20063                    if (mChildren != null) {
20064                        for (PackageFreezer freezer : mChildren) {
20065                            freezer.close();
20066                        }
20067                    }
20068                }
20069            }
20070        }
20071    }
20072
20073    /**
20074     * Verify that given package is currently frozen.
20075     */
20076    private void checkPackageFrozen(String packageName) {
20077        synchronized (mPackages) {
20078            if (!mFrozenPackages.contains(packageName)) {
20079                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20080            }
20081        }
20082    }
20083
20084    @Override
20085    public int movePackage(final String packageName, final String volumeUuid) {
20086        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20087
20088        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20089        final int moveId = mNextMoveId.getAndIncrement();
20090        mHandler.post(new Runnable() {
20091            @Override
20092            public void run() {
20093                try {
20094                    movePackageInternal(packageName, volumeUuid, moveId, user);
20095                } catch (PackageManagerException e) {
20096                    Slog.w(TAG, "Failed to move " + packageName, e);
20097                    mMoveCallbacks.notifyStatusChanged(moveId,
20098                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20099                }
20100            }
20101        });
20102        return moveId;
20103    }
20104
20105    private void movePackageInternal(final String packageName, final String volumeUuid,
20106            final int moveId, UserHandle user) throws PackageManagerException {
20107        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20108        final PackageManager pm = mContext.getPackageManager();
20109
20110        final boolean currentAsec;
20111        final String currentVolumeUuid;
20112        final File codeFile;
20113        final String installerPackageName;
20114        final String packageAbiOverride;
20115        final int appId;
20116        final String seinfo;
20117        final String label;
20118        final int targetSdkVersion;
20119        final PackageFreezer freezer;
20120        final int[] installedUserIds;
20121
20122        // reader
20123        synchronized (mPackages) {
20124            final PackageParser.Package pkg = mPackages.get(packageName);
20125            final PackageSetting ps = mSettings.mPackages.get(packageName);
20126            if (pkg == null || ps == null) {
20127                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20128            }
20129
20130            if (pkg.applicationInfo.isSystemApp()) {
20131                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20132                        "Cannot move system application");
20133            }
20134
20135            if (pkg.applicationInfo.isExternalAsec()) {
20136                currentAsec = true;
20137                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20138            } else if (pkg.applicationInfo.isForwardLocked()) {
20139                currentAsec = true;
20140                currentVolumeUuid = "forward_locked";
20141            } else {
20142                currentAsec = false;
20143                currentVolumeUuid = ps.volumeUuid;
20144
20145                final File probe = new File(pkg.codePath);
20146                final File probeOat = new File(probe, "oat");
20147                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20148                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20149                            "Move only supported for modern cluster style installs");
20150                }
20151            }
20152
20153            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20154                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20155                        "Package already moved to " + volumeUuid);
20156            }
20157            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20158                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20159                        "Device admin cannot be moved");
20160            }
20161
20162            if (mFrozenPackages.contains(packageName)) {
20163                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20164                        "Failed to move already frozen package");
20165            }
20166
20167            codeFile = new File(pkg.codePath);
20168            installerPackageName = ps.installerPackageName;
20169            packageAbiOverride = ps.cpuAbiOverrideString;
20170            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20171            seinfo = pkg.applicationInfo.seinfo;
20172            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20173            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20174            freezer = freezePackage(packageName, "movePackageInternal");
20175            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20176        }
20177
20178        final Bundle extras = new Bundle();
20179        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20180        extras.putString(Intent.EXTRA_TITLE, label);
20181        mMoveCallbacks.notifyCreated(moveId, extras);
20182
20183        int installFlags;
20184        final boolean moveCompleteApp;
20185        final File measurePath;
20186
20187        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20188            installFlags = INSTALL_INTERNAL;
20189            moveCompleteApp = !currentAsec;
20190            measurePath = Environment.getDataAppDirectory(volumeUuid);
20191        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20192            installFlags = INSTALL_EXTERNAL;
20193            moveCompleteApp = false;
20194            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20195        } else {
20196            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20197            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20198                    || !volume.isMountedWritable()) {
20199                freezer.close();
20200                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20201                        "Move location not mounted private volume");
20202            }
20203
20204            Preconditions.checkState(!currentAsec);
20205
20206            installFlags = INSTALL_INTERNAL;
20207            moveCompleteApp = true;
20208            measurePath = Environment.getDataAppDirectory(volumeUuid);
20209        }
20210
20211        final PackageStats stats = new PackageStats(null, -1);
20212        synchronized (mInstaller) {
20213            for (int userId : installedUserIds) {
20214                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20215                    freezer.close();
20216                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20217                            "Failed to measure package size");
20218                }
20219            }
20220        }
20221
20222        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20223                + stats.dataSize);
20224
20225        final long startFreeBytes = measurePath.getFreeSpace();
20226        final long sizeBytes;
20227        if (moveCompleteApp) {
20228            sizeBytes = stats.codeSize + stats.dataSize;
20229        } else {
20230            sizeBytes = stats.codeSize;
20231        }
20232
20233        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20234            freezer.close();
20235            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20236                    "Not enough free space to move");
20237        }
20238
20239        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20240
20241        final CountDownLatch installedLatch = new CountDownLatch(1);
20242        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20243            @Override
20244            public void onUserActionRequired(Intent intent) throws RemoteException {
20245                throw new IllegalStateException();
20246            }
20247
20248            @Override
20249            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20250                    Bundle extras) throws RemoteException {
20251                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20252                        + PackageManager.installStatusToString(returnCode, msg));
20253
20254                installedLatch.countDown();
20255                freezer.close();
20256
20257                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20258                switch (status) {
20259                    case PackageInstaller.STATUS_SUCCESS:
20260                        mMoveCallbacks.notifyStatusChanged(moveId,
20261                                PackageManager.MOVE_SUCCEEDED);
20262                        break;
20263                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20264                        mMoveCallbacks.notifyStatusChanged(moveId,
20265                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20266                        break;
20267                    default:
20268                        mMoveCallbacks.notifyStatusChanged(moveId,
20269                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20270                        break;
20271                }
20272            }
20273        };
20274
20275        final MoveInfo move;
20276        if (moveCompleteApp) {
20277            // Kick off a thread to report progress estimates
20278            new Thread() {
20279                @Override
20280                public void run() {
20281                    while (true) {
20282                        try {
20283                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20284                                break;
20285                            }
20286                        } catch (InterruptedException ignored) {
20287                        }
20288
20289                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20290                        final int progress = 10 + (int) MathUtils.constrain(
20291                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20292                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20293                    }
20294                }
20295            }.start();
20296
20297            final String dataAppName = codeFile.getName();
20298            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20299                    dataAppName, appId, seinfo, targetSdkVersion);
20300        } else {
20301            move = null;
20302        }
20303
20304        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20305
20306        final Message msg = mHandler.obtainMessage(INIT_COPY);
20307        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20308        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20309                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20310                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20311        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20312        msg.obj = params;
20313
20314        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20315                System.identityHashCode(msg.obj));
20316        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20317                System.identityHashCode(msg.obj));
20318
20319        mHandler.sendMessage(msg);
20320    }
20321
20322    @Override
20323    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20324        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20325
20326        final int realMoveId = mNextMoveId.getAndIncrement();
20327        final Bundle extras = new Bundle();
20328        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20329        mMoveCallbacks.notifyCreated(realMoveId, extras);
20330
20331        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20332            @Override
20333            public void onCreated(int moveId, Bundle extras) {
20334                // Ignored
20335            }
20336
20337            @Override
20338            public void onStatusChanged(int moveId, int status, long estMillis) {
20339                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20340            }
20341        };
20342
20343        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20344        storage.setPrimaryStorageUuid(volumeUuid, callback);
20345        return realMoveId;
20346    }
20347
20348    @Override
20349    public int getMoveStatus(int moveId) {
20350        mContext.enforceCallingOrSelfPermission(
20351                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20352        return mMoveCallbacks.mLastStatus.get(moveId);
20353    }
20354
20355    @Override
20356    public void registerMoveCallback(IPackageMoveObserver callback) {
20357        mContext.enforceCallingOrSelfPermission(
20358                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20359        mMoveCallbacks.register(callback);
20360    }
20361
20362    @Override
20363    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20364        mContext.enforceCallingOrSelfPermission(
20365                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20366        mMoveCallbacks.unregister(callback);
20367    }
20368
20369    @Override
20370    public boolean setInstallLocation(int loc) {
20371        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20372                null);
20373        if (getInstallLocation() == loc) {
20374            return true;
20375        }
20376        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20377                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20378            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20379                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20380            return true;
20381        }
20382        return false;
20383   }
20384
20385    @Override
20386    public int getInstallLocation() {
20387        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20388                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20389                PackageHelper.APP_INSTALL_AUTO);
20390    }
20391
20392    /** Called by UserManagerService */
20393    void cleanUpUser(UserManagerService userManager, int userHandle) {
20394        synchronized (mPackages) {
20395            mDirtyUsers.remove(userHandle);
20396            mUserNeedsBadging.delete(userHandle);
20397            mSettings.removeUserLPw(userHandle);
20398            mPendingBroadcasts.remove(userHandle);
20399            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20400            removeUnusedPackagesLPw(userManager, userHandle);
20401        }
20402    }
20403
20404    /**
20405     * We're removing userHandle and would like to remove any downloaded packages
20406     * that are no longer in use by any other user.
20407     * @param userHandle the user being removed
20408     */
20409    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20410        final boolean DEBUG_CLEAN_APKS = false;
20411        int [] users = userManager.getUserIds();
20412        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20413        while (psit.hasNext()) {
20414            PackageSetting ps = psit.next();
20415            if (ps.pkg == null) {
20416                continue;
20417            }
20418            final String packageName = ps.pkg.packageName;
20419            // Skip over if system app
20420            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20421                continue;
20422            }
20423            if (DEBUG_CLEAN_APKS) {
20424                Slog.i(TAG, "Checking package " + packageName);
20425            }
20426            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20427            if (keep) {
20428                if (DEBUG_CLEAN_APKS) {
20429                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20430                }
20431            } else {
20432                for (int i = 0; i < users.length; i++) {
20433                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20434                        keep = true;
20435                        if (DEBUG_CLEAN_APKS) {
20436                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20437                                    + users[i]);
20438                        }
20439                        break;
20440                    }
20441                }
20442            }
20443            if (!keep) {
20444                if (DEBUG_CLEAN_APKS) {
20445                    Slog.i(TAG, "  Removing package " + packageName);
20446                }
20447                mHandler.post(new Runnable() {
20448                    public void run() {
20449                        deletePackageX(packageName, userHandle, 0);
20450                    } //end run
20451                });
20452            }
20453        }
20454    }
20455
20456    /** Called by UserManagerService */
20457    void createNewUser(int userId) {
20458        synchronized (mInstallLock) {
20459            mSettings.createNewUserLI(this, mInstaller, userId);
20460        }
20461        synchronized (mPackages) {
20462            scheduleWritePackageRestrictionsLocked(userId);
20463            scheduleWritePackageListLocked(userId);
20464            applyFactoryDefaultBrowserLPw(userId);
20465            primeDomainVerificationsLPw(userId);
20466        }
20467    }
20468
20469    void onNewUserCreated(final int userId) {
20470        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20471        // If permission review for legacy apps is required, we represent
20472        // dagerous permissions for such apps as always granted runtime
20473        // permissions to keep per user flag state whether review is needed.
20474        // Hence, if a new user is added we have to propagate dangerous
20475        // permission grants for these legacy apps.
20476        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20477            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20478                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20479        }
20480    }
20481
20482    @Override
20483    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20484        mContext.enforceCallingOrSelfPermission(
20485                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20486                "Only package verification agents can read the verifier device identity");
20487
20488        synchronized (mPackages) {
20489            return mSettings.getVerifierDeviceIdentityLPw();
20490        }
20491    }
20492
20493    @Override
20494    public void setPermissionEnforced(String permission, boolean enforced) {
20495        // TODO: Now that we no longer change GID for storage, this should to away.
20496        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20497                "setPermissionEnforced");
20498        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20499            synchronized (mPackages) {
20500                if (mSettings.mReadExternalStorageEnforced == null
20501                        || mSettings.mReadExternalStorageEnforced != enforced) {
20502                    mSettings.mReadExternalStorageEnforced = enforced;
20503                    mSettings.writeLPr();
20504                }
20505            }
20506            // kill any non-foreground processes so we restart them and
20507            // grant/revoke the GID.
20508            final IActivityManager am = ActivityManagerNative.getDefault();
20509            if (am != null) {
20510                final long token = Binder.clearCallingIdentity();
20511                try {
20512                    am.killProcessesBelowForeground("setPermissionEnforcement");
20513                } catch (RemoteException e) {
20514                } finally {
20515                    Binder.restoreCallingIdentity(token);
20516                }
20517            }
20518        } else {
20519            throw new IllegalArgumentException("No selective enforcement for " + permission);
20520        }
20521    }
20522
20523    @Override
20524    @Deprecated
20525    public boolean isPermissionEnforced(String permission) {
20526        return true;
20527    }
20528
20529    @Override
20530    public boolean isStorageLow() {
20531        final long token = Binder.clearCallingIdentity();
20532        try {
20533            final DeviceStorageMonitorInternal
20534                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20535            if (dsm != null) {
20536                return dsm.isMemoryLow();
20537            } else {
20538                return false;
20539            }
20540        } finally {
20541            Binder.restoreCallingIdentity(token);
20542        }
20543    }
20544
20545    @Override
20546    public IPackageInstaller getPackageInstaller() {
20547        return mInstallerService;
20548    }
20549
20550    private boolean userNeedsBadging(int userId) {
20551        int index = mUserNeedsBadging.indexOfKey(userId);
20552        if (index < 0) {
20553            final UserInfo userInfo;
20554            final long token = Binder.clearCallingIdentity();
20555            try {
20556                userInfo = sUserManager.getUserInfo(userId);
20557            } finally {
20558                Binder.restoreCallingIdentity(token);
20559            }
20560            final boolean b;
20561            if (userInfo != null && userInfo.isManagedProfile()) {
20562                b = true;
20563            } else {
20564                b = false;
20565            }
20566            mUserNeedsBadging.put(userId, b);
20567            return b;
20568        }
20569        return mUserNeedsBadging.valueAt(index);
20570    }
20571
20572    @Override
20573    public KeySet getKeySetByAlias(String packageName, String alias) {
20574        if (packageName == null || alias == null) {
20575            return null;
20576        }
20577        synchronized(mPackages) {
20578            final PackageParser.Package pkg = mPackages.get(packageName);
20579            if (pkg == null) {
20580                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20581                throw new IllegalArgumentException("Unknown package: " + packageName);
20582            }
20583            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20584            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20585        }
20586    }
20587
20588    @Override
20589    public KeySet getSigningKeySet(String packageName) {
20590        if (packageName == null) {
20591            return null;
20592        }
20593        synchronized(mPackages) {
20594            final PackageParser.Package pkg = mPackages.get(packageName);
20595            if (pkg == null) {
20596                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20597                throw new IllegalArgumentException("Unknown package: " + packageName);
20598            }
20599            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20600                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20601                throw new SecurityException("May not access signing KeySet of other apps.");
20602            }
20603            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20604            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20605        }
20606    }
20607
20608    @Override
20609    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20610        if (packageName == null || ks == null) {
20611            return false;
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            IBinder ksh = ks.getToken();
20620            if (ksh instanceof KeySetHandle) {
20621                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20622                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20623            }
20624            return false;
20625        }
20626    }
20627
20628    @Override
20629    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20630        if (packageName == null || ks == null) {
20631            return false;
20632        }
20633        synchronized(mPackages) {
20634            final PackageParser.Package pkg = mPackages.get(packageName);
20635            if (pkg == null) {
20636                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20637                throw new IllegalArgumentException("Unknown package: " + packageName);
20638            }
20639            IBinder ksh = ks.getToken();
20640            if (ksh instanceof KeySetHandle) {
20641                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20642                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20643            }
20644            return false;
20645        }
20646    }
20647
20648    private void deletePackageIfUnusedLPr(final String packageName) {
20649        PackageSetting ps = mSettings.mPackages.get(packageName);
20650        if (ps == null) {
20651            return;
20652        }
20653        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20654            // TODO Implement atomic delete if package is unused
20655            // It is currently possible that the package will be deleted even if it is installed
20656            // after this method returns.
20657            mHandler.post(new Runnable() {
20658                public void run() {
20659                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20660                }
20661            });
20662        }
20663    }
20664
20665    /**
20666     * Check and throw if the given before/after packages would be considered a
20667     * downgrade.
20668     */
20669    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20670            throws PackageManagerException {
20671        if (after.versionCode < before.mVersionCode) {
20672            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20673                    "Update version code " + after.versionCode + " is older than current "
20674                    + before.mVersionCode);
20675        } else if (after.versionCode == before.mVersionCode) {
20676            if (after.baseRevisionCode < before.baseRevisionCode) {
20677                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20678                        "Update base revision code " + after.baseRevisionCode
20679                        + " is older than current " + before.baseRevisionCode);
20680            }
20681
20682            if (!ArrayUtils.isEmpty(after.splitNames)) {
20683                for (int i = 0; i < after.splitNames.length; i++) {
20684                    final String splitName = after.splitNames[i];
20685                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20686                    if (j != -1) {
20687                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20688                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20689                                    "Update split " + splitName + " revision code "
20690                                    + after.splitRevisionCodes[i] + " is older than current "
20691                                    + before.splitRevisionCodes[j]);
20692                        }
20693                    }
20694                }
20695            }
20696        }
20697    }
20698
20699    private static class MoveCallbacks extends Handler {
20700        private static final int MSG_CREATED = 1;
20701        private static final int MSG_STATUS_CHANGED = 2;
20702
20703        private final RemoteCallbackList<IPackageMoveObserver>
20704                mCallbacks = new RemoteCallbackList<>();
20705
20706        private final SparseIntArray mLastStatus = new SparseIntArray();
20707
20708        public MoveCallbacks(Looper looper) {
20709            super(looper);
20710        }
20711
20712        public void register(IPackageMoveObserver callback) {
20713            mCallbacks.register(callback);
20714        }
20715
20716        public void unregister(IPackageMoveObserver callback) {
20717            mCallbacks.unregister(callback);
20718        }
20719
20720        @Override
20721        public void handleMessage(Message msg) {
20722            final SomeArgs args = (SomeArgs) msg.obj;
20723            final int n = mCallbacks.beginBroadcast();
20724            for (int i = 0; i < n; i++) {
20725                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20726                try {
20727                    invokeCallback(callback, msg.what, args);
20728                } catch (RemoteException ignored) {
20729                }
20730            }
20731            mCallbacks.finishBroadcast();
20732            args.recycle();
20733        }
20734
20735        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20736                throws RemoteException {
20737            switch (what) {
20738                case MSG_CREATED: {
20739                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20740                    break;
20741                }
20742                case MSG_STATUS_CHANGED: {
20743                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20744                    break;
20745                }
20746            }
20747        }
20748
20749        private void notifyCreated(int moveId, Bundle extras) {
20750            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20751
20752            final SomeArgs args = SomeArgs.obtain();
20753            args.argi1 = moveId;
20754            args.arg2 = extras;
20755            obtainMessage(MSG_CREATED, args).sendToTarget();
20756        }
20757
20758        private void notifyStatusChanged(int moveId, int status) {
20759            notifyStatusChanged(moveId, status, -1);
20760        }
20761
20762        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20763            Slog.v(TAG, "Move " + moveId + " status " + status);
20764
20765            final SomeArgs args = SomeArgs.obtain();
20766            args.argi1 = moveId;
20767            args.argi2 = status;
20768            args.arg3 = estMillis;
20769            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20770
20771            synchronized (mLastStatus) {
20772                mLastStatus.put(moveId, status);
20773            }
20774        }
20775    }
20776
20777    private final static class OnPermissionChangeListeners extends Handler {
20778        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20779
20780        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20781                new RemoteCallbackList<>();
20782
20783        public OnPermissionChangeListeners(Looper looper) {
20784            super(looper);
20785        }
20786
20787        @Override
20788        public void handleMessage(Message msg) {
20789            switch (msg.what) {
20790                case MSG_ON_PERMISSIONS_CHANGED: {
20791                    final int uid = msg.arg1;
20792                    handleOnPermissionsChanged(uid);
20793                } break;
20794            }
20795        }
20796
20797        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20798            mPermissionListeners.register(listener);
20799
20800        }
20801
20802        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20803            mPermissionListeners.unregister(listener);
20804        }
20805
20806        public void onPermissionsChanged(int uid) {
20807            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20808                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20809            }
20810        }
20811
20812        private void handleOnPermissionsChanged(int uid) {
20813            final int count = mPermissionListeners.beginBroadcast();
20814            try {
20815                for (int i = 0; i < count; i++) {
20816                    IOnPermissionsChangeListener callback = mPermissionListeners
20817                            .getBroadcastItem(i);
20818                    try {
20819                        callback.onPermissionsChanged(uid);
20820                    } catch (RemoteException e) {
20821                        Log.e(TAG, "Permission listener is dead", e);
20822                    }
20823                }
20824            } finally {
20825                mPermissionListeners.finishBroadcast();
20826            }
20827        }
20828    }
20829
20830    private class PackageManagerInternalImpl extends PackageManagerInternal {
20831        @Override
20832        public void setLocationPackagesProvider(PackagesProvider provider) {
20833            synchronized (mPackages) {
20834                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20835            }
20836        }
20837
20838        @Override
20839        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20840            synchronized (mPackages) {
20841                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20842            }
20843        }
20844
20845        @Override
20846        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20847            synchronized (mPackages) {
20848                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20849            }
20850        }
20851
20852        @Override
20853        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20854            synchronized (mPackages) {
20855                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20856            }
20857        }
20858
20859        @Override
20860        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20861            synchronized (mPackages) {
20862                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20863            }
20864        }
20865
20866        @Override
20867        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20868            synchronized (mPackages) {
20869                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20870            }
20871        }
20872
20873        @Override
20874        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20875            synchronized (mPackages) {
20876                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20877                        packageName, userId);
20878            }
20879        }
20880
20881        @Override
20882        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20883            synchronized (mPackages) {
20884                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20885                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20886                        packageName, userId);
20887            }
20888        }
20889
20890        @Override
20891        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20892            synchronized (mPackages) {
20893                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20894                        packageName, userId);
20895            }
20896        }
20897
20898        @Override
20899        public void setKeepUninstalledPackages(final List<String> packageList) {
20900            Preconditions.checkNotNull(packageList);
20901            List<String> removedFromList = null;
20902            synchronized (mPackages) {
20903                if (mKeepUninstalledPackages != null) {
20904                    final int packagesCount = mKeepUninstalledPackages.size();
20905                    for (int i = 0; i < packagesCount; i++) {
20906                        String oldPackage = mKeepUninstalledPackages.get(i);
20907                        if (packageList != null && packageList.contains(oldPackage)) {
20908                            continue;
20909                        }
20910                        if (removedFromList == null) {
20911                            removedFromList = new ArrayList<>();
20912                        }
20913                        removedFromList.add(oldPackage);
20914                    }
20915                }
20916                mKeepUninstalledPackages = new ArrayList<>(packageList);
20917                if (removedFromList != null) {
20918                    final int removedCount = removedFromList.size();
20919                    for (int i = 0; i < removedCount; i++) {
20920                        deletePackageIfUnusedLPr(removedFromList.get(i));
20921                    }
20922                }
20923            }
20924        }
20925
20926        @Override
20927        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20928            synchronized (mPackages) {
20929                // If we do not support permission review, done.
20930                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20931                    return false;
20932                }
20933
20934                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20935                if (packageSetting == null) {
20936                    return false;
20937                }
20938
20939                // Permission review applies only to apps not supporting the new permission model.
20940                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20941                    return false;
20942                }
20943
20944                // Legacy apps have the permission and get user consent on launch.
20945                PermissionsState permissionsState = packageSetting.getPermissionsState();
20946                return permissionsState.isPermissionReviewRequired(userId);
20947            }
20948        }
20949
20950        @Override
20951        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20952            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20953        }
20954
20955        @Override
20956        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20957                int userId) {
20958            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20959        }
20960
20961        @Override
20962        public void setDeviceAndProfileOwnerPackages(
20963                int deviceOwnerUserId, String deviceOwnerPackage,
20964                SparseArray<String> profileOwnerPackages) {
20965            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20966                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20967        }
20968
20969        @Override
20970        public boolean isPackageDataProtected(int userId, String packageName) {
20971            return mProtectedPackages.isPackageDataProtected(userId, packageName);
20972        }
20973    }
20974
20975    @Override
20976    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20977        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20978        synchronized (mPackages) {
20979            final long identity = Binder.clearCallingIdentity();
20980            try {
20981                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20982                        packageNames, userId);
20983            } finally {
20984                Binder.restoreCallingIdentity(identity);
20985            }
20986        }
20987    }
20988
20989    private static void enforceSystemOrPhoneCaller(String tag) {
20990        int callingUid = Binder.getCallingUid();
20991        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20992            throw new SecurityException(
20993                    "Cannot call " + tag + " from UID " + callingUid);
20994        }
20995    }
20996
20997    boolean isHistoricalPackageUsageAvailable() {
20998        return mPackageUsage.isHistoricalPackageUsageAvailable();
20999    }
21000
21001    /**
21002     * Return a <b>copy</b> of the collection of packages known to the package manager.
21003     * @return A copy of the values of mPackages.
21004     */
21005    Collection<PackageParser.Package> getPackages() {
21006        synchronized (mPackages) {
21007            return new ArrayList<>(mPackages.values());
21008        }
21009    }
21010
21011    /**
21012     * Logs process start information (including base APK hash) to the security log.
21013     * @hide
21014     */
21015    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21016            String apkFile, int pid) {
21017        if (!SecurityLog.isLoggingEnabled()) {
21018            return;
21019        }
21020        Bundle data = new Bundle();
21021        data.putLong("startTimestamp", System.currentTimeMillis());
21022        data.putString("processName", processName);
21023        data.putInt("uid", uid);
21024        data.putString("seinfo", seinfo);
21025        data.putString("apkFile", apkFile);
21026        data.putInt("pid", pid);
21027        Message msg = mProcessLoggingHandler.obtainMessage(
21028                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21029        msg.setData(data);
21030        mProcessLoggingHandler.sendMessage(msg);
21031    }
21032
21033    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21034        return mCompilerStats.getPackageStats(pkgName);
21035    }
21036
21037    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21038        return getOrCreateCompilerPackageStats(pkg.packageName);
21039    }
21040
21041    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21042        return mCompilerStats.getOrCreatePackageStats(pkgName);
21043    }
21044
21045    public void deleteCompilerPackageStats(String pkgName) {
21046        mCompilerStats.deletePackageStats(pkgName);
21047    }
21048}
21049