PackageManagerService.java revision c2e96d45d27ab1465aaef89c1a3161708c714bcd
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.Pair;
216import android.util.PrintStreamPrinter;
217import android.util.Slog;
218import android.util.SparseArray;
219import android.util.SparseBooleanArray;
220import android.util.SparseIntArray;
221import android.util.Xml;
222import android.util.jar.StrictJarFile;
223import android.view.Display;
224
225import com.android.internal.R;
226import com.android.internal.annotations.GuardedBy;
227import com.android.internal.app.IMediaContainerService;
228import com.android.internal.app.ResolverActivity;
229import com.android.internal.content.NativeLibraryHelper;
230import com.android.internal.content.PackageHelper;
231import com.android.internal.logging.MetricsLogger;
232import com.android.internal.os.IParcelFileDescriptorFactory;
233import com.android.internal.os.InstallerConnection.InstallerException;
234import com.android.internal.os.SomeArgs;
235import com.android.internal.os.Zygote;
236import com.android.internal.telephony.CarrierAppUtils;
237import com.android.internal.util.ArrayUtils;
238import com.android.internal.util.FastPrintWriter;
239import com.android.internal.util.FastXmlSerializer;
240import com.android.internal.util.IndentingPrintWriter;
241import com.android.internal.util.Preconditions;
242import com.android.internal.util.XmlUtils;
243import com.android.server.AttributeCache;
244import com.android.server.EventLogTags;
245import com.android.server.FgThread;
246import com.android.server.IntentResolver;
247import com.android.server.LocalServices;
248import com.android.server.ServiceThread;
249import com.android.server.SystemConfig;
250import com.android.server.Watchdog;
251import com.android.server.net.NetworkPolicyManagerInternal;
252import com.android.server.pm.PermissionsState.PermissionState;
253import com.android.server.pm.Settings.DatabaseVersion;
254import com.android.server.pm.Settings.VersionInfo;
255import com.android.server.storage.DeviceStorageMonitorInternal;
256
257import dalvik.system.CloseGuard;
258import dalvik.system.DexFile;
259import dalvik.system.VMRuntime;
260
261import libcore.io.IoUtils;
262import libcore.util.EmptyArray;
263
264import org.xmlpull.v1.XmlPullParser;
265import org.xmlpull.v1.XmlPullParserException;
266import org.xmlpull.v1.XmlSerializer;
267
268import java.io.BufferedOutputStream;
269import java.io.BufferedReader;
270import java.io.ByteArrayInputStream;
271import java.io.ByteArrayOutputStream;
272import java.io.File;
273import java.io.FileDescriptor;
274import java.io.FileInputStream;
275import java.io.FileNotFoundException;
276import java.io.FileOutputStream;
277import java.io.FileReader;
278import java.io.FilenameFilter;
279import java.io.IOException;
280import java.io.PrintWriter;
281import java.nio.charset.StandardCharsets;
282import java.security.DigestInputStream;
283import java.security.MessageDigest;
284import java.security.NoSuchAlgorithmException;
285import java.security.PublicKey;
286import java.security.cert.Certificate;
287import java.security.cert.CertificateEncodingException;
288import java.security.cert.CertificateException;
289import java.text.SimpleDateFormat;
290import java.util.ArrayList;
291import java.util.Arrays;
292import java.util.Collection;
293import java.util.Collections;
294import java.util.Comparator;
295import java.util.Date;
296import java.util.HashSet;
297import java.util.Iterator;
298import java.util.List;
299import java.util.Map;
300import java.util.Objects;
301import java.util.Set;
302import java.util.concurrent.CountDownLatch;
303import java.util.concurrent.TimeUnit;
304import java.util.concurrent.atomic.AtomicBoolean;
305import java.util.concurrent.atomic.AtomicInteger;
306
307/**
308 * Keep track of all those APKs everywhere.
309 * <p>
310 * Internally there are two important locks:
311 * <ul>
312 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
313 * and other related state. It is a fine-grained lock that should only be held
314 * momentarily, as it's one of the most contended locks in the system.
315 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
316 * operations typically involve heavy lifting of application data on disk. Since
317 * {@code installd} is single-threaded, and it's operations can often be slow,
318 * this lock should never be acquired while already holding {@link #mPackages}.
319 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
320 * holding {@link #mInstallLock}.
321 * </ul>
322 * Many internal methods rely on the caller to hold the appropriate locks, and
323 * this contract is expressed through method name suffixes:
324 * <ul>
325 * <li>fooLI(): the caller must hold {@link #mInstallLock}
326 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
327 * being modified must be frozen
328 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
329 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
330 * </ul>
331 * <p>
332 * Because this class is very central to the platform's security; please run all
333 * CTS and unit tests whenever making modifications:
334 *
335 * <pre>
336 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
337 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
338 * </pre>
339 */
340public class PackageManagerService extends IPackageManager.Stub {
341    static final String TAG = "PackageManager";
342    static final boolean DEBUG_SETTINGS = false;
343    static final boolean DEBUG_PREFERRED = false;
344    static final boolean DEBUG_UPGRADE = false;
345    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
346    private static final boolean DEBUG_BACKUP = false;
347    private static final boolean DEBUG_INSTALL = false;
348    private static final boolean DEBUG_REMOVE = false;
349    private static final boolean DEBUG_BROADCASTS = false;
350    private static final boolean DEBUG_SHOW_INFO = false;
351    private static final boolean DEBUG_PACKAGE_INFO = false;
352    private static final boolean DEBUG_INTENT_MATCHING = false;
353    private static final boolean DEBUG_PACKAGE_SCANNING = false;
354    private static final boolean DEBUG_VERIFY = false;
355    private static final boolean DEBUG_FILTERS = false;
356
357    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
358    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
359    // user, but by default initialize to this.
360    static final boolean DEBUG_DEXOPT = false;
361
362    private static final boolean DEBUG_ABI_SELECTION = false;
363    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
364    private static final boolean DEBUG_TRIAGED_MISSING = false;
365    private static final boolean DEBUG_APP_DATA = false;
366
367    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
368
369    // STOPSHIP; b/30256615
370    private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE;
371
372    private static final int RADIO_UID = Process.PHONE_UID;
373    private static final int LOG_UID = Process.LOG_UID;
374    private static final int NFC_UID = Process.NFC_UID;
375    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
376    private static final int SHELL_UID = Process.SHELL_UID;
377
378    // Cap the size of permission trees that 3rd party apps can define
379    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
380
381    // Suffix used during package installation when copying/moving
382    // package apks to install directory.
383    private static final String INSTALL_PACKAGE_SUFFIX = "-";
384
385    static final int SCAN_NO_DEX = 1<<1;
386    static final int SCAN_FORCE_DEX = 1<<2;
387    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
388    static final int SCAN_NEW_INSTALL = 1<<4;
389    static final int SCAN_NO_PATHS = 1<<5;
390    static final int SCAN_UPDATE_TIME = 1<<6;
391    static final int SCAN_DEFER_DEX = 1<<7;
392    static final int SCAN_BOOTING = 1<<8;
393    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
394    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
395    static final int SCAN_REPLACING = 1<<11;
396    static final int SCAN_REQUIRE_KNOWN = 1<<12;
397    static final int SCAN_MOVE = 1<<13;
398    static final int SCAN_INITIAL = 1<<14;
399    static final int SCAN_CHECK_ONLY = 1<<15;
400    static final int SCAN_DONT_KILL_APP = 1<<17;
401    static final int SCAN_IGNORE_FROZEN = 1<<18;
402
403    static final int REMOVE_CHATTY = 1<<16;
404
405    private static final int[] EMPTY_INT_ARRAY = new int[0];
406
407    /**
408     * Timeout (in milliseconds) after which the watchdog should declare that
409     * our handler thread is wedged.  The usual default for such things is one
410     * minute but we sometimes do very lengthy I/O operations on this thread,
411     * such as installing multi-gigabyte applications, so ours needs to be longer.
412     */
413    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
414
415    /**
416     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
417     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
418     * settings entry if available, otherwise we use the hardcoded default.  If it's been
419     * more than this long since the last fstrim, we force one during the boot sequence.
420     *
421     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
422     * one gets run at the next available charging+idle time.  This final mandatory
423     * no-fstrim check kicks in only of the other scheduling criteria is never met.
424     */
425    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
426
427    /**
428     * Whether verification is enabled by default.
429     */
430    private static final boolean DEFAULT_VERIFY_ENABLE = true;
431
432    /**
433     * The default maximum time to wait for the verification agent to return in
434     * milliseconds.
435     */
436    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
437
438    /**
439     * The default response for package verification timeout.
440     *
441     * This can be either PackageManager.VERIFICATION_ALLOW or
442     * PackageManager.VERIFICATION_REJECT.
443     */
444    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
445
446    static final String PLATFORM_PACKAGE_NAME = "android";
447
448    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
449
450    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
451            DEFAULT_CONTAINER_PACKAGE,
452            "com.android.defcontainer.DefaultContainerService");
453
454    private static final String KILL_APP_REASON_GIDS_CHANGED =
455            "permission grant or revoke changed gids";
456
457    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
458            "permissions revoked";
459
460    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
461
462    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
463
464    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
465    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
466
467    /** Permission grant: not grant the permission. */
468    private static final int GRANT_DENIED = 1;
469
470    /** Permission grant: grant the permission as an install permission. */
471    private static final int GRANT_INSTALL = 2;
472
473    /** Permission grant: grant the permission as a runtime one. */
474    private static final int GRANT_RUNTIME = 3;
475
476    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
477    private static final int GRANT_UPGRADE = 4;
478
479    /** Canonical intent used to identify what counts as a "web browser" app */
480    private static final Intent sBrowserIntent;
481    static {
482        sBrowserIntent = new Intent();
483        sBrowserIntent.setAction(Intent.ACTION_VIEW);
484        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
485        sBrowserIntent.setData(Uri.parse("http:"));
486    }
487
488    /**
489     * The set of all protected actions [i.e. those actions for which a high priority
490     * intent filter is disallowed].
491     */
492    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
493    static {
494        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
495        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
496        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
497        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
498    }
499
500    // Compilation reasons.
501    public static final int REASON_FIRST_BOOT = 0;
502    public static final int REASON_BOOT = 1;
503    public static final int REASON_INSTALL = 2;
504    public static final int REASON_BACKGROUND_DEXOPT = 3;
505    public static final int REASON_AB_OTA = 4;
506    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
507    public static final int REASON_SHARED_APK = 6;
508    public static final int REASON_FORCED_DEXOPT = 7;
509    public static final int REASON_CORE_APP = 8;
510
511    public static final int REASON_LAST = REASON_CORE_APP;
512
513    /** Special library name that skips shared libraries check during compilation. */
514    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
515
516    final ServiceThread mHandlerThread;
517
518    final PackageHandler mHandler;
519
520    private final ProcessLoggingHandler mProcessLoggingHandler;
521
522    /**
523     * Messages for {@link #mHandler} that need to wait for system ready before
524     * being dispatched.
525     */
526    private ArrayList<Message> mPostSystemReadyMessages;
527
528    final int mSdkVersion = Build.VERSION.SDK_INT;
529
530    final Context mContext;
531    final boolean mFactoryTest;
532    final boolean mOnlyCore;
533    final DisplayMetrics mMetrics;
534    final int mDefParseFlags;
535    final String[] mSeparateProcesses;
536    final boolean mIsUpgrade;
537    final boolean mIsPreNUpgrade;
538    final boolean mIsPreNMR1Upgrade;
539
540    /** The location for ASEC container files on internal storage. */
541    final String mAsecInternalPath;
542
543    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
544    // LOCK HELD.  Can be called with mInstallLock held.
545    @GuardedBy("mInstallLock")
546    final Installer mInstaller;
547
548    /** Directory where installed third-party apps stored */
549    final File mAppInstallDir;
550    final File mEphemeralInstallDir;
551
552    /**
553     * Directory to which applications installed internally have their
554     * 32 bit native libraries copied.
555     */
556    private File mAppLib32InstallDir;
557
558    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
559    // apps.
560    final File mDrmAppPrivateInstallDir;
561
562    // ----------------------------------------------------------------
563
564    // Lock for state used when installing and doing other long running
565    // operations.  Methods that must be called with this lock held have
566    // the suffix "LI".
567    final Object mInstallLock = new Object();
568
569    // ----------------------------------------------------------------
570
571    // Keys are String (package name), values are Package.  This also serves
572    // as the lock for the global state.  Methods that must be called with
573    // this lock held have the prefix "LP".
574    @GuardedBy("mPackages")
575    final ArrayMap<String, PackageParser.Package> mPackages =
576            new ArrayMap<String, PackageParser.Package>();
577
578    final ArrayMap<String, Set<String>> mKnownCodebase =
579            new ArrayMap<String, Set<String>>();
580
581    // Tracks available target package names -> overlay package paths.
582    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
583        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
584
585    /**
586     * Tracks new system packages [received in an OTA] that we expect to
587     * find updated user-installed versions. Keys are package name, values
588     * are package location.
589     */
590    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
591    /**
592     * Tracks high priority intent filters for protected actions. During boot, certain
593     * filter actions are protected and should never be allowed to have a high priority
594     * intent filter for them. However, there is one, and only one exception -- the
595     * setup wizard. It must be able to define a high priority intent filter for these
596     * actions to ensure there are no escapes from the wizard. We need to delay processing
597     * of these during boot as we need to look at all of the system packages in order
598     * to know which component is the setup wizard.
599     */
600    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
601    /**
602     * Whether or not processing protected filters should be deferred.
603     */
604    private boolean mDeferProtectedFilters = true;
605
606    /**
607     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
608     */
609    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
610    /**
611     * Whether or not system app permissions should be promoted from install to runtime.
612     */
613    boolean mPromoteSystemApps;
614
615    @GuardedBy("mPackages")
616    final Settings mSettings;
617
618    /**
619     * Set of package names that are currently "frozen", which means active
620     * surgery is being done on the code/data for that package. The platform
621     * will refuse to launch frozen packages to avoid race conditions.
622     *
623     * @see PackageFreezer
624     */
625    @GuardedBy("mPackages")
626    final ArraySet<String> mFrozenPackages = new ArraySet<>();
627
628    final ProtectedPackages mProtectedPackages;
629
630    boolean mFirstBoot;
631
632    // System configuration read by SystemConfig.
633    final int[] mGlobalGids;
634    final SparseArray<ArraySet<String>> mSystemPermissions;
635    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
636
637    // If mac_permissions.xml was found for seinfo labeling.
638    boolean mFoundPolicyFile;
639
640    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
641
642    public static final class SharedLibraryEntry {
643        public final String path;
644        public final String apk;
645
646        SharedLibraryEntry(String _path, String _apk) {
647            path = _path;
648            apk = _apk;
649        }
650    }
651
652    // Currently known shared libraries.
653    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
654            new ArrayMap<String, SharedLibraryEntry>();
655
656    // All available activities, for your resolving pleasure.
657    final ActivityIntentResolver mActivities =
658            new ActivityIntentResolver();
659
660    // All available receivers, for your resolving pleasure.
661    final ActivityIntentResolver mReceivers =
662            new ActivityIntentResolver();
663
664    // All available services, for your resolving pleasure.
665    final ServiceIntentResolver mServices = new ServiceIntentResolver();
666
667    // All available providers, for your resolving pleasure.
668    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
669
670    // Mapping from provider base names (first directory in content URI codePath)
671    // to the provider information.
672    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
673            new ArrayMap<String, PackageParser.Provider>();
674
675    // Mapping from instrumentation class names to info about them.
676    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
677            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
678
679    // Mapping from permission names to info about them.
680    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
681            new ArrayMap<String, PackageParser.PermissionGroup>();
682
683    // Packages whose data we have transfered into another package, thus
684    // should no longer exist.
685    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
686
687    // Broadcast actions that are only available to the system.
688    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
689
690    /** List of packages waiting for verification. */
691    final SparseArray<PackageVerificationState> mPendingVerification
692            = new SparseArray<PackageVerificationState>();
693
694    /** Set of packages associated with each app op permission. */
695    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
696
697    final PackageInstallerService mInstallerService;
698
699    private final PackageDexOptimizer mPackageDexOptimizer;
700
701    private AtomicInteger mNextMoveId = new AtomicInteger();
702    private final MoveCallbacks mMoveCallbacks;
703
704    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
705
706    // Cache of users who need badging.
707    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
708
709    /** Token for keys in mPendingVerification. */
710    private int mPendingVerificationToken = 0;
711
712    volatile boolean mSystemReady;
713    volatile boolean mSafeMode;
714    volatile boolean mHasSystemUidErrors;
715
716    ApplicationInfo mAndroidApplication;
717    final ActivityInfo mResolveActivity = new ActivityInfo();
718    final ResolveInfo mResolveInfo = new ResolveInfo();
719    ComponentName mResolveComponentName;
720    PackageParser.Package mPlatformPackage;
721    ComponentName mCustomResolverComponentName;
722
723    boolean mResolverReplaced = false;
724
725    private final @Nullable ComponentName mIntentFilterVerifierComponent;
726    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
727
728    private int mIntentFilterVerificationToken = 0;
729
730    /** Component that knows whether or not an ephemeral application exists */
731    final ComponentName mEphemeralResolverComponent;
732    /** The service connection to the ephemeral resolver */
733    final EphemeralResolverConnection mEphemeralResolverConnection;
734
735    /** Component used to install ephemeral applications */
736    final ComponentName mEphemeralInstallerComponent;
737    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
738    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
739
740    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
741            = new SparseArray<IntentFilterVerificationState>();
742
743    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
744
745    // List of packages names to keep cached, even if they are uninstalled for all users
746    private List<String> mKeepUninstalledPackages;
747
748    private UserManagerInternal mUserManagerInternal;
749
750    private static class IFVerificationParams {
751        PackageParser.Package pkg;
752        boolean replacing;
753        int userId;
754        int verifierUid;
755
756        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
757                int _userId, int _verifierUid) {
758            pkg = _pkg;
759            replacing = _replacing;
760            userId = _userId;
761            replacing = _replacing;
762            verifierUid = _verifierUid;
763        }
764    }
765
766    private interface IntentFilterVerifier<T extends IntentFilter> {
767        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
768                                               T filter, String packageName);
769        void startVerifications(int userId);
770        void receiveVerificationResponse(int verificationId);
771    }
772
773    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
774        private Context mContext;
775        private ComponentName mIntentFilterVerifierComponent;
776        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
777
778        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
779            mContext = context;
780            mIntentFilterVerifierComponent = verifierComponent;
781        }
782
783        private String getDefaultScheme() {
784            return IntentFilter.SCHEME_HTTPS;
785        }
786
787        @Override
788        public void startVerifications(int userId) {
789            // Launch verifications requests
790            int count = mCurrentIntentFilterVerifications.size();
791            for (int n=0; n<count; n++) {
792                int verificationId = mCurrentIntentFilterVerifications.get(n);
793                final IntentFilterVerificationState ivs =
794                        mIntentFilterVerificationStates.get(verificationId);
795
796                String packageName = ivs.getPackageName();
797
798                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
799                final int filterCount = filters.size();
800                ArraySet<String> domainsSet = new ArraySet<>();
801                for (int m=0; m<filterCount; m++) {
802                    PackageParser.ActivityIntentInfo filter = filters.get(m);
803                    domainsSet.addAll(filter.getHostsList());
804                }
805                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
806                synchronized (mPackages) {
807                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
808                            packageName, domainsList) != null) {
809                        scheduleWriteSettingsLocked();
810                    }
811                }
812                sendVerificationRequest(userId, verificationId, ivs);
813            }
814            mCurrentIntentFilterVerifications.clear();
815        }
816
817        private void sendVerificationRequest(int userId, int verificationId,
818                IntentFilterVerificationState ivs) {
819
820            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
821            verificationIntent.putExtra(
822                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
823                    verificationId);
824            verificationIntent.putExtra(
825                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
826                    getDefaultScheme());
827            verificationIntent.putExtra(
828                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
829                    ivs.getHostsString());
830            verificationIntent.putExtra(
831                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
832                    ivs.getPackageName());
833            verificationIntent.setComponent(mIntentFilterVerifierComponent);
834            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
835
836            UserHandle user = new UserHandle(userId);
837            mContext.sendBroadcastAsUser(verificationIntent, user);
838            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
839                    "Sending IntentFilter verification broadcast");
840        }
841
842        public void receiveVerificationResponse(int verificationId) {
843            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
844
845            final boolean verified = ivs.isVerified();
846
847            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
848            final int count = filters.size();
849            if (DEBUG_DOMAIN_VERIFICATION) {
850                Slog.i(TAG, "Received verification response " + verificationId
851                        + " for " + count + " filters, verified=" + verified);
852            }
853            for (int n=0; n<count; n++) {
854                PackageParser.ActivityIntentInfo filter = filters.get(n);
855                filter.setVerified(verified);
856
857                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
858                        + " verified with result:" + verified + " and hosts:"
859                        + ivs.getHostsString());
860            }
861
862            mIntentFilterVerificationStates.remove(verificationId);
863
864            final String packageName = ivs.getPackageName();
865            IntentFilterVerificationInfo ivi = null;
866
867            synchronized (mPackages) {
868                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
869            }
870            if (ivi == null) {
871                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
872                        + verificationId + " packageName:" + packageName);
873                return;
874            }
875            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
876                    "Updating IntentFilterVerificationInfo for package " + packageName
877                            +" verificationId:" + verificationId);
878
879            synchronized (mPackages) {
880                if (verified) {
881                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
882                } else {
883                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
884                }
885                scheduleWriteSettingsLocked();
886
887                final int userId = ivs.getUserId();
888                if (userId != UserHandle.USER_ALL) {
889                    final int userStatus =
890                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
891
892                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
893                    boolean needUpdate = false;
894
895                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
896                    // already been set by the User thru the Disambiguation dialog
897                    switch (userStatus) {
898                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
899                            if (verified) {
900                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
901                            } else {
902                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
903                            }
904                            needUpdate = true;
905                            break;
906
907                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
908                            if (verified) {
909                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
910                                needUpdate = true;
911                            }
912                            break;
913
914                        default:
915                            // Nothing to do
916                    }
917
918                    if (needUpdate) {
919                        mSettings.updateIntentFilterVerificationStatusLPw(
920                                packageName, updatedStatus, userId);
921                        scheduleWritePackageRestrictionsLocked(userId);
922                    }
923                }
924            }
925        }
926
927        @Override
928        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
929                    ActivityIntentInfo filter, String packageName) {
930            if (!hasValidDomains(filter)) {
931                return false;
932            }
933            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
934            if (ivs == null) {
935                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
936                        packageName);
937            }
938            if (DEBUG_DOMAIN_VERIFICATION) {
939                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
940            }
941            ivs.addFilter(filter);
942            return true;
943        }
944
945        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
946                int userId, int verificationId, String packageName) {
947            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
948                    verifierUid, userId, packageName);
949            ivs.setPendingState();
950            synchronized (mPackages) {
951                mIntentFilterVerificationStates.append(verificationId, ivs);
952                mCurrentIntentFilterVerifications.add(verificationId);
953            }
954            return ivs;
955        }
956    }
957
958    private static boolean hasValidDomains(ActivityIntentInfo filter) {
959        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
960                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
961                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
962    }
963
964    // Set of pending broadcasts for aggregating enable/disable of components.
965    static class PendingPackageBroadcasts {
966        // for each user id, a map of <package name -> components within that package>
967        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
968
969        public PendingPackageBroadcasts() {
970            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
971        }
972
973        public ArrayList<String> get(int userId, String packageName) {
974            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
975            return packages.get(packageName);
976        }
977
978        public void put(int userId, String packageName, ArrayList<String> components) {
979            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
980            packages.put(packageName, components);
981        }
982
983        public void remove(int userId, String packageName) {
984            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
985            if (packages != null) {
986                packages.remove(packageName);
987            }
988        }
989
990        public void remove(int userId) {
991            mUidMap.remove(userId);
992        }
993
994        public int userIdCount() {
995            return mUidMap.size();
996        }
997
998        public int userIdAt(int n) {
999            return mUidMap.keyAt(n);
1000        }
1001
1002        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1003            return mUidMap.get(userId);
1004        }
1005
1006        public int size() {
1007            // total number of pending broadcast entries across all userIds
1008            int num = 0;
1009            for (int i = 0; i< mUidMap.size(); i++) {
1010                num += mUidMap.valueAt(i).size();
1011            }
1012            return num;
1013        }
1014
1015        public void clear() {
1016            mUidMap.clear();
1017        }
1018
1019        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1020            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1021            if (map == null) {
1022                map = new ArrayMap<String, ArrayList<String>>();
1023                mUidMap.put(userId, map);
1024            }
1025            return map;
1026        }
1027    }
1028    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1029
1030    // Service Connection to remote media container service to copy
1031    // package uri's from external media onto secure containers
1032    // or internal storage.
1033    private IMediaContainerService mContainerService = null;
1034
1035    static final int SEND_PENDING_BROADCAST = 1;
1036    static final int MCS_BOUND = 3;
1037    static final int END_COPY = 4;
1038    static final int INIT_COPY = 5;
1039    static final int MCS_UNBIND = 6;
1040    static final int START_CLEANING_PACKAGE = 7;
1041    static final int FIND_INSTALL_LOC = 8;
1042    static final int POST_INSTALL = 9;
1043    static final int MCS_RECONNECT = 10;
1044    static final int MCS_GIVE_UP = 11;
1045    static final int UPDATED_MEDIA_STATUS = 12;
1046    static final int WRITE_SETTINGS = 13;
1047    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1048    static final int PACKAGE_VERIFIED = 15;
1049    static final int CHECK_PENDING_VERIFICATION = 16;
1050    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1051    static final int INTENT_FILTER_VERIFIED = 18;
1052    static final int WRITE_PACKAGE_LIST = 19;
1053
1054    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1055
1056    // Delay time in millisecs
1057    static final int BROADCAST_DELAY = 10 * 1000;
1058
1059    static UserManagerService sUserManager;
1060
1061    // Stores a list of users whose package restrictions file needs to be updated
1062    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1063
1064    final private DefaultContainerConnection mDefContainerConn =
1065            new DefaultContainerConnection();
1066    class DefaultContainerConnection implements ServiceConnection {
1067        public void onServiceConnected(ComponentName name, IBinder service) {
1068            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1069            IMediaContainerService imcs =
1070                IMediaContainerService.Stub.asInterface(service);
1071            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1072        }
1073
1074        public void onServiceDisconnected(ComponentName name) {
1075            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1076        }
1077    }
1078
1079    // Recordkeeping of restore-after-install operations that are currently in flight
1080    // between the Package Manager and the Backup Manager
1081    static class PostInstallData {
1082        public InstallArgs args;
1083        public PackageInstalledInfo res;
1084
1085        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1086            args = _a;
1087            res = _r;
1088        }
1089    }
1090
1091    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1092    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1093
1094    // XML tags for backup/restore of various bits of state
1095    private static final String TAG_PREFERRED_BACKUP = "pa";
1096    private static final String TAG_DEFAULT_APPS = "da";
1097    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1098
1099    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1100    private static final String TAG_ALL_GRANTS = "rt-grants";
1101    private static final String TAG_GRANT = "grant";
1102    private static final String ATTR_PACKAGE_NAME = "pkg";
1103
1104    private static final String TAG_PERMISSION = "perm";
1105    private static final String ATTR_PERMISSION_NAME = "name";
1106    private static final String ATTR_IS_GRANTED = "g";
1107    private static final String ATTR_USER_SET = "set";
1108    private static final String ATTR_USER_FIXED = "fixed";
1109    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1110
1111    // System/policy permission grants are not backed up
1112    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1113            FLAG_PERMISSION_POLICY_FIXED
1114            | FLAG_PERMISSION_SYSTEM_FIXED
1115            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1116
1117    // And we back up these user-adjusted states
1118    private static final int USER_RUNTIME_GRANT_MASK =
1119            FLAG_PERMISSION_USER_SET
1120            | FLAG_PERMISSION_USER_FIXED
1121            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1122
1123    final @Nullable String mRequiredVerifierPackage;
1124    final @NonNull String mRequiredInstallerPackage;
1125    final @Nullable String mSetupWizardPackage;
1126    final @NonNull String mServicesSystemSharedLibraryPackageName;
1127    final @NonNull String mSharedSystemSharedLibraryPackageName;
1128
1129    private final PackageUsage mPackageUsage = new PackageUsage();
1130    private final CompilerStats mCompilerStats = new CompilerStats();
1131
1132    class PackageHandler extends Handler {
1133        private boolean mBound = false;
1134        final ArrayList<HandlerParams> mPendingInstalls =
1135            new ArrayList<HandlerParams>();
1136
1137        private boolean connectToService() {
1138            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1139                    " DefaultContainerService");
1140            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1141            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1142            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1143                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1144                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1145                mBound = true;
1146                return true;
1147            }
1148            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1149            return false;
1150        }
1151
1152        private void disconnectService() {
1153            mContainerService = null;
1154            mBound = false;
1155            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1156            mContext.unbindService(mDefContainerConn);
1157            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1158        }
1159
1160        PackageHandler(Looper looper) {
1161            super(looper);
1162        }
1163
1164        public void handleMessage(Message msg) {
1165            try {
1166                doHandleMessage(msg);
1167            } finally {
1168                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1169            }
1170        }
1171
1172        void doHandleMessage(Message msg) {
1173            switch (msg.what) {
1174                case INIT_COPY: {
1175                    HandlerParams params = (HandlerParams) msg.obj;
1176                    int idx = mPendingInstalls.size();
1177                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1178                    // If a bind was already initiated we dont really
1179                    // need to do anything. The pending install
1180                    // will be processed later on.
1181                    if (!mBound) {
1182                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1183                                System.identityHashCode(mHandler));
1184                        // If this is the only one pending we might
1185                        // have to bind to the service again.
1186                        if (!connectToService()) {
1187                            Slog.e(TAG, "Failed to bind to media container service");
1188                            params.serviceError();
1189                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1190                                    System.identityHashCode(mHandler));
1191                            if (params.traceMethod != null) {
1192                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1193                                        params.traceCookie);
1194                            }
1195                            return;
1196                        } else {
1197                            // Once we bind to the service, the first
1198                            // pending request will be processed.
1199                            mPendingInstalls.add(idx, params);
1200                        }
1201                    } else {
1202                        mPendingInstalls.add(idx, params);
1203                        // Already bound to the service. Just make
1204                        // sure we trigger off processing the first request.
1205                        if (idx == 0) {
1206                            mHandler.sendEmptyMessage(MCS_BOUND);
1207                        }
1208                    }
1209                    break;
1210                }
1211                case MCS_BOUND: {
1212                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1213                    if (msg.obj != null) {
1214                        mContainerService = (IMediaContainerService) msg.obj;
1215                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1216                                System.identityHashCode(mHandler));
1217                    }
1218                    if (mContainerService == null) {
1219                        if (!mBound) {
1220                            // Something seriously wrong since we are not bound and we are not
1221                            // waiting for connection. Bail out.
1222                            Slog.e(TAG, "Cannot bind to media container service");
1223                            for (HandlerParams params : mPendingInstalls) {
1224                                // Indicate service bind error
1225                                params.serviceError();
1226                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1227                                        System.identityHashCode(params));
1228                                if (params.traceMethod != null) {
1229                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1230                                            params.traceMethod, params.traceCookie);
1231                                }
1232                                return;
1233                            }
1234                            mPendingInstalls.clear();
1235                        } else {
1236                            Slog.w(TAG, "Waiting to connect to media container service");
1237                        }
1238                    } else if (mPendingInstalls.size() > 0) {
1239                        HandlerParams params = mPendingInstalls.get(0);
1240                        if (params != null) {
1241                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1242                                    System.identityHashCode(params));
1243                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1244                            if (params.startCopy()) {
1245                                // We are done...  look for more work or to
1246                                // go idle.
1247                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1248                                        "Checking for more work or unbind...");
1249                                // Delete pending install
1250                                if (mPendingInstalls.size() > 0) {
1251                                    mPendingInstalls.remove(0);
1252                                }
1253                                if (mPendingInstalls.size() == 0) {
1254                                    if (mBound) {
1255                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1256                                                "Posting delayed MCS_UNBIND");
1257                                        removeMessages(MCS_UNBIND);
1258                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1259                                        // Unbind after a little delay, to avoid
1260                                        // continual thrashing.
1261                                        sendMessageDelayed(ubmsg, 10000);
1262                                    }
1263                                } else {
1264                                    // There are more pending requests in queue.
1265                                    // Just post MCS_BOUND message to trigger processing
1266                                    // of next pending install.
1267                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1268                                            "Posting MCS_BOUND for next work");
1269                                    mHandler.sendEmptyMessage(MCS_BOUND);
1270                                }
1271                            }
1272                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1273                        }
1274                    } else {
1275                        // Should never happen ideally.
1276                        Slog.w(TAG, "Empty queue");
1277                    }
1278                    break;
1279                }
1280                case MCS_RECONNECT: {
1281                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1282                    if (mPendingInstalls.size() > 0) {
1283                        if (mBound) {
1284                            disconnectService();
1285                        }
1286                        if (!connectToService()) {
1287                            Slog.e(TAG, "Failed to bind to media container service");
1288                            for (HandlerParams params : mPendingInstalls) {
1289                                // Indicate service bind error
1290                                params.serviceError();
1291                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1292                                        System.identityHashCode(params));
1293                            }
1294                            mPendingInstalls.clear();
1295                        }
1296                    }
1297                    break;
1298                }
1299                case MCS_UNBIND: {
1300                    // If there is no actual work left, then time to unbind.
1301                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1302
1303                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1304                        if (mBound) {
1305                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1306
1307                            disconnectService();
1308                        }
1309                    } else if (mPendingInstalls.size() > 0) {
1310                        // There are more pending requests in queue.
1311                        // Just post MCS_BOUND message to trigger processing
1312                        // of next pending install.
1313                        mHandler.sendEmptyMessage(MCS_BOUND);
1314                    }
1315
1316                    break;
1317                }
1318                case MCS_GIVE_UP: {
1319                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1320                    HandlerParams params = mPendingInstalls.remove(0);
1321                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1322                            System.identityHashCode(params));
1323                    break;
1324                }
1325                case SEND_PENDING_BROADCAST: {
1326                    String packages[];
1327                    ArrayList<String> components[];
1328                    int size = 0;
1329                    int uids[];
1330                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1331                    synchronized (mPackages) {
1332                        if (mPendingBroadcasts == null) {
1333                            return;
1334                        }
1335                        size = mPendingBroadcasts.size();
1336                        if (size <= 0) {
1337                            // Nothing to be done. Just return
1338                            return;
1339                        }
1340                        packages = new String[size];
1341                        components = new ArrayList[size];
1342                        uids = new int[size];
1343                        int i = 0;  // filling out the above arrays
1344
1345                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1346                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1347                            Iterator<Map.Entry<String, ArrayList<String>>> it
1348                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1349                                            .entrySet().iterator();
1350                            while (it.hasNext() && i < size) {
1351                                Map.Entry<String, ArrayList<String>> ent = it.next();
1352                                packages[i] = ent.getKey();
1353                                components[i] = ent.getValue();
1354                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1355                                uids[i] = (ps != null)
1356                                        ? UserHandle.getUid(packageUserId, ps.appId)
1357                                        : -1;
1358                                i++;
1359                            }
1360                        }
1361                        size = i;
1362                        mPendingBroadcasts.clear();
1363                    }
1364                    // Send broadcasts
1365                    for (int i = 0; i < size; i++) {
1366                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1367                    }
1368                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1369                    break;
1370                }
1371                case START_CLEANING_PACKAGE: {
1372                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1373                    final String packageName = (String)msg.obj;
1374                    final int userId = msg.arg1;
1375                    final boolean andCode = msg.arg2 != 0;
1376                    synchronized (mPackages) {
1377                        if (userId == UserHandle.USER_ALL) {
1378                            int[] users = sUserManager.getUserIds();
1379                            for (int user : users) {
1380                                mSettings.addPackageToCleanLPw(
1381                                        new PackageCleanItem(user, packageName, andCode));
1382                            }
1383                        } else {
1384                            mSettings.addPackageToCleanLPw(
1385                                    new PackageCleanItem(userId, packageName, andCode));
1386                        }
1387                    }
1388                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1389                    startCleaningPackages();
1390                } break;
1391                case POST_INSTALL: {
1392                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1393
1394                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1395                    final boolean didRestore = (msg.arg2 != 0);
1396                    mRunningInstalls.delete(msg.arg1);
1397
1398                    if (data != null) {
1399                        InstallArgs args = data.args;
1400                        PackageInstalledInfo parentRes = data.res;
1401
1402                        final boolean grantPermissions = (args.installFlags
1403                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1404                        final boolean killApp = (args.installFlags
1405                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1406                        final String[] grantedPermissions = args.installGrantPermissions;
1407
1408                        // Handle the parent package
1409                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1410                                grantedPermissions, didRestore, args.installerPackageName,
1411                                args.observer);
1412
1413                        // Handle the child packages
1414                        final int childCount = (parentRes.addedChildPackages != null)
1415                                ? parentRes.addedChildPackages.size() : 0;
1416                        for (int i = 0; i < childCount; i++) {
1417                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1418                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1419                                    grantedPermissions, false, args.installerPackageName,
1420                                    args.observer);
1421                        }
1422
1423                        // Log tracing if needed
1424                        if (args.traceMethod != null) {
1425                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1426                                    args.traceCookie);
1427                        }
1428                    } else {
1429                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1430                    }
1431
1432                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1433                } break;
1434                case UPDATED_MEDIA_STATUS: {
1435                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1436                    boolean reportStatus = msg.arg1 == 1;
1437                    boolean doGc = msg.arg2 == 1;
1438                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1439                    if (doGc) {
1440                        // Force a gc to clear up stale containers.
1441                        Runtime.getRuntime().gc();
1442                    }
1443                    if (msg.obj != null) {
1444                        @SuppressWarnings("unchecked")
1445                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1446                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1447                        // Unload containers
1448                        unloadAllContainers(args);
1449                    }
1450                    if (reportStatus) {
1451                        try {
1452                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1453                            PackageHelper.getMountService().finishMediaUpdate();
1454                        } catch (RemoteException e) {
1455                            Log.e(TAG, "MountService not running?");
1456                        }
1457                    }
1458                } break;
1459                case WRITE_SETTINGS: {
1460                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1461                    synchronized (mPackages) {
1462                        removeMessages(WRITE_SETTINGS);
1463                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1464                        mSettings.writeLPr();
1465                        mDirtyUsers.clear();
1466                    }
1467                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1468                } break;
1469                case WRITE_PACKAGE_RESTRICTIONS: {
1470                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1471                    synchronized (mPackages) {
1472                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1473                        for (int userId : mDirtyUsers) {
1474                            mSettings.writePackageRestrictionsLPr(userId);
1475                        }
1476                        mDirtyUsers.clear();
1477                    }
1478                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1479                } break;
1480                case WRITE_PACKAGE_LIST: {
1481                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1482                    synchronized (mPackages) {
1483                        removeMessages(WRITE_PACKAGE_LIST);
1484                        mSettings.writePackageListLPr(msg.arg1);
1485                    }
1486                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1487                } break;
1488                case CHECK_PENDING_VERIFICATION: {
1489                    final int verificationId = msg.arg1;
1490                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1491
1492                    if ((state != null) && !state.timeoutExtended()) {
1493                        final InstallArgs args = state.getInstallArgs();
1494                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1495
1496                        Slog.i(TAG, "Verification timed out for " + originUri);
1497                        mPendingVerification.remove(verificationId);
1498
1499                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1500
1501                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1502                            Slog.i(TAG, "Continuing with installation of " + originUri);
1503                            state.setVerifierResponse(Binder.getCallingUid(),
1504                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1505                            broadcastPackageVerified(verificationId, originUri,
1506                                    PackageManager.VERIFICATION_ALLOW,
1507                                    state.getInstallArgs().getUser());
1508                            try {
1509                                ret = args.copyApk(mContainerService, true);
1510                            } catch (RemoteException e) {
1511                                Slog.e(TAG, "Could not contact the ContainerService");
1512                            }
1513                        } else {
1514                            broadcastPackageVerified(verificationId, originUri,
1515                                    PackageManager.VERIFICATION_REJECT,
1516                                    state.getInstallArgs().getUser());
1517                        }
1518
1519                        Trace.asyncTraceEnd(
1520                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1521
1522                        processPendingInstall(args, ret);
1523                        mHandler.sendEmptyMessage(MCS_UNBIND);
1524                    }
1525                    break;
1526                }
1527                case PACKAGE_VERIFIED: {
1528                    final int verificationId = msg.arg1;
1529
1530                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1531                    if (state == null) {
1532                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1533                        break;
1534                    }
1535
1536                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1537
1538                    state.setVerifierResponse(response.callerUid, response.code);
1539
1540                    if (state.isVerificationComplete()) {
1541                        mPendingVerification.remove(verificationId);
1542
1543                        final InstallArgs args = state.getInstallArgs();
1544                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1545
1546                        int ret;
1547                        if (state.isInstallAllowed()) {
1548                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1549                            broadcastPackageVerified(verificationId, originUri,
1550                                    response.code, state.getInstallArgs().getUser());
1551                            try {
1552                                ret = args.copyApk(mContainerService, true);
1553                            } catch (RemoteException e) {
1554                                Slog.e(TAG, "Could not contact the ContainerService");
1555                            }
1556                        } else {
1557                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1558                        }
1559
1560                        Trace.asyncTraceEnd(
1561                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1562
1563                        processPendingInstall(args, ret);
1564                        mHandler.sendEmptyMessage(MCS_UNBIND);
1565                    }
1566
1567                    break;
1568                }
1569                case START_INTENT_FILTER_VERIFICATIONS: {
1570                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1571                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1572                            params.replacing, params.pkg);
1573                    break;
1574                }
1575                case INTENT_FILTER_VERIFIED: {
1576                    final int verificationId = msg.arg1;
1577
1578                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1579                            verificationId);
1580                    if (state == null) {
1581                        Slog.w(TAG, "Invalid IntentFilter verification token "
1582                                + verificationId + " received");
1583                        break;
1584                    }
1585
1586                    final int userId = state.getUserId();
1587
1588                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1589                            "Processing IntentFilter verification with token:"
1590                            + verificationId + " and userId:" + userId);
1591
1592                    final IntentFilterVerificationResponse response =
1593                            (IntentFilterVerificationResponse) msg.obj;
1594
1595                    state.setVerifierResponse(response.callerUid, response.code);
1596
1597                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1598                            "IntentFilter verification with token:" + verificationId
1599                            + " and userId:" + userId
1600                            + " is settings verifier response with response code:"
1601                            + response.code);
1602
1603                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1604                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1605                                + response.getFailedDomainsString());
1606                    }
1607
1608                    if (state.isVerificationComplete()) {
1609                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1610                    } else {
1611                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1612                                "IntentFilter verification with token:" + verificationId
1613                                + " was not said to be complete");
1614                    }
1615
1616                    break;
1617                }
1618            }
1619        }
1620    }
1621
1622    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1623            boolean killApp, String[] grantedPermissions,
1624            boolean launchedForRestore, String installerPackage,
1625            IPackageInstallObserver2 installObserver) {
1626        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1627            // Send the removed broadcasts
1628            if (res.removedInfo != null) {
1629                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1630            }
1631
1632            // Now that we successfully installed the package, grant runtime
1633            // permissions if requested before broadcasting the install.
1634            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1635                    >= Build.VERSION_CODES.M) {
1636                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1637            }
1638
1639            final boolean update = res.removedInfo != null
1640                    && res.removedInfo.removedPackage != null;
1641
1642            // If this is the first time we have child packages for a disabled privileged
1643            // app that had no children, we grant requested runtime permissions to the new
1644            // children if the parent on the system image had them already granted.
1645            if (res.pkg.parentPackage != null) {
1646                synchronized (mPackages) {
1647                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1648                }
1649            }
1650
1651            synchronized (mPackages) {
1652                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1653            }
1654
1655            final String packageName = res.pkg.applicationInfo.packageName;
1656            Bundle extras = new Bundle(1);
1657            extras.putInt(Intent.EXTRA_UID, res.uid);
1658
1659            // Determine the set of users who are adding this package for
1660            // the first time vs. those who are seeing an update.
1661            int[] firstUsers = EMPTY_INT_ARRAY;
1662            int[] updateUsers = EMPTY_INT_ARRAY;
1663            if (res.origUsers == null || res.origUsers.length == 0) {
1664                firstUsers = res.newUsers;
1665            } else {
1666                for (int newUser : res.newUsers) {
1667                    boolean isNew = true;
1668                    for (int origUser : res.origUsers) {
1669                        if (origUser == newUser) {
1670                            isNew = false;
1671                            break;
1672                        }
1673                    }
1674                    if (isNew) {
1675                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1676                    } else {
1677                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1678                    }
1679                }
1680            }
1681
1682            // Send installed broadcasts if the install/update is not ephemeral
1683            if (!isEphemeral(res.pkg)) {
1684                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1685
1686                // Send added for users that see the package for the first time
1687                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1688                        extras, 0 /*flags*/, null /*targetPackage*/,
1689                        null /*finishedReceiver*/, firstUsers);
1690
1691                // Send added for users that don't see the package for the first time
1692                if (update) {
1693                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1694                }
1695                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1696                        extras, 0 /*flags*/, null /*targetPackage*/,
1697                        null /*finishedReceiver*/, updateUsers);
1698
1699                // Send replaced for users that don't see the package for the first time
1700                if (update) {
1701                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1702                            packageName, extras, 0 /*flags*/,
1703                            null /*targetPackage*/, null /*finishedReceiver*/,
1704                            updateUsers);
1705                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1706                            null /*package*/, null /*extras*/, 0 /*flags*/,
1707                            packageName /*targetPackage*/,
1708                            null /*finishedReceiver*/, updateUsers);
1709                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1710                    // First-install and we did a restore, so we're responsible for the
1711                    // first-launch broadcast.
1712                    if (DEBUG_BACKUP) {
1713                        Slog.i(TAG, "Post-restore of " + packageName
1714                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1715                    }
1716                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1717                }
1718
1719                // Send broadcast package appeared if forward locked/external for all users
1720                // treat asec-hosted packages like removable media on upgrade
1721                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1722                    if (DEBUG_INSTALL) {
1723                        Slog.i(TAG, "upgrading pkg " + res.pkg
1724                                + " is ASEC-hosted -> AVAILABLE");
1725                    }
1726                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1727                    ArrayList<String> pkgList = new ArrayList<>(1);
1728                    pkgList.add(packageName);
1729                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1730                }
1731            }
1732
1733            // Work that needs to happen on first install within each user
1734            if (firstUsers != null && firstUsers.length > 0) {
1735                synchronized (mPackages) {
1736                    for (int userId : firstUsers) {
1737                        // If this app is a browser and it's newly-installed for some
1738                        // users, clear any default-browser state in those users. The
1739                        // app's nature doesn't depend on the user, so we can just check
1740                        // its browser nature in any user and generalize.
1741                        if (packageIsBrowser(packageName, userId)) {
1742                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1743                        }
1744
1745                        // We may also need to apply pending (restored) runtime
1746                        // permission grants within these users.
1747                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1748                    }
1749                }
1750            }
1751
1752            // Log current value of "unknown sources" setting
1753            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1754                    getUnknownSourcesSettings());
1755
1756            // Force a gc to clear up things
1757            Runtime.getRuntime().gc();
1758
1759            // Remove the replaced package's older resources safely now
1760            // We delete after a gc for applications  on sdcard.
1761            if (res.removedInfo != null && res.removedInfo.args != null) {
1762                synchronized (mInstallLock) {
1763                    res.removedInfo.args.doPostDeleteLI(true);
1764                }
1765            }
1766        }
1767
1768        // If someone is watching installs - notify them
1769        if (installObserver != null) {
1770            try {
1771                Bundle extras = extrasForInstallResult(res);
1772                installObserver.onPackageInstalled(res.name, res.returnCode,
1773                        res.returnMsg, extras);
1774            } catch (RemoteException e) {
1775                Slog.i(TAG, "Observer no longer exists.");
1776            }
1777        }
1778    }
1779
1780    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1781            PackageParser.Package pkg) {
1782        if (pkg.parentPackage == null) {
1783            return;
1784        }
1785        if (pkg.requestedPermissions == null) {
1786            return;
1787        }
1788        final PackageSetting disabledSysParentPs = mSettings
1789                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1790        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1791                || !disabledSysParentPs.isPrivileged()
1792                || (disabledSysParentPs.childPackageNames != null
1793                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1794            return;
1795        }
1796        final int[] allUserIds = sUserManager.getUserIds();
1797        final int permCount = pkg.requestedPermissions.size();
1798        for (int i = 0; i < permCount; i++) {
1799            String permission = pkg.requestedPermissions.get(i);
1800            BasePermission bp = mSettings.mPermissions.get(permission);
1801            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1802                continue;
1803            }
1804            for (int userId : allUserIds) {
1805                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1806                        permission, userId)) {
1807                    grantRuntimePermission(pkg.packageName, permission, userId);
1808                }
1809            }
1810        }
1811    }
1812
1813    private StorageEventListener mStorageListener = new StorageEventListener() {
1814        @Override
1815        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1816            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1817                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1818                    final String volumeUuid = vol.getFsUuid();
1819
1820                    // Clean up any users or apps that were removed or recreated
1821                    // while this volume was missing
1822                    reconcileUsers(volumeUuid);
1823                    reconcileApps(volumeUuid);
1824
1825                    // Clean up any install sessions that expired or were
1826                    // cancelled while this volume was missing
1827                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1828
1829                    loadPrivatePackages(vol);
1830
1831                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1832                    unloadPrivatePackages(vol);
1833                }
1834            }
1835
1836            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1837                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1838                    updateExternalMediaStatus(true, false);
1839                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1840                    updateExternalMediaStatus(false, false);
1841                }
1842            }
1843        }
1844
1845        @Override
1846        public void onVolumeForgotten(String fsUuid) {
1847            if (TextUtils.isEmpty(fsUuid)) {
1848                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1849                return;
1850            }
1851
1852            // Remove any apps installed on the forgotten volume
1853            synchronized (mPackages) {
1854                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1855                for (PackageSetting ps : packages) {
1856                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1857                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1858                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1859                }
1860
1861                mSettings.onVolumeForgotten(fsUuid);
1862                mSettings.writeLPr();
1863            }
1864        }
1865    };
1866
1867    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1868            String[] grantedPermissions) {
1869        for (int userId : userIds) {
1870            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1871        }
1872
1873        // We could have touched GID membership, so flush out packages.list
1874        synchronized (mPackages) {
1875            mSettings.writePackageListLPr();
1876        }
1877    }
1878
1879    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1880            String[] grantedPermissions) {
1881        SettingBase sb = (SettingBase) pkg.mExtras;
1882        if (sb == null) {
1883            return;
1884        }
1885
1886        PermissionsState permissionsState = sb.getPermissionsState();
1887
1888        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1889                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1890
1891        for (String permission : pkg.requestedPermissions) {
1892            final BasePermission bp;
1893            synchronized (mPackages) {
1894                bp = mSettings.mPermissions.get(permission);
1895            }
1896            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1897                    && (grantedPermissions == null
1898                           || ArrayUtils.contains(grantedPermissions, permission))) {
1899                final int flags = permissionsState.getPermissionFlags(permission, userId);
1900                // Installer cannot change immutable permissions.
1901                if ((flags & immutableFlags) == 0) {
1902                    grantRuntimePermission(pkg.packageName, permission, userId);
1903                }
1904            }
1905        }
1906    }
1907
1908    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1909        Bundle extras = null;
1910        switch (res.returnCode) {
1911            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1912                extras = new Bundle();
1913                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1914                        res.origPermission);
1915                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1916                        res.origPackage);
1917                break;
1918            }
1919            case PackageManager.INSTALL_SUCCEEDED: {
1920                extras = new Bundle();
1921                extras.putBoolean(Intent.EXTRA_REPLACING,
1922                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1923                break;
1924            }
1925        }
1926        return extras;
1927    }
1928
1929    void scheduleWriteSettingsLocked() {
1930        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1931            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1932        }
1933    }
1934
1935    void scheduleWritePackageListLocked(int userId) {
1936        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1937            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1938            msg.arg1 = userId;
1939            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1940        }
1941    }
1942
1943    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1944        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1945        scheduleWritePackageRestrictionsLocked(userId);
1946    }
1947
1948    void scheduleWritePackageRestrictionsLocked(int userId) {
1949        final int[] userIds = (userId == UserHandle.USER_ALL)
1950                ? sUserManager.getUserIds() : new int[]{userId};
1951        for (int nextUserId : userIds) {
1952            if (!sUserManager.exists(nextUserId)) return;
1953            mDirtyUsers.add(nextUserId);
1954            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1955                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1956            }
1957        }
1958    }
1959
1960    public static PackageManagerService main(Context context, Installer installer,
1961            boolean factoryTest, boolean onlyCore) {
1962        // Self-check for initial settings.
1963        PackageManagerServiceCompilerMapping.checkProperties();
1964
1965        PackageManagerService m = new PackageManagerService(context, installer,
1966                factoryTest, onlyCore);
1967        m.enableSystemUserPackages();
1968        ServiceManager.addService("package", m);
1969        return m;
1970    }
1971
1972    private void enableSystemUserPackages() {
1973        if (!UserManager.isSplitSystemUser()) {
1974            return;
1975        }
1976        // For system user, enable apps based on the following conditions:
1977        // - app is whitelisted or belong to one of these groups:
1978        //   -- system app which has no launcher icons
1979        //   -- system app which has INTERACT_ACROSS_USERS permission
1980        //   -- system IME app
1981        // - app is not in the blacklist
1982        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1983        Set<String> enableApps = new ArraySet<>();
1984        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1985                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1986                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1987        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1988        enableApps.addAll(wlApps);
1989        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1990                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1991        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1992        enableApps.removeAll(blApps);
1993        Log.i(TAG, "Applications installed for system user: " + enableApps);
1994        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1995                UserHandle.SYSTEM);
1996        final int allAppsSize = allAps.size();
1997        synchronized (mPackages) {
1998            for (int i = 0; i < allAppsSize; i++) {
1999                String pName = allAps.get(i);
2000                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2001                // Should not happen, but we shouldn't be failing if it does
2002                if (pkgSetting == null) {
2003                    continue;
2004                }
2005                boolean install = enableApps.contains(pName);
2006                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2007                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2008                            + " for system user");
2009                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2010                }
2011            }
2012        }
2013    }
2014
2015    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2016        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2017                Context.DISPLAY_SERVICE);
2018        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2019    }
2020
2021    /**
2022     * Requests that files preopted on a secondary system partition be copied to the data partition
2023     * if possible.  Note that the actual copying of the files is accomplished by init for security
2024     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2025     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2026     */
2027    private static void requestCopyPreoptedFiles() {
2028        final int WAIT_TIME_MS = 100;
2029        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2030        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2031            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2032            // We will wait for up to 100 seconds.
2033            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2034            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2035                try {
2036                    Thread.sleep(WAIT_TIME_MS);
2037                } catch (InterruptedException e) {
2038                    // Do nothing
2039                }
2040                if (SystemClock.uptimeMillis() > timeEnd) {
2041                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2042                    Slog.wtf(TAG, "cppreopt did not finish!");
2043                    break;
2044                }
2045            }
2046        }
2047    }
2048
2049    public PackageManagerService(Context context, Installer installer,
2050            boolean factoryTest, boolean onlyCore) {
2051        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2052                SystemClock.uptimeMillis());
2053
2054        if (mSdkVersion <= 0) {
2055            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2056        }
2057
2058        mContext = context;
2059        mFactoryTest = factoryTest;
2060        mOnlyCore = onlyCore;
2061        mMetrics = new DisplayMetrics();
2062        mSettings = new Settings(mPackages);
2063        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2064                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2065        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2066                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2067        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2068                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2069        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2070                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2071        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2072                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2073        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2074                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2075
2076        String separateProcesses = SystemProperties.get("debug.separate_processes");
2077        if (separateProcesses != null && separateProcesses.length() > 0) {
2078            if ("*".equals(separateProcesses)) {
2079                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2080                mSeparateProcesses = null;
2081                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2082            } else {
2083                mDefParseFlags = 0;
2084                mSeparateProcesses = separateProcesses.split(",");
2085                Slog.w(TAG, "Running with debug.separate_processes: "
2086                        + separateProcesses);
2087            }
2088        } else {
2089            mDefParseFlags = 0;
2090            mSeparateProcesses = null;
2091        }
2092
2093        mInstaller = installer;
2094        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2095                "*dexopt*");
2096        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2097
2098        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2099                FgThread.get().getLooper());
2100
2101        getDefaultDisplayMetrics(context, mMetrics);
2102
2103        SystemConfig systemConfig = SystemConfig.getInstance();
2104        mGlobalGids = systemConfig.getGlobalGids();
2105        mSystemPermissions = systemConfig.getSystemPermissions();
2106        mAvailableFeatures = systemConfig.getAvailableFeatures();
2107
2108        mProtectedPackages = new ProtectedPackages(mContext);
2109
2110        synchronized (mInstallLock) {
2111        // writer
2112        synchronized (mPackages) {
2113            mHandlerThread = new ServiceThread(TAG,
2114                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2115            mHandlerThread.start();
2116            mHandler = new PackageHandler(mHandlerThread.getLooper());
2117            mProcessLoggingHandler = new ProcessLoggingHandler();
2118            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2119
2120            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2121
2122            File dataDir = Environment.getDataDirectory();
2123            mAppInstallDir = new File(dataDir, "app");
2124            mAppLib32InstallDir = new File(dataDir, "app-lib");
2125            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2126            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2127            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2128
2129            sUserManager = new UserManagerService(context, this, mPackages);
2130
2131            // Propagate permission configuration in to package manager.
2132            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2133                    = systemConfig.getPermissions();
2134            for (int i=0; i<permConfig.size(); i++) {
2135                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2136                BasePermission bp = mSettings.mPermissions.get(perm.name);
2137                if (bp == null) {
2138                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2139                    mSettings.mPermissions.put(perm.name, bp);
2140                }
2141                if (perm.gids != null) {
2142                    bp.setGids(perm.gids, perm.perUser);
2143                }
2144            }
2145
2146            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2147            for (int i=0; i<libConfig.size(); i++) {
2148                mSharedLibraries.put(libConfig.keyAt(i),
2149                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2150            }
2151
2152            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2153
2154            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2155
2156            if (mFirstBoot) {
2157                requestCopyPreoptedFiles();
2158            }
2159
2160            String customResolverActivity = Resources.getSystem().getString(
2161                    R.string.config_customResolverActivity);
2162            if (TextUtils.isEmpty(customResolverActivity)) {
2163                customResolverActivity = null;
2164            } else {
2165                mCustomResolverComponentName = ComponentName.unflattenFromString(
2166                        customResolverActivity);
2167            }
2168
2169            long startTime = SystemClock.uptimeMillis();
2170
2171            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2172                    startTime);
2173
2174            // Set flag to monitor and not change apk file paths when
2175            // scanning install directories.
2176            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2177
2178            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2179            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2180
2181            if (bootClassPath == null) {
2182                Slog.w(TAG, "No BOOTCLASSPATH found!");
2183            }
2184
2185            if (systemServerClassPath == null) {
2186                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2187            }
2188
2189            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2190            final String[] dexCodeInstructionSets =
2191                    getDexCodeInstructionSets(
2192                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2193
2194            /**
2195             * Ensure all external libraries have had dexopt run on them.
2196             */
2197            if (mSharedLibraries.size() > 0) {
2198                // NOTE: For now, we're compiling these system "shared libraries"
2199                // (and framework jars) into all available architectures. It's possible
2200                // to compile them only when we come across an app that uses them (there's
2201                // already logic for that in scanPackageLI) but that adds some complexity.
2202                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2203                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2204                        final String lib = libEntry.path;
2205                        if (lib == null) {
2206                            continue;
2207                        }
2208
2209                        try {
2210                            // Shared libraries do not have profiles so we perform a full
2211                            // AOT compilation (if needed).
2212                            int dexoptNeeded = DexFile.getDexOptNeeded(
2213                                    lib, dexCodeInstructionSet,
2214                                    getCompilerFilterForReason(REASON_SHARED_APK),
2215                                    false /* newProfile */);
2216                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2217                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2218                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2219                                        getCompilerFilterForReason(REASON_SHARED_APK),
2220                                        StorageManager.UUID_PRIVATE_INTERNAL,
2221                                        SKIP_SHARED_LIBRARY_CHECK);
2222                            }
2223                        } catch (FileNotFoundException e) {
2224                            Slog.w(TAG, "Library not found: " + lib);
2225                        } catch (IOException | InstallerException e) {
2226                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2227                                    + e.getMessage());
2228                        }
2229                    }
2230                }
2231            }
2232
2233            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2234
2235            final VersionInfo ver = mSettings.getInternalVersion();
2236            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2237
2238            // when upgrading from pre-M, promote system app permissions from install to runtime
2239            mPromoteSystemApps =
2240                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2241
2242            // When upgrading from pre-N, we need to handle package extraction like first boot,
2243            // as there is no profiling data available.
2244            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2245
2246            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2247
2248            // save off the names of pre-existing system packages prior to scanning; we don't
2249            // want to automatically grant runtime permissions for new system apps
2250            if (mPromoteSystemApps) {
2251                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2252                while (pkgSettingIter.hasNext()) {
2253                    PackageSetting ps = pkgSettingIter.next();
2254                    if (isSystemApp(ps)) {
2255                        mExistingSystemPackages.add(ps.name);
2256                    }
2257                }
2258            }
2259
2260            // Collect vendor overlay packages.
2261            // (Do this before scanning any apps.)
2262            // For security and version matching reason, only consider
2263            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2264            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2265            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2266                    | PackageParser.PARSE_IS_SYSTEM
2267                    | PackageParser.PARSE_IS_SYSTEM_DIR
2268                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2269
2270            // Find base frameworks (resource packages without code).
2271            scanDirTracedLI(frameworkDir, mDefParseFlags
2272                    | PackageParser.PARSE_IS_SYSTEM
2273                    | PackageParser.PARSE_IS_SYSTEM_DIR
2274                    | PackageParser.PARSE_IS_PRIVILEGED,
2275                    scanFlags | SCAN_NO_DEX, 0);
2276
2277            // Collected privileged system packages.
2278            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2279            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2280                    | PackageParser.PARSE_IS_SYSTEM
2281                    | PackageParser.PARSE_IS_SYSTEM_DIR
2282                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2283
2284            // Collect ordinary system packages.
2285            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2286            scanDirTracedLI(systemAppDir, mDefParseFlags
2287                    | PackageParser.PARSE_IS_SYSTEM
2288                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2289
2290            // Collect all vendor packages.
2291            File vendorAppDir = new File("/vendor/app");
2292            try {
2293                vendorAppDir = vendorAppDir.getCanonicalFile();
2294            } catch (IOException e) {
2295                // failed to look up canonical path, continue with original one
2296            }
2297            scanDirTracedLI(vendorAppDir, mDefParseFlags
2298                    | PackageParser.PARSE_IS_SYSTEM
2299                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2300
2301            // Collect all OEM packages.
2302            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2303            scanDirTracedLI(oemAppDir, mDefParseFlags
2304                    | PackageParser.PARSE_IS_SYSTEM
2305                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2306
2307            // Prune any system packages that no longer exist.
2308            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2309            if (!mOnlyCore) {
2310                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2311                while (psit.hasNext()) {
2312                    PackageSetting ps = psit.next();
2313
2314                    /*
2315                     * If this is not a system app, it can't be a
2316                     * disable system app.
2317                     */
2318                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2319                        continue;
2320                    }
2321
2322                    /*
2323                     * If the package is scanned, it's not erased.
2324                     */
2325                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2326                    if (scannedPkg != null) {
2327                        /*
2328                         * If the system app is both scanned and in the
2329                         * disabled packages list, then it must have been
2330                         * added via OTA. Remove it from the currently
2331                         * scanned package so the previously user-installed
2332                         * application can be scanned.
2333                         */
2334                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2335                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2336                                    + ps.name + "; removing system app.  Last known codePath="
2337                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2338                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2339                                    + scannedPkg.mVersionCode);
2340                            removePackageLI(scannedPkg, true);
2341                            mExpectingBetter.put(ps.name, ps.codePath);
2342                        }
2343
2344                        continue;
2345                    }
2346
2347                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2348                        psit.remove();
2349                        logCriticalInfo(Log.WARN, "System package " + ps.name
2350                                + " no longer exists; it's data will be wiped");
2351                        // Actual deletion of code and data will be handled by later
2352                        // reconciliation step
2353                    } else {
2354                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2355                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2356                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2357                        }
2358                    }
2359                }
2360            }
2361
2362            //look for any incomplete package installations
2363            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2364            for (int i = 0; i < deletePkgsList.size(); i++) {
2365                // Actual deletion of code and data will be handled by later
2366                // reconciliation step
2367                final String packageName = deletePkgsList.get(i).name;
2368                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2369                synchronized (mPackages) {
2370                    mSettings.removePackageLPw(packageName);
2371                }
2372            }
2373
2374            //delete tmp files
2375            deleteTempPackageFiles();
2376
2377            // Remove any shared userIDs that have no associated packages
2378            mSettings.pruneSharedUsersLPw();
2379
2380            if (!mOnlyCore) {
2381                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2382                        SystemClock.uptimeMillis());
2383                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2384
2385                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2386                        | PackageParser.PARSE_FORWARD_LOCK,
2387                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2388
2389                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2390                        | PackageParser.PARSE_IS_EPHEMERAL,
2391                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2392
2393                /**
2394                 * Remove disable package settings for any updated system
2395                 * apps that were removed via an OTA. If they're not a
2396                 * previously-updated app, remove them completely.
2397                 * Otherwise, just revoke their system-level permissions.
2398                 */
2399                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2400                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2401                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2402
2403                    String msg;
2404                    if (deletedPkg == null) {
2405                        msg = "Updated system package " + deletedAppName
2406                                + " no longer exists; it's data will be wiped";
2407                        // Actual deletion of code and data will be handled by later
2408                        // reconciliation step
2409                    } else {
2410                        msg = "Updated system app + " + deletedAppName
2411                                + " no longer present; removing system privileges for "
2412                                + deletedAppName;
2413
2414                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2415
2416                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2417                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2418                    }
2419                    logCriticalInfo(Log.WARN, msg);
2420                }
2421
2422                /**
2423                 * Make sure all system apps that we expected to appear on
2424                 * the userdata partition actually showed up. If they never
2425                 * appeared, crawl back and revive the system version.
2426                 */
2427                for (int i = 0; i < mExpectingBetter.size(); i++) {
2428                    final String packageName = mExpectingBetter.keyAt(i);
2429                    if (!mPackages.containsKey(packageName)) {
2430                        final File scanFile = mExpectingBetter.valueAt(i);
2431
2432                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2433                                + " but never showed up; reverting to system");
2434
2435                        int reparseFlags = mDefParseFlags;
2436                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2437                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2438                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2439                                    | PackageParser.PARSE_IS_PRIVILEGED;
2440                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2441                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2442                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2443                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2444                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2445                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2446                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2447                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2448                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2449                        } else {
2450                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2451                            continue;
2452                        }
2453
2454                        mSettings.enableSystemPackageLPw(packageName);
2455
2456                        try {
2457                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2458                        } catch (PackageManagerException e) {
2459                            Slog.e(TAG, "Failed to parse original system package: "
2460                                    + e.getMessage());
2461                        }
2462                    }
2463                }
2464            }
2465            mExpectingBetter.clear();
2466
2467            // Resolve protected action filters. Only the setup wizard is allowed to
2468            // have a high priority filter for these actions.
2469            mSetupWizardPackage = getSetupWizardPackageName();
2470            if (mProtectedFilters.size() > 0) {
2471                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2472                    Slog.i(TAG, "No setup wizard;"
2473                        + " All protected intents capped to priority 0");
2474                }
2475                for (ActivityIntentInfo filter : mProtectedFilters) {
2476                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2477                        if (DEBUG_FILTERS) {
2478                            Slog.i(TAG, "Found setup wizard;"
2479                                + " allow priority " + filter.getPriority() + ";"
2480                                + " package: " + filter.activity.info.packageName
2481                                + " activity: " + filter.activity.className
2482                                + " priority: " + filter.getPriority());
2483                        }
2484                        // skip setup wizard; allow it to keep the high priority filter
2485                        continue;
2486                    }
2487                    Slog.w(TAG, "Protected action; cap priority to 0;"
2488                            + " package: " + filter.activity.info.packageName
2489                            + " activity: " + filter.activity.className
2490                            + " origPrio: " + filter.getPriority());
2491                    filter.setPriority(0);
2492                }
2493            }
2494            mDeferProtectedFilters = false;
2495            mProtectedFilters.clear();
2496
2497            // Now that we know all of the shared libraries, update all clients to have
2498            // the correct library paths.
2499            updateAllSharedLibrariesLPw();
2500
2501            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2502                // NOTE: We ignore potential failures here during a system scan (like
2503                // the rest of the commands above) because there's precious little we
2504                // can do about it. A settings error is reported, though.
2505                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2506                        false /* boot complete */);
2507            }
2508
2509            // Now that we know all the packages we are keeping,
2510            // read and update their last usage times.
2511            mPackageUsage.read(mPackages);
2512            mCompilerStats.read();
2513
2514            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2515                    SystemClock.uptimeMillis());
2516            Slog.i(TAG, "Time to scan packages: "
2517                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2518                    + " seconds");
2519
2520            // If the platform SDK has changed since the last time we booted,
2521            // we need to re-grant app permission to catch any new ones that
2522            // appear.  This is really a hack, and means that apps can in some
2523            // cases get permissions that the user didn't initially explicitly
2524            // allow...  it would be nice to have some better way to handle
2525            // this situation.
2526            int updateFlags = UPDATE_PERMISSIONS_ALL;
2527            if (ver.sdkVersion != mSdkVersion) {
2528                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2529                        + mSdkVersion + "; regranting permissions for internal storage");
2530                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2531            }
2532            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2533            ver.sdkVersion = mSdkVersion;
2534
2535            // If this is the first boot or an update from pre-M, and it is a normal
2536            // boot, then we need to initialize the default preferred apps across
2537            // all defined users.
2538            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2539                for (UserInfo user : sUserManager.getUsers(true)) {
2540                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2541                    applyFactoryDefaultBrowserLPw(user.id);
2542                    primeDomainVerificationsLPw(user.id);
2543                }
2544            }
2545
2546            // Prepare storage for system user really early during boot,
2547            // since core system apps like SettingsProvider and SystemUI
2548            // can't wait for user to start
2549            final int storageFlags;
2550            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2551                storageFlags = StorageManager.FLAG_STORAGE_DE;
2552            } else {
2553                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2554            }
2555            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2556                    storageFlags);
2557
2558            // If this is first boot after an OTA, and a normal boot, then
2559            // we need to clear code cache directories.
2560            // Note that we do *not* clear the application profiles. These remain valid
2561            // across OTAs and are used to drive profile verification (post OTA) and
2562            // profile compilation (without waiting to collect a fresh set of profiles).
2563            if (mIsUpgrade && !onlyCore) {
2564                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2565                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2566                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2567                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2568                        // No apps are running this early, so no need to freeze
2569                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2570                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2571                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2572                    }
2573                }
2574                ver.fingerprint = Build.FINGERPRINT;
2575            }
2576
2577            checkDefaultBrowser();
2578
2579            // clear only after permissions and other defaults have been updated
2580            mExistingSystemPackages.clear();
2581            mPromoteSystemApps = false;
2582
2583            // All the changes are done during package scanning.
2584            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2585
2586            // can downgrade to reader
2587            mSettings.writeLPr();
2588
2589            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2590            // early on (before the package manager declares itself as early) because other
2591            // components in the system server might ask for package contexts for these apps.
2592            //
2593            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2594            // (i.e, that the data partition is unavailable).
2595            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2596                long start = System.nanoTime();
2597                List<PackageParser.Package> coreApps = new ArrayList<>();
2598                for (PackageParser.Package pkg : mPackages.values()) {
2599                    if (pkg.coreApp) {
2600                        coreApps.add(pkg);
2601                    }
2602                }
2603
2604                int[] stats = performDexOptUpgrade(coreApps, false,
2605                        getCompilerFilterForReason(REASON_CORE_APP));
2606
2607                final int elapsedTimeSeconds =
2608                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2609                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2610
2611                if (DEBUG_DEXOPT) {
2612                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2613                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2614                }
2615
2616
2617                // TODO: Should we log these stats to tron too ?
2618                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2619                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2620                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2621                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2622            }
2623
2624            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2625                    SystemClock.uptimeMillis());
2626
2627            if (!mOnlyCore) {
2628                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2629                mRequiredInstallerPackage = getRequiredInstallerLPr();
2630                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2631                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2632                        mIntentFilterVerifierComponent);
2633                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2634                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2635                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2636                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2637            } else {
2638                mRequiredVerifierPackage = null;
2639                mRequiredInstallerPackage = null;
2640                mIntentFilterVerifierComponent = null;
2641                mIntentFilterVerifier = null;
2642                mServicesSystemSharedLibraryPackageName = null;
2643                mSharedSystemSharedLibraryPackageName = null;
2644            }
2645
2646            mInstallerService = new PackageInstallerService(context, this);
2647
2648            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2649            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2650            // both the installer and resolver must be present to enable ephemeral
2651            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2652                if (DEBUG_EPHEMERAL) {
2653                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2654                            + " installer:" + ephemeralInstallerComponent);
2655                }
2656                mEphemeralResolverComponent = ephemeralResolverComponent;
2657                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2658                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2659                mEphemeralResolverConnection =
2660                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2661            } else {
2662                if (DEBUG_EPHEMERAL) {
2663                    final String missingComponent =
2664                            (ephemeralResolverComponent == null)
2665                            ? (ephemeralInstallerComponent == null)
2666                                    ? "resolver and installer"
2667                                    : "resolver"
2668                            : "installer";
2669                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2670                }
2671                mEphemeralResolverComponent = null;
2672                mEphemeralInstallerComponent = null;
2673                mEphemeralResolverConnection = null;
2674            }
2675
2676            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2677        } // synchronized (mPackages)
2678        } // synchronized (mInstallLock)
2679
2680        // Now after opening every single application zip, make sure they
2681        // are all flushed.  Not really needed, but keeps things nice and
2682        // tidy.
2683        Runtime.getRuntime().gc();
2684
2685        // The initial scanning above does many calls into installd while
2686        // holding the mPackages lock, but we're mostly interested in yelling
2687        // once we have a booted system.
2688        mInstaller.setWarnIfHeld(mPackages);
2689
2690        // Expose private service for system components to use.
2691        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2692    }
2693
2694    @Override
2695    public boolean isFirstBoot() {
2696        return mFirstBoot;
2697    }
2698
2699    @Override
2700    public boolean isOnlyCoreApps() {
2701        return mOnlyCore;
2702    }
2703
2704    @Override
2705    public boolean isUpgrade() {
2706        return mIsUpgrade;
2707    }
2708
2709    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2710        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2711
2712        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2713                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2714                UserHandle.USER_SYSTEM);
2715        if (matches.size() == 1) {
2716            return matches.get(0).getComponentInfo().packageName;
2717        } else {
2718            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2719            return null;
2720        }
2721    }
2722
2723    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2724        synchronized (mPackages) {
2725            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2726            if (libraryEntry == null) {
2727                throw new IllegalStateException("Missing required shared library:" + libraryName);
2728            }
2729            return libraryEntry.apk;
2730        }
2731    }
2732
2733    private @NonNull String getRequiredInstallerLPr() {
2734        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2735        intent.addCategory(Intent.CATEGORY_DEFAULT);
2736        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2737
2738        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2739                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2740                UserHandle.USER_SYSTEM);
2741        if (matches.size() == 1) {
2742            ResolveInfo resolveInfo = matches.get(0);
2743            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2744                throw new RuntimeException("The installer must be a privileged app");
2745            }
2746            return matches.get(0).getComponentInfo().packageName;
2747        } else {
2748            throw new RuntimeException("There must be exactly one installer; found " + matches);
2749        }
2750    }
2751
2752    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2753        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2754
2755        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2756                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2757                UserHandle.USER_SYSTEM);
2758        ResolveInfo best = null;
2759        final int N = matches.size();
2760        for (int i = 0; i < N; i++) {
2761            final ResolveInfo cur = matches.get(i);
2762            final String packageName = cur.getComponentInfo().packageName;
2763            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2764                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2765                continue;
2766            }
2767
2768            if (best == null || cur.priority > best.priority) {
2769                best = cur;
2770            }
2771        }
2772
2773        if (best != null) {
2774            return best.getComponentInfo().getComponentName();
2775        } else {
2776            throw new RuntimeException("There must be at least one intent filter verifier");
2777        }
2778    }
2779
2780    private @Nullable ComponentName getEphemeralResolverLPr() {
2781        final String[] packageArray =
2782                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2783        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2784            if (DEBUG_EPHEMERAL) {
2785                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2786            }
2787            return null;
2788        }
2789
2790        final int resolveFlags =
2791                MATCH_DIRECT_BOOT_AWARE
2792                | MATCH_DIRECT_BOOT_UNAWARE
2793                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2794        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2795        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2796                resolveFlags, UserHandle.USER_SYSTEM);
2797
2798        final int N = resolvers.size();
2799        if (N == 0) {
2800            if (DEBUG_EPHEMERAL) {
2801                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2802            }
2803            return null;
2804        }
2805
2806        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2807        for (int i = 0; i < N; i++) {
2808            final ResolveInfo info = resolvers.get(i);
2809
2810            if (info.serviceInfo == null) {
2811                continue;
2812            }
2813
2814            final String packageName = info.serviceInfo.packageName;
2815            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2816                if (DEBUG_EPHEMERAL) {
2817                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2818                            + " pkg: " + packageName + ", info:" + info);
2819                }
2820                continue;
2821            }
2822
2823            if (DEBUG_EPHEMERAL) {
2824                Slog.v(TAG, "Ephemeral resolver found;"
2825                        + " pkg: " + packageName + ", info:" + info);
2826            }
2827            return new ComponentName(packageName, info.serviceInfo.name);
2828        }
2829        if (DEBUG_EPHEMERAL) {
2830            Slog.v(TAG, "Ephemeral resolver NOT found");
2831        }
2832        return null;
2833    }
2834
2835    private @Nullable ComponentName getEphemeralInstallerLPr() {
2836        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2837        intent.addCategory(Intent.CATEGORY_DEFAULT);
2838        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2839
2840        final int resolveFlags =
2841                MATCH_DIRECT_BOOT_AWARE
2842                | MATCH_DIRECT_BOOT_UNAWARE
2843                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2844        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2845                resolveFlags, UserHandle.USER_SYSTEM);
2846        if (matches.size() == 0) {
2847            return null;
2848        } else if (matches.size() == 1) {
2849            return matches.get(0).getComponentInfo().getComponentName();
2850        } else {
2851            throw new RuntimeException(
2852                    "There must be at most one ephemeral installer; found " + matches);
2853        }
2854    }
2855
2856    private void primeDomainVerificationsLPw(int userId) {
2857        if (DEBUG_DOMAIN_VERIFICATION) {
2858            Slog.d(TAG, "Priming domain verifications in user " + userId);
2859        }
2860
2861        SystemConfig systemConfig = SystemConfig.getInstance();
2862        ArraySet<String> packages = systemConfig.getLinkedApps();
2863        ArraySet<String> domains = new ArraySet<String>();
2864
2865        for (String packageName : packages) {
2866            PackageParser.Package pkg = mPackages.get(packageName);
2867            if (pkg != null) {
2868                if (!pkg.isSystemApp()) {
2869                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2870                    continue;
2871                }
2872
2873                domains.clear();
2874                for (PackageParser.Activity a : pkg.activities) {
2875                    for (ActivityIntentInfo filter : a.intents) {
2876                        if (hasValidDomains(filter)) {
2877                            domains.addAll(filter.getHostsList());
2878                        }
2879                    }
2880                }
2881
2882                if (domains.size() > 0) {
2883                    if (DEBUG_DOMAIN_VERIFICATION) {
2884                        Slog.v(TAG, "      + " + packageName);
2885                    }
2886                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2887                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2888                    // and then 'always' in the per-user state actually used for intent resolution.
2889                    final IntentFilterVerificationInfo ivi;
2890                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2891                            new ArrayList<String>(domains));
2892                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2893                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2894                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2895                } else {
2896                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2897                            + "' does not handle web links");
2898                }
2899            } else {
2900                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2901            }
2902        }
2903
2904        scheduleWritePackageRestrictionsLocked(userId);
2905        scheduleWriteSettingsLocked();
2906    }
2907
2908    private void applyFactoryDefaultBrowserLPw(int userId) {
2909        // The default browser app's package name is stored in a string resource,
2910        // with a product-specific overlay used for vendor customization.
2911        String browserPkg = mContext.getResources().getString(
2912                com.android.internal.R.string.default_browser);
2913        if (!TextUtils.isEmpty(browserPkg)) {
2914            // non-empty string => required to be a known package
2915            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2916            if (ps == null) {
2917                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2918                browserPkg = null;
2919            } else {
2920                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2921            }
2922        }
2923
2924        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2925        // default.  If there's more than one, just leave everything alone.
2926        if (browserPkg == null) {
2927            calculateDefaultBrowserLPw(userId);
2928        }
2929    }
2930
2931    private void calculateDefaultBrowserLPw(int userId) {
2932        List<String> allBrowsers = resolveAllBrowserApps(userId);
2933        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2934        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2935    }
2936
2937    private List<String> resolveAllBrowserApps(int userId) {
2938        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2939        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2940                PackageManager.MATCH_ALL, userId);
2941
2942        final int count = list.size();
2943        List<String> result = new ArrayList<String>(count);
2944        for (int i=0; i<count; i++) {
2945            ResolveInfo info = list.get(i);
2946            if (info.activityInfo == null
2947                    || !info.handleAllWebDataURI
2948                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2949                    || result.contains(info.activityInfo.packageName)) {
2950                continue;
2951            }
2952            result.add(info.activityInfo.packageName);
2953        }
2954
2955        return result;
2956    }
2957
2958    private boolean packageIsBrowser(String packageName, int userId) {
2959        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2960                PackageManager.MATCH_ALL, userId);
2961        final int N = list.size();
2962        for (int i = 0; i < N; i++) {
2963            ResolveInfo info = list.get(i);
2964            if (packageName.equals(info.activityInfo.packageName)) {
2965                return true;
2966            }
2967        }
2968        return false;
2969    }
2970
2971    private void checkDefaultBrowser() {
2972        final int myUserId = UserHandle.myUserId();
2973        final String packageName = getDefaultBrowserPackageName(myUserId);
2974        if (packageName != null) {
2975            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2976            if (info == null) {
2977                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2978                synchronized (mPackages) {
2979                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2980                }
2981            }
2982        }
2983    }
2984
2985    @Override
2986    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2987            throws RemoteException {
2988        try {
2989            return super.onTransact(code, data, reply, flags);
2990        } catch (RuntimeException e) {
2991            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2992                Slog.wtf(TAG, "Package Manager Crash", e);
2993            }
2994            throw e;
2995        }
2996    }
2997
2998    static int[] appendInts(int[] cur, int[] add) {
2999        if (add == null) return cur;
3000        if (cur == null) return add;
3001        final int N = add.length;
3002        for (int i=0; i<N; i++) {
3003            cur = appendInt(cur, add[i]);
3004        }
3005        return cur;
3006    }
3007
3008    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3009        if (!sUserManager.exists(userId)) return null;
3010        if (ps == null) {
3011            return null;
3012        }
3013        final PackageParser.Package p = ps.pkg;
3014        if (p == null) {
3015            return null;
3016        }
3017
3018        final PermissionsState permissionsState = ps.getPermissionsState();
3019
3020        // Compute GIDs only if requested
3021        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3022                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3023        // Compute granted permissions only if package has requested permissions
3024        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3025                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3026        final PackageUserState state = ps.readUserState(userId);
3027
3028        return PackageParser.generatePackageInfo(p, gids, flags,
3029                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3030    }
3031
3032    @Override
3033    public void checkPackageStartable(String packageName, int userId) {
3034        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3035
3036        synchronized (mPackages) {
3037            final PackageSetting ps = mSettings.mPackages.get(packageName);
3038            if (ps == null) {
3039                throw new SecurityException("Package " + packageName + " was not found!");
3040            }
3041
3042            if (!ps.getInstalled(userId)) {
3043                throw new SecurityException(
3044                        "Package " + packageName + " was not installed for user " + userId + "!");
3045            }
3046
3047            if (mSafeMode && !ps.isSystem()) {
3048                throw new SecurityException("Package " + packageName + " not a system app!");
3049            }
3050
3051            if (mFrozenPackages.contains(packageName)) {
3052                throw new SecurityException("Package " + packageName + " is currently frozen!");
3053            }
3054
3055            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3056                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3057                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3058            }
3059        }
3060    }
3061
3062    @Override
3063    public boolean isPackageAvailable(String packageName, int userId) {
3064        if (!sUserManager.exists(userId)) return false;
3065        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3066                false /* requireFullPermission */, false /* checkShell */, "is package available");
3067        synchronized (mPackages) {
3068            PackageParser.Package p = mPackages.get(packageName);
3069            if (p != null) {
3070                final PackageSetting ps = (PackageSetting) p.mExtras;
3071                if (ps != null) {
3072                    final PackageUserState state = ps.readUserState(userId);
3073                    if (state != null) {
3074                        return PackageParser.isAvailable(state);
3075                    }
3076                }
3077            }
3078        }
3079        return false;
3080    }
3081
3082    @Override
3083    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3084        if (!sUserManager.exists(userId)) return null;
3085        flags = updateFlagsForPackage(flags, userId, packageName);
3086        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3087                false /* requireFullPermission */, false /* checkShell */, "get package info");
3088        // reader
3089        synchronized (mPackages) {
3090            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3091            PackageParser.Package p = null;
3092            if (matchFactoryOnly) {
3093                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3094                if (ps != null) {
3095                    return generatePackageInfo(ps, flags, userId);
3096                }
3097            }
3098            if (p == null) {
3099                p = mPackages.get(packageName);
3100                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3101                    return null;
3102                }
3103            }
3104            if (DEBUG_PACKAGE_INFO)
3105                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3106            if (p != null) {
3107                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3108            }
3109            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3110                final PackageSetting ps = mSettings.mPackages.get(packageName);
3111                return generatePackageInfo(ps, flags, userId);
3112            }
3113        }
3114        return null;
3115    }
3116
3117    @Override
3118    public String[] currentToCanonicalPackageNames(String[] names) {
3119        String[] out = new String[names.length];
3120        // reader
3121        synchronized (mPackages) {
3122            for (int i=names.length-1; i>=0; i--) {
3123                PackageSetting ps = mSettings.mPackages.get(names[i]);
3124                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3125            }
3126        }
3127        return out;
3128    }
3129
3130    @Override
3131    public String[] canonicalToCurrentPackageNames(String[] names) {
3132        String[] out = new String[names.length];
3133        // reader
3134        synchronized (mPackages) {
3135            for (int i=names.length-1; i>=0; i--) {
3136                String cur = mSettings.mRenamedPackages.get(names[i]);
3137                out[i] = cur != null ? cur : names[i];
3138            }
3139        }
3140        return out;
3141    }
3142
3143    @Override
3144    public int getPackageUid(String packageName, int flags, int userId) {
3145        if (!sUserManager.exists(userId)) return -1;
3146        flags = updateFlagsForPackage(flags, userId, packageName);
3147        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3148                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3149
3150        // reader
3151        synchronized (mPackages) {
3152            final PackageParser.Package p = mPackages.get(packageName);
3153            if (p != null && p.isMatch(flags)) {
3154                return UserHandle.getUid(userId, p.applicationInfo.uid);
3155            }
3156            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3157                final PackageSetting ps = mSettings.mPackages.get(packageName);
3158                if (ps != null && ps.isMatch(flags)) {
3159                    return UserHandle.getUid(userId, ps.appId);
3160                }
3161            }
3162        }
3163
3164        return -1;
3165    }
3166
3167    @Override
3168    public int[] getPackageGids(String packageName, int flags, int userId) {
3169        if (!sUserManager.exists(userId)) return null;
3170        flags = updateFlagsForPackage(flags, userId, packageName);
3171        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3172                false /* requireFullPermission */, false /* checkShell */,
3173                "getPackageGids");
3174
3175        // reader
3176        synchronized (mPackages) {
3177            final PackageParser.Package p = mPackages.get(packageName);
3178            if (p != null && p.isMatch(flags)) {
3179                PackageSetting ps = (PackageSetting) p.mExtras;
3180                return ps.getPermissionsState().computeGids(userId);
3181            }
3182            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3183                final PackageSetting ps = mSettings.mPackages.get(packageName);
3184                if (ps != null && ps.isMatch(flags)) {
3185                    return ps.getPermissionsState().computeGids(userId);
3186                }
3187            }
3188        }
3189
3190        return null;
3191    }
3192
3193    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3194        if (bp.perm != null) {
3195            return PackageParser.generatePermissionInfo(bp.perm, flags);
3196        }
3197        PermissionInfo pi = new PermissionInfo();
3198        pi.name = bp.name;
3199        pi.packageName = bp.sourcePackage;
3200        pi.nonLocalizedLabel = bp.name;
3201        pi.protectionLevel = bp.protectionLevel;
3202        return pi;
3203    }
3204
3205    @Override
3206    public PermissionInfo getPermissionInfo(String name, int flags) {
3207        // reader
3208        synchronized (mPackages) {
3209            final BasePermission p = mSettings.mPermissions.get(name);
3210            if (p != null) {
3211                return generatePermissionInfo(p, flags);
3212            }
3213            return null;
3214        }
3215    }
3216
3217    @Override
3218    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3219            int flags) {
3220        // reader
3221        synchronized (mPackages) {
3222            if (group != null && !mPermissionGroups.containsKey(group)) {
3223                // This is thrown as NameNotFoundException
3224                return null;
3225            }
3226
3227            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3228            for (BasePermission p : mSettings.mPermissions.values()) {
3229                if (group == null) {
3230                    if (p.perm == null || p.perm.info.group == null) {
3231                        out.add(generatePermissionInfo(p, flags));
3232                    }
3233                } else {
3234                    if (p.perm != null && group.equals(p.perm.info.group)) {
3235                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3236                    }
3237                }
3238            }
3239            return new ParceledListSlice<>(out);
3240        }
3241    }
3242
3243    @Override
3244    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3245        // reader
3246        synchronized (mPackages) {
3247            return PackageParser.generatePermissionGroupInfo(
3248                    mPermissionGroups.get(name), flags);
3249        }
3250    }
3251
3252    @Override
3253    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3254        // reader
3255        synchronized (mPackages) {
3256            final int N = mPermissionGroups.size();
3257            ArrayList<PermissionGroupInfo> out
3258                    = new ArrayList<PermissionGroupInfo>(N);
3259            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3260                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3261            }
3262            return new ParceledListSlice<>(out);
3263        }
3264    }
3265
3266    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3267            int userId) {
3268        if (!sUserManager.exists(userId)) return null;
3269        PackageSetting ps = mSettings.mPackages.get(packageName);
3270        if (ps != null) {
3271            if (ps.pkg == null) {
3272                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3273                if (pInfo != null) {
3274                    return pInfo.applicationInfo;
3275                }
3276                return null;
3277            }
3278            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3279                    ps.readUserState(userId), userId);
3280        }
3281        return null;
3282    }
3283
3284    @Override
3285    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3286        if (!sUserManager.exists(userId)) return null;
3287        flags = updateFlagsForApplication(flags, userId, packageName);
3288        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3289                false /* requireFullPermission */, false /* checkShell */, "get application info");
3290        // writer
3291        synchronized (mPackages) {
3292            PackageParser.Package p = mPackages.get(packageName);
3293            if (DEBUG_PACKAGE_INFO) Log.v(
3294                    TAG, "getApplicationInfo " + packageName
3295                    + ": " + p);
3296            if (p != null) {
3297                PackageSetting ps = mSettings.mPackages.get(packageName);
3298                if (ps == null) return null;
3299                // Note: isEnabledLP() does not apply here - always return info
3300                return PackageParser.generateApplicationInfo(
3301                        p, flags, ps.readUserState(userId), userId);
3302            }
3303            if ("android".equals(packageName)||"system".equals(packageName)) {
3304                return mAndroidApplication;
3305            }
3306            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3307                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3308            }
3309        }
3310        return null;
3311    }
3312
3313    @Override
3314    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3315            final IPackageDataObserver observer) {
3316        mContext.enforceCallingOrSelfPermission(
3317                android.Manifest.permission.CLEAR_APP_CACHE, null);
3318        // Queue up an async operation since clearing cache may take a little while.
3319        mHandler.post(new Runnable() {
3320            public void run() {
3321                mHandler.removeCallbacks(this);
3322                boolean success = true;
3323                synchronized (mInstallLock) {
3324                    try {
3325                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3326                    } catch (InstallerException e) {
3327                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3328                        success = false;
3329                    }
3330                }
3331                if (observer != null) {
3332                    try {
3333                        observer.onRemoveCompleted(null, success);
3334                    } catch (RemoteException e) {
3335                        Slog.w(TAG, "RemoveException when invoking call back");
3336                    }
3337                }
3338            }
3339        });
3340    }
3341
3342    @Override
3343    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3344            final IntentSender pi) {
3345        mContext.enforceCallingOrSelfPermission(
3346                android.Manifest.permission.CLEAR_APP_CACHE, null);
3347        // Queue up an async operation since clearing cache may take a little while.
3348        mHandler.post(new Runnable() {
3349            public void run() {
3350                mHandler.removeCallbacks(this);
3351                boolean success = true;
3352                synchronized (mInstallLock) {
3353                    try {
3354                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3355                    } catch (InstallerException e) {
3356                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3357                        success = false;
3358                    }
3359                }
3360                if(pi != null) {
3361                    try {
3362                        // Callback via pending intent
3363                        int code = success ? 1 : 0;
3364                        pi.sendIntent(null, code, null,
3365                                null, null);
3366                    } catch (SendIntentException e1) {
3367                        Slog.i(TAG, "Failed to send pending intent");
3368                    }
3369                }
3370            }
3371        });
3372    }
3373
3374    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3375        synchronized (mInstallLock) {
3376            try {
3377                mInstaller.freeCache(volumeUuid, freeStorageSize);
3378            } catch (InstallerException e) {
3379                throw new IOException("Failed to free enough space", e);
3380            }
3381        }
3382    }
3383
3384    /**
3385     * Update given flags based on encryption status of current user.
3386     */
3387    private int updateFlags(int flags, int userId) {
3388        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3389                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3390            // Caller expressed an explicit opinion about what encryption
3391            // aware/unaware components they want to see, so fall through and
3392            // give them what they want
3393        } else {
3394            // Caller expressed no opinion, so match based on user state
3395            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3396                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3397            } else {
3398                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3399            }
3400        }
3401        return flags;
3402    }
3403
3404    private UserManagerInternal getUserManagerInternal() {
3405        if (mUserManagerInternal == null) {
3406            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3407        }
3408        return mUserManagerInternal;
3409    }
3410
3411    /**
3412     * Update given flags when being used to request {@link PackageInfo}.
3413     */
3414    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3415        boolean triaged = true;
3416        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3417                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3418            // Caller is asking for component details, so they'd better be
3419            // asking for specific encryption matching behavior, or be triaged
3420            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3421                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3422                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3423                triaged = false;
3424            }
3425        }
3426        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3427                | PackageManager.MATCH_SYSTEM_ONLY
3428                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3429            triaged = false;
3430        }
3431        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3432            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3433                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3434        }
3435        return updateFlags(flags, userId);
3436    }
3437
3438    /**
3439     * Update given flags when being used to request {@link ApplicationInfo}.
3440     */
3441    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3442        return updateFlagsForPackage(flags, userId, cookie);
3443    }
3444
3445    /**
3446     * Update given flags when being used to request {@link ComponentInfo}.
3447     */
3448    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3449        if (cookie instanceof Intent) {
3450            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3451                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3452            }
3453        }
3454
3455        boolean triaged = true;
3456        // Caller is asking for component details, so they'd better be
3457        // asking for specific encryption matching behavior, or be triaged
3458        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3459                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3460                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3461            triaged = false;
3462        }
3463        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3464            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3465                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3466        }
3467
3468        return updateFlags(flags, userId);
3469    }
3470
3471    /**
3472     * Update given flags when being used to request {@link ResolveInfo}.
3473     */
3474    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3475        // Safe mode means we shouldn't match any third-party components
3476        if (mSafeMode) {
3477            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3478        }
3479
3480        return updateFlagsForComponent(flags, userId, cookie);
3481    }
3482
3483    @Override
3484    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3485        if (!sUserManager.exists(userId)) return null;
3486        flags = updateFlagsForComponent(flags, userId, component);
3487        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3488                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3489        synchronized (mPackages) {
3490            PackageParser.Activity a = mActivities.mActivities.get(component);
3491
3492            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3493            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3494                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3495                if (ps == null) return null;
3496                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3497                        userId);
3498            }
3499            if (mResolveComponentName.equals(component)) {
3500                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3501                        new PackageUserState(), userId);
3502            }
3503        }
3504        return null;
3505    }
3506
3507    @Override
3508    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3509            String resolvedType) {
3510        synchronized (mPackages) {
3511            if (component.equals(mResolveComponentName)) {
3512                // The resolver supports EVERYTHING!
3513                return true;
3514            }
3515            PackageParser.Activity a = mActivities.mActivities.get(component);
3516            if (a == null) {
3517                return false;
3518            }
3519            for (int i=0; i<a.intents.size(); i++) {
3520                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3521                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3522                    return true;
3523                }
3524            }
3525            return false;
3526        }
3527    }
3528
3529    @Override
3530    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3531        if (!sUserManager.exists(userId)) return null;
3532        flags = updateFlagsForComponent(flags, userId, component);
3533        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3534                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3535        synchronized (mPackages) {
3536            PackageParser.Activity a = mReceivers.mActivities.get(component);
3537            if (DEBUG_PACKAGE_INFO) Log.v(
3538                TAG, "getReceiverInfo " + component + ": " + a);
3539            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3540                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3541                if (ps == null) return null;
3542                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3543                        userId);
3544            }
3545        }
3546        return null;
3547    }
3548
3549    @Override
3550    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3551        if (!sUserManager.exists(userId)) return null;
3552        flags = updateFlagsForComponent(flags, userId, component);
3553        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3554                false /* requireFullPermission */, false /* checkShell */, "get service info");
3555        synchronized (mPackages) {
3556            PackageParser.Service s = mServices.mServices.get(component);
3557            if (DEBUG_PACKAGE_INFO) Log.v(
3558                TAG, "getServiceInfo " + component + ": " + s);
3559            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3560                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3561                if (ps == null) return null;
3562                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3563                        userId);
3564            }
3565        }
3566        return null;
3567    }
3568
3569    @Override
3570    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3571        if (!sUserManager.exists(userId)) return null;
3572        flags = updateFlagsForComponent(flags, userId, component);
3573        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3574                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3575        synchronized (mPackages) {
3576            PackageParser.Provider p = mProviders.mProviders.get(component);
3577            if (DEBUG_PACKAGE_INFO) Log.v(
3578                TAG, "getProviderInfo " + component + ": " + p);
3579            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3580                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3581                if (ps == null) return null;
3582                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3583                        userId);
3584            }
3585        }
3586        return null;
3587    }
3588
3589    @Override
3590    public String[] getSystemSharedLibraryNames() {
3591        Set<String> libSet;
3592        synchronized (mPackages) {
3593            libSet = mSharedLibraries.keySet();
3594            int size = libSet.size();
3595            if (size > 0) {
3596                String[] libs = new String[size];
3597                libSet.toArray(libs);
3598                return libs;
3599            }
3600        }
3601        return null;
3602    }
3603
3604    @Override
3605    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3606        synchronized (mPackages) {
3607            return mServicesSystemSharedLibraryPackageName;
3608        }
3609    }
3610
3611    @Override
3612    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3613        synchronized (mPackages) {
3614            return mSharedSystemSharedLibraryPackageName;
3615        }
3616    }
3617
3618    @Override
3619    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3620        synchronized (mPackages) {
3621            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3622
3623            final FeatureInfo fi = new FeatureInfo();
3624            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3625                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3626            res.add(fi);
3627
3628            return new ParceledListSlice<>(res);
3629        }
3630    }
3631
3632    @Override
3633    public boolean hasSystemFeature(String name, int version) {
3634        synchronized (mPackages) {
3635            final FeatureInfo feat = mAvailableFeatures.get(name);
3636            if (feat == null) {
3637                return false;
3638            } else {
3639                return feat.version >= version;
3640            }
3641        }
3642    }
3643
3644    @Override
3645    public int checkPermission(String permName, String pkgName, int userId) {
3646        if (!sUserManager.exists(userId)) {
3647            return PackageManager.PERMISSION_DENIED;
3648        }
3649
3650        synchronized (mPackages) {
3651            final PackageParser.Package p = mPackages.get(pkgName);
3652            if (p != null && p.mExtras != null) {
3653                final PackageSetting ps = (PackageSetting) p.mExtras;
3654                final PermissionsState permissionsState = ps.getPermissionsState();
3655                if (permissionsState.hasPermission(permName, userId)) {
3656                    return PackageManager.PERMISSION_GRANTED;
3657                }
3658                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3659                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3660                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3661                    return PackageManager.PERMISSION_GRANTED;
3662                }
3663            }
3664        }
3665
3666        return PackageManager.PERMISSION_DENIED;
3667    }
3668
3669    @Override
3670    public int checkUidPermission(String permName, int uid) {
3671        final int userId = UserHandle.getUserId(uid);
3672
3673        if (!sUserManager.exists(userId)) {
3674            return PackageManager.PERMISSION_DENIED;
3675        }
3676
3677        synchronized (mPackages) {
3678            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3679            if (obj != null) {
3680                final SettingBase ps = (SettingBase) obj;
3681                final PermissionsState permissionsState = ps.getPermissionsState();
3682                if (permissionsState.hasPermission(permName, userId)) {
3683                    return PackageManager.PERMISSION_GRANTED;
3684                }
3685                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3686                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3687                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3688                    return PackageManager.PERMISSION_GRANTED;
3689                }
3690            } else {
3691                ArraySet<String> perms = mSystemPermissions.get(uid);
3692                if (perms != null) {
3693                    if (perms.contains(permName)) {
3694                        return PackageManager.PERMISSION_GRANTED;
3695                    }
3696                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3697                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3698                        return PackageManager.PERMISSION_GRANTED;
3699                    }
3700                }
3701            }
3702        }
3703
3704        return PackageManager.PERMISSION_DENIED;
3705    }
3706
3707    @Override
3708    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3709        if (UserHandle.getCallingUserId() != userId) {
3710            mContext.enforceCallingPermission(
3711                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3712                    "isPermissionRevokedByPolicy for user " + userId);
3713        }
3714
3715        if (checkPermission(permission, packageName, userId)
3716                == PackageManager.PERMISSION_GRANTED) {
3717            return false;
3718        }
3719
3720        final long identity = Binder.clearCallingIdentity();
3721        try {
3722            final int flags = getPermissionFlags(permission, packageName, userId);
3723            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3724        } finally {
3725            Binder.restoreCallingIdentity(identity);
3726        }
3727    }
3728
3729    @Override
3730    public String getPermissionControllerPackageName() {
3731        synchronized (mPackages) {
3732            return mRequiredInstallerPackage;
3733        }
3734    }
3735
3736    /**
3737     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3738     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3739     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3740     * @param message the message to log on security exception
3741     */
3742    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3743            boolean checkShell, String message) {
3744        if (userId < 0) {
3745            throw new IllegalArgumentException("Invalid userId " + userId);
3746        }
3747        if (checkShell) {
3748            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3749        }
3750        if (userId == UserHandle.getUserId(callingUid)) return;
3751        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3752            if (requireFullPermission) {
3753                mContext.enforceCallingOrSelfPermission(
3754                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3755            } else {
3756                try {
3757                    mContext.enforceCallingOrSelfPermission(
3758                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3759                } catch (SecurityException se) {
3760                    mContext.enforceCallingOrSelfPermission(
3761                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3762                }
3763            }
3764        }
3765    }
3766
3767    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3768        if (callingUid == Process.SHELL_UID) {
3769            if (userHandle >= 0
3770                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3771                throw new SecurityException("Shell does not have permission to access user "
3772                        + userHandle);
3773            } else if (userHandle < 0) {
3774                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3775                        + Debug.getCallers(3));
3776            }
3777        }
3778    }
3779
3780    private BasePermission findPermissionTreeLP(String permName) {
3781        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3782            if (permName.startsWith(bp.name) &&
3783                    permName.length() > bp.name.length() &&
3784                    permName.charAt(bp.name.length()) == '.') {
3785                return bp;
3786            }
3787        }
3788        return null;
3789    }
3790
3791    private BasePermission checkPermissionTreeLP(String permName) {
3792        if (permName != null) {
3793            BasePermission bp = findPermissionTreeLP(permName);
3794            if (bp != null) {
3795                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3796                    return bp;
3797                }
3798                throw new SecurityException("Calling uid "
3799                        + Binder.getCallingUid()
3800                        + " is not allowed to add to permission tree "
3801                        + bp.name + " owned by uid " + bp.uid);
3802            }
3803        }
3804        throw new SecurityException("No permission tree found for " + permName);
3805    }
3806
3807    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3808        if (s1 == null) {
3809            return s2 == null;
3810        }
3811        if (s2 == null) {
3812            return false;
3813        }
3814        if (s1.getClass() != s2.getClass()) {
3815            return false;
3816        }
3817        return s1.equals(s2);
3818    }
3819
3820    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3821        if (pi1.icon != pi2.icon) return false;
3822        if (pi1.logo != pi2.logo) return false;
3823        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3824        if (!compareStrings(pi1.name, pi2.name)) return false;
3825        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3826        // We'll take care of setting this one.
3827        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3828        // These are not currently stored in settings.
3829        //if (!compareStrings(pi1.group, pi2.group)) return false;
3830        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3831        //if (pi1.labelRes != pi2.labelRes) return false;
3832        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3833        return true;
3834    }
3835
3836    int permissionInfoFootprint(PermissionInfo info) {
3837        int size = info.name.length();
3838        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3839        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3840        return size;
3841    }
3842
3843    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3844        int size = 0;
3845        for (BasePermission perm : mSettings.mPermissions.values()) {
3846            if (perm.uid == tree.uid) {
3847                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3848            }
3849        }
3850        return size;
3851    }
3852
3853    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3854        // We calculate the max size of permissions defined by this uid and throw
3855        // if that plus the size of 'info' would exceed our stated maximum.
3856        if (tree.uid != Process.SYSTEM_UID) {
3857            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3858            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3859                throw new SecurityException("Permission tree size cap exceeded");
3860            }
3861        }
3862    }
3863
3864    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3865        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3866            throw new SecurityException("Label must be specified in permission");
3867        }
3868        BasePermission tree = checkPermissionTreeLP(info.name);
3869        BasePermission bp = mSettings.mPermissions.get(info.name);
3870        boolean added = bp == null;
3871        boolean changed = true;
3872        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3873        if (added) {
3874            enforcePermissionCapLocked(info, tree);
3875            bp = new BasePermission(info.name, tree.sourcePackage,
3876                    BasePermission.TYPE_DYNAMIC);
3877        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3878            throw new SecurityException(
3879                    "Not allowed to modify non-dynamic permission "
3880                    + info.name);
3881        } else {
3882            if (bp.protectionLevel == fixedLevel
3883                    && bp.perm.owner.equals(tree.perm.owner)
3884                    && bp.uid == tree.uid
3885                    && comparePermissionInfos(bp.perm.info, info)) {
3886                changed = false;
3887            }
3888        }
3889        bp.protectionLevel = fixedLevel;
3890        info = new PermissionInfo(info);
3891        info.protectionLevel = fixedLevel;
3892        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3893        bp.perm.info.packageName = tree.perm.info.packageName;
3894        bp.uid = tree.uid;
3895        if (added) {
3896            mSettings.mPermissions.put(info.name, bp);
3897        }
3898        if (changed) {
3899            if (!async) {
3900                mSettings.writeLPr();
3901            } else {
3902                scheduleWriteSettingsLocked();
3903            }
3904        }
3905        return added;
3906    }
3907
3908    @Override
3909    public boolean addPermission(PermissionInfo info) {
3910        synchronized (mPackages) {
3911            return addPermissionLocked(info, false);
3912        }
3913    }
3914
3915    @Override
3916    public boolean addPermissionAsync(PermissionInfo info) {
3917        synchronized (mPackages) {
3918            return addPermissionLocked(info, true);
3919        }
3920    }
3921
3922    @Override
3923    public void removePermission(String name) {
3924        synchronized (mPackages) {
3925            checkPermissionTreeLP(name);
3926            BasePermission bp = mSettings.mPermissions.get(name);
3927            if (bp != null) {
3928                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3929                    throw new SecurityException(
3930                            "Not allowed to modify non-dynamic permission "
3931                            + name);
3932                }
3933                mSettings.mPermissions.remove(name);
3934                mSettings.writeLPr();
3935            }
3936        }
3937    }
3938
3939    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3940            BasePermission bp) {
3941        int index = pkg.requestedPermissions.indexOf(bp.name);
3942        if (index == -1) {
3943            throw new SecurityException("Package " + pkg.packageName
3944                    + " has not requested permission " + bp.name);
3945        }
3946        if (!bp.isRuntime() && !bp.isDevelopment()) {
3947            throw new SecurityException("Permission " + bp.name
3948                    + " is not a changeable permission type");
3949        }
3950    }
3951
3952    @Override
3953    public void grantRuntimePermission(String packageName, String name, final int userId) {
3954        if (!sUserManager.exists(userId)) {
3955            Log.e(TAG, "No such user:" + userId);
3956            return;
3957        }
3958
3959        mContext.enforceCallingOrSelfPermission(
3960                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3961                "grantRuntimePermission");
3962
3963        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3964                true /* requireFullPermission */, true /* checkShell */,
3965                "grantRuntimePermission");
3966
3967        final int uid;
3968        final SettingBase sb;
3969
3970        synchronized (mPackages) {
3971            final PackageParser.Package pkg = mPackages.get(packageName);
3972            if (pkg == null) {
3973                throw new IllegalArgumentException("Unknown package: " + packageName);
3974            }
3975
3976            final BasePermission bp = mSettings.mPermissions.get(name);
3977            if (bp == null) {
3978                throw new IllegalArgumentException("Unknown permission: " + name);
3979            }
3980
3981            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3982
3983            // If a permission review is required for legacy apps we represent
3984            // their permissions as always granted runtime ones since we need
3985            // to keep the review required permission flag per user while an
3986            // install permission's state is shared across all users.
3987            if (Build.PERMISSIONS_REVIEW_REQUIRED
3988                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3989                    && bp.isRuntime()) {
3990                return;
3991            }
3992
3993            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3994            sb = (SettingBase) pkg.mExtras;
3995            if (sb == null) {
3996                throw new IllegalArgumentException("Unknown package: " + packageName);
3997            }
3998
3999            final PermissionsState permissionsState = sb.getPermissionsState();
4000
4001            final int flags = permissionsState.getPermissionFlags(name, userId);
4002            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4003                throw new SecurityException("Cannot grant system fixed permission "
4004                        + name + " for package " + packageName);
4005            }
4006
4007            if (bp.isDevelopment()) {
4008                // Development permissions must be handled specially, since they are not
4009                // normal runtime permissions.  For now they apply to all users.
4010                if (permissionsState.grantInstallPermission(bp) !=
4011                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4012                    scheduleWriteSettingsLocked();
4013                }
4014                return;
4015            }
4016
4017            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4018                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4019                return;
4020            }
4021
4022            final int result = permissionsState.grantRuntimePermission(bp, userId);
4023            switch (result) {
4024                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4025                    return;
4026                }
4027
4028                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4029                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4030                    mHandler.post(new Runnable() {
4031                        @Override
4032                        public void run() {
4033                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4034                        }
4035                    });
4036                }
4037                break;
4038            }
4039
4040            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4041
4042            // Not critical if that is lost - app has to request again.
4043            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4044        }
4045
4046        // Only need to do this if user is initialized. Otherwise it's a new user
4047        // and there are no processes running as the user yet and there's no need
4048        // to make an expensive call to remount processes for the changed permissions.
4049        if (READ_EXTERNAL_STORAGE.equals(name)
4050                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4051            final long token = Binder.clearCallingIdentity();
4052            try {
4053                if (sUserManager.isInitialized(userId)) {
4054                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4055                            MountServiceInternal.class);
4056                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4057                }
4058            } finally {
4059                Binder.restoreCallingIdentity(token);
4060            }
4061        }
4062    }
4063
4064    @Override
4065    public void revokeRuntimePermission(String packageName, String name, int userId) {
4066        if (!sUserManager.exists(userId)) {
4067            Log.e(TAG, "No such user:" + userId);
4068            return;
4069        }
4070
4071        mContext.enforceCallingOrSelfPermission(
4072                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4073                "revokeRuntimePermission");
4074
4075        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4076                true /* requireFullPermission */, true /* checkShell */,
4077                "revokeRuntimePermission");
4078
4079        final int appId;
4080
4081        synchronized (mPackages) {
4082            final PackageParser.Package pkg = mPackages.get(packageName);
4083            if (pkg == null) {
4084                throw new IllegalArgumentException("Unknown package: " + packageName);
4085            }
4086
4087            final BasePermission bp = mSettings.mPermissions.get(name);
4088            if (bp == null) {
4089                throw new IllegalArgumentException("Unknown permission: " + name);
4090            }
4091
4092            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4093
4094            // If a permission review is required for legacy apps we represent
4095            // their permissions as always granted runtime ones since we need
4096            // to keep the review required permission flag per user while an
4097            // install permission's state is shared across all users.
4098            if (Build.PERMISSIONS_REVIEW_REQUIRED
4099                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4100                    && bp.isRuntime()) {
4101                return;
4102            }
4103
4104            SettingBase sb = (SettingBase) pkg.mExtras;
4105            if (sb == null) {
4106                throw new IllegalArgumentException("Unknown package: " + packageName);
4107            }
4108
4109            final PermissionsState permissionsState = sb.getPermissionsState();
4110
4111            final int flags = permissionsState.getPermissionFlags(name, userId);
4112            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4113                throw new SecurityException("Cannot revoke system fixed permission "
4114                        + name + " for package " + packageName);
4115            }
4116
4117            if (bp.isDevelopment()) {
4118                // Development permissions must be handled specially, since they are not
4119                // normal runtime permissions.  For now they apply to all users.
4120                if (permissionsState.revokeInstallPermission(bp) !=
4121                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4122                    scheduleWriteSettingsLocked();
4123                }
4124                return;
4125            }
4126
4127            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4128                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4129                return;
4130            }
4131
4132            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4133
4134            // Critical, after this call app should never have the permission.
4135            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4136
4137            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4138        }
4139
4140        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4141    }
4142
4143    @Override
4144    public void resetRuntimePermissions() {
4145        mContext.enforceCallingOrSelfPermission(
4146                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4147                "revokeRuntimePermission");
4148
4149        int callingUid = Binder.getCallingUid();
4150        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4151            mContext.enforceCallingOrSelfPermission(
4152                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4153                    "resetRuntimePermissions");
4154        }
4155
4156        synchronized (mPackages) {
4157            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4158            for (int userId : UserManagerService.getInstance().getUserIds()) {
4159                final int packageCount = mPackages.size();
4160                for (int i = 0; i < packageCount; i++) {
4161                    PackageParser.Package pkg = mPackages.valueAt(i);
4162                    if (!(pkg.mExtras instanceof PackageSetting)) {
4163                        continue;
4164                    }
4165                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4166                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4167                }
4168            }
4169        }
4170    }
4171
4172    @Override
4173    public int getPermissionFlags(String name, String packageName, int userId) {
4174        if (!sUserManager.exists(userId)) {
4175            return 0;
4176        }
4177
4178        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4179
4180        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4181                true /* requireFullPermission */, false /* checkShell */,
4182                "getPermissionFlags");
4183
4184        synchronized (mPackages) {
4185            final PackageParser.Package pkg = mPackages.get(packageName);
4186            if (pkg == null) {
4187                return 0;
4188            }
4189
4190            final BasePermission bp = mSettings.mPermissions.get(name);
4191            if (bp == null) {
4192                return 0;
4193            }
4194
4195            SettingBase sb = (SettingBase) pkg.mExtras;
4196            if (sb == null) {
4197                return 0;
4198            }
4199
4200            PermissionsState permissionsState = sb.getPermissionsState();
4201            return permissionsState.getPermissionFlags(name, userId);
4202        }
4203    }
4204
4205    @Override
4206    public void updatePermissionFlags(String name, String packageName, int flagMask,
4207            int flagValues, int userId) {
4208        if (!sUserManager.exists(userId)) {
4209            return;
4210        }
4211
4212        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4213
4214        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4215                true /* requireFullPermission */, true /* checkShell */,
4216                "updatePermissionFlags");
4217
4218        // Only the system can change these flags and nothing else.
4219        if (getCallingUid() != Process.SYSTEM_UID) {
4220            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4221            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4222            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4223            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4224            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4225        }
4226
4227        synchronized (mPackages) {
4228            final PackageParser.Package pkg = mPackages.get(packageName);
4229            if (pkg == null) {
4230                throw new IllegalArgumentException("Unknown package: " + packageName);
4231            }
4232
4233            final BasePermission bp = mSettings.mPermissions.get(name);
4234            if (bp == null) {
4235                throw new IllegalArgumentException("Unknown permission: " + name);
4236            }
4237
4238            SettingBase sb = (SettingBase) pkg.mExtras;
4239            if (sb == null) {
4240                throw new IllegalArgumentException("Unknown package: " + packageName);
4241            }
4242
4243            PermissionsState permissionsState = sb.getPermissionsState();
4244
4245            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4246
4247            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4248                // Install and runtime permissions are stored in different places,
4249                // so figure out what permission changed and persist the change.
4250                if (permissionsState.getInstallPermissionState(name) != null) {
4251                    scheduleWriteSettingsLocked();
4252                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4253                        || hadState) {
4254                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4255                }
4256            }
4257        }
4258    }
4259
4260    /**
4261     * Update the permission flags for all packages and runtime permissions of a user in order
4262     * to allow device or profile owner to remove POLICY_FIXED.
4263     */
4264    @Override
4265    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4266        if (!sUserManager.exists(userId)) {
4267            return;
4268        }
4269
4270        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4271
4272        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4273                true /* requireFullPermission */, true /* checkShell */,
4274                "updatePermissionFlagsForAllApps");
4275
4276        // Only the system can change system fixed flags.
4277        if (getCallingUid() != Process.SYSTEM_UID) {
4278            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4279            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4280        }
4281
4282        synchronized (mPackages) {
4283            boolean changed = false;
4284            final int packageCount = mPackages.size();
4285            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4286                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4287                SettingBase sb = (SettingBase) pkg.mExtras;
4288                if (sb == null) {
4289                    continue;
4290                }
4291                PermissionsState permissionsState = sb.getPermissionsState();
4292                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4293                        userId, flagMask, flagValues);
4294            }
4295            if (changed) {
4296                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4297            }
4298        }
4299    }
4300
4301    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4302        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4303                != PackageManager.PERMISSION_GRANTED
4304            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4305                != PackageManager.PERMISSION_GRANTED) {
4306            throw new SecurityException(message + " requires "
4307                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4308                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4309        }
4310    }
4311
4312    @Override
4313    public boolean shouldShowRequestPermissionRationale(String permissionName,
4314            String packageName, int userId) {
4315        if (UserHandle.getCallingUserId() != userId) {
4316            mContext.enforceCallingPermission(
4317                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4318                    "canShowRequestPermissionRationale for user " + userId);
4319        }
4320
4321        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4322        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4323            return false;
4324        }
4325
4326        if (checkPermission(permissionName, packageName, userId)
4327                == PackageManager.PERMISSION_GRANTED) {
4328            return false;
4329        }
4330
4331        final int flags;
4332
4333        final long identity = Binder.clearCallingIdentity();
4334        try {
4335            flags = getPermissionFlags(permissionName,
4336                    packageName, userId);
4337        } finally {
4338            Binder.restoreCallingIdentity(identity);
4339        }
4340
4341        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4342                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4343                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4344
4345        if ((flags & fixedFlags) != 0) {
4346            return false;
4347        }
4348
4349        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4350    }
4351
4352    @Override
4353    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4354        mContext.enforceCallingOrSelfPermission(
4355                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4356                "addOnPermissionsChangeListener");
4357
4358        synchronized (mPackages) {
4359            mOnPermissionChangeListeners.addListenerLocked(listener);
4360        }
4361    }
4362
4363    @Override
4364    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4365        synchronized (mPackages) {
4366            mOnPermissionChangeListeners.removeListenerLocked(listener);
4367        }
4368    }
4369
4370    @Override
4371    public boolean isProtectedBroadcast(String actionName) {
4372        synchronized (mPackages) {
4373            if (mProtectedBroadcasts.contains(actionName)) {
4374                return true;
4375            } else if (actionName != null) {
4376                // TODO: remove these terrible hacks
4377                if (actionName.startsWith("android.net.netmon.lingerExpired")
4378                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4379                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4380                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4381                    return true;
4382                }
4383            }
4384        }
4385        return false;
4386    }
4387
4388    @Override
4389    public int checkSignatures(String pkg1, String pkg2) {
4390        synchronized (mPackages) {
4391            final PackageParser.Package p1 = mPackages.get(pkg1);
4392            final PackageParser.Package p2 = mPackages.get(pkg2);
4393            if (p1 == null || p1.mExtras == null
4394                    || p2 == null || p2.mExtras == null) {
4395                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4396            }
4397            return compareSignatures(p1.mSignatures, p2.mSignatures);
4398        }
4399    }
4400
4401    @Override
4402    public int checkUidSignatures(int uid1, int uid2) {
4403        // Map to base uids.
4404        uid1 = UserHandle.getAppId(uid1);
4405        uid2 = UserHandle.getAppId(uid2);
4406        // reader
4407        synchronized (mPackages) {
4408            Signature[] s1;
4409            Signature[] s2;
4410            Object obj = mSettings.getUserIdLPr(uid1);
4411            if (obj != null) {
4412                if (obj instanceof SharedUserSetting) {
4413                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4414                } else if (obj instanceof PackageSetting) {
4415                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4416                } else {
4417                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4418                }
4419            } else {
4420                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4421            }
4422            obj = mSettings.getUserIdLPr(uid2);
4423            if (obj != null) {
4424                if (obj instanceof SharedUserSetting) {
4425                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4426                } else if (obj instanceof PackageSetting) {
4427                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4428                } else {
4429                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4430                }
4431            } else {
4432                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4433            }
4434            return compareSignatures(s1, s2);
4435        }
4436    }
4437
4438    /**
4439     * This method should typically only be used when granting or revoking
4440     * permissions, since the app may immediately restart after this call.
4441     * <p>
4442     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4443     * guard your work against the app being relaunched.
4444     */
4445    private void killUid(int appId, int userId, String reason) {
4446        final long identity = Binder.clearCallingIdentity();
4447        try {
4448            IActivityManager am = ActivityManagerNative.getDefault();
4449            if (am != null) {
4450                try {
4451                    am.killUid(appId, userId, reason);
4452                } catch (RemoteException e) {
4453                    /* ignore - same process */
4454                }
4455            }
4456        } finally {
4457            Binder.restoreCallingIdentity(identity);
4458        }
4459    }
4460
4461    /**
4462     * Compares two sets of signatures. Returns:
4463     * <br />
4464     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4465     * <br />
4466     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4467     * <br />
4468     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4469     * <br />
4470     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4471     * <br />
4472     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4473     */
4474    static int compareSignatures(Signature[] s1, Signature[] s2) {
4475        if (s1 == null) {
4476            return s2 == null
4477                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4478                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4479        }
4480
4481        if (s2 == null) {
4482            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4483        }
4484
4485        if (s1.length != s2.length) {
4486            return PackageManager.SIGNATURE_NO_MATCH;
4487        }
4488
4489        // Since both signature sets are of size 1, we can compare without HashSets.
4490        if (s1.length == 1) {
4491            return s1[0].equals(s2[0]) ?
4492                    PackageManager.SIGNATURE_MATCH :
4493                    PackageManager.SIGNATURE_NO_MATCH;
4494        }
4495
4496        ArraySet<Signature> set1 = new ArraySet<Signature>();
4497        for (Signature sig : s1) {
4498            set1.add(sig);
4499        }
4500        ArraySet<Signature> set2 = new ArraySet<Signature>();
4501        for (Signature sig : s2) {
4502            set2.add(sig);
4503        }
4504        // Make sure s2 contains all signatures in s1.
4505        if (set1.equals(set2)) {
4506            return PackageManager.SIGNATURE_MATCH;
4507        }
4508        return PackageManager.SIGNATURE_NO_MATCH;
4509    }
4510
4511    /**
4512     * If the database version for this type of package (internal storage or
4513     * external storage) is less than the version where package signatures
4514     * were updated, return true.
4515     */
4516    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4517        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4518        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4519    }
4520
4521    /**
4522     * Used for backward compatibility to make sure any packages with
4523     * certificate chains get upgraded to the new style. {@code existingSigs}
4524     * will be in the old format (since they were stored on disk from before the
4525     * system upgrade) and {@code scannedSigs} will be in the newer format.
4526     */
4527    private int compareSignaturesCompat(PackageSignatures existingSigs,
4528            PackageParser.Package scannedPkg) {
4529        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4530            return PackageManager.SIGNATURE_NO_MATCH;
4531        }
4532
4533        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4534        for (Signature sig : existingSigs.mSignatures) {
4535            existingSet.add(sig);
4536        }
4537        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4538        for (Signature sig : scannedPkg.mSignatures) {
4539            try {
4540                Signature[] chainSignatures = sig.getChainSignatures();
4541                for (Signature chainSig : chainSignatures) {
4542                    scannedCompatSet.add(chainSig);
4543                }
4544            } catch (CertificateEncodingException e) {
4545                scannedCompatSet.add(sig);
4546            }
4547        }
4548        /*
4549         * Make sure the expanded scanned set contains all signatures in the
4550         * existing one.
4551         */
4552        if (scannedCompatSet.equals(existingSet)) {
4553            // Migrate the old signatures to the new scheme.
4554            existingSigs.assignSignatures(scannedPkg.mSignatures);
4555            // The new KeySets will be re-added later in the scanning process.
4556            synchronized (mPackages) {
4557                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4558            }
4559            return PackageManager.SIGNATURE_MATCH;
4560        }
4561        return PackageManager.SIGNATURE_NO_MATCH;
4562    }
4563
4564    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4565        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4566        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4567    }
4568
4569    private int compareSignaturesRecover(PackageSignatures existingSigs,
4570            PackageParser.Package scannedPkg) {
4571        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4572            return PackageManager.SIGNATURE_NO_MATCH;
4573        }
4574
4575        String msg = null;
4576        try {
4577            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4578                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4579                        + scannedPkg.packageName);
4580                return PackageManager.SIGNATURE_MATCH;
4581            }
4582        } catch (CertificateException e) {
4583            msg = e.getMessage();
4584        }
4585
4586        logCriticalInfo(Log.INFO,
4587                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4588        return PackageManager.SIGNATURE_NO_MATCH;
4589    }
4590
4591    @Override
4592    public List<String> getAllPackages() {
4593        synchronized (mPackages) {
4594            return new ArrayList<String>(mPackages.keySet());
4595        }
4596    }
4597
4598    @Override
4599    public String[] getPackagesForUid(int uid) {
4600        uid = UserHandle.getAppId(uid);
4601        // reader
4602        synchronized (mPackages) {
4603            Object obj = mSettings.getUserIdLPr(uid);
4604            if (obj instanceof SharedUserSetting) {
4605                final SharedUserSetting sus = (SharedUserSetting) obj;
4606                final int N = sus.packages.size();
4607                final String[] res = new String[N];
4608                for (int i = 0; i < N; i++) {
4609                    res[i] = sus.packages.valueAt(i).name;
4610                }
4611                return res;
4612            } else if (obj instanceof PackageSetting) {
4613                final PackageSetting ps = (PackageSetting) obj;
4614                return new String[] { ps.name };
4615            }
4616        }
4617        return null;
4618    }
4619
4620    @Override
4621    public String getNameForUid(int uid) {
4622        // reader
4623        synchronized (mPackages) {
4624            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4625            if (obj instanceof SharedUserSetting) {
4626                final SharedUserSetting sus = (SharedUserSetting) obj;
4627                return sus.name + ":" + sus.userId;
4628            } else if (obj instanceof PackageSetting) {
4629                final PackageSetting ps = (PackageSetting) obj;
4630                return ps.name;
4631            }
4632        }
4633        return null;
4634    }
4635
4636    @Override
4637    public int getUidForSharedUser(String sharedUserName) {
4638        if(sharedUserName == null) {
4639            return -1;
4640        }
4641        // reader
4642        synchronized (mPackages) {
4643            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4644            if (suid == null) {
4645                return -1;
4646            }
4647            return suid.userId;
4648        }
4649    }
4650
4651    @Override
4652    public int getFlagsForUid(int uid) {
4653        synchronized (mPackages) {
4654            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4655            if (obj instanceof SharedUserSetting) {
4656                final SharedUserSetting sus = (SharedUserSetting) obj;
4657                return sus.pkgFlags;
4658            } else if (obj instanceof PackageSetting) {
4659                final PackageSetting ps = (PackageSetting) obj;
4660                return ps.pkgFlags;
4661            }
4662        }
4663        return 0;
4664    }
4665
4666    @Override
4667    public int getPrivateFlagsForUid(int uid) {
4668        synchronized (mPackages) {
4669            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4670            if (obj instanceof SharedUserSetting) {
4671                final SharedUserSetting sus = (SharedUserSetting) obj;
4672                return sus.pkgPrivateFlags;
4673            } else if (obj instanceof PackageSetting) {
4674                final PackageSetting ps = (PackageSetting) obj;
4675                return ps.pkgPrivateFlags;
4676            }
4677        }
4678        return 0;
4679    }
4680
4681    @Override
4682    public boolean isUidPrivileged(int uid) {
4683        uid = UserHandle.getAppId(uid);
4684        // reader
4685        synchronized (mPackages) {
4686            Object obj = mSettings.getUserIdLPr(uid);
4687            if (obj instanceof SharedUserSetting) {
4688                final SharedUserSetting sus = (SharedUserSetting) obj;
4689                final Iterator<PackageSetting> it = sus.packages.iterator();
4690                while (it.hasNext()) {
4691                    if (it.next().isPrivileged()) {
4692                        return true;
4693                    }
4694                }
4695            } else if (obj instanceof PackageSetting) {
4696                final PackageSetting ps = (PackageSetting) obj;
4697                return ps.isPrivileged();
4698            }
4699        }
4700        return false;
4701    }
4702
4703    @Override
4704    public String[] getAppOpPermissionPackages(String permissionName) {
4705        synchronized (mPackages) {
4706            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4707            if (pkgs == null) {
4708                return null;
4709            }
4710            return pkgs.toArray(new String[pkgs.size()]);
4711        }
4712    }
4713
4714    @Override
4715    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4716            int flags, int userId) {
4717        try {
4718            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4719
4720            if (!sUserManager.exists(userId)) return null;
4721            flags = updateFlagsForResolve(flags, userId, intent);
4722            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4723                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4724
4725            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4726            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4727                    flags, userId);
4728            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4729
4730            final ResolveInfo bestChoice =
4731                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4732            return bestChoice;
4733        } finally {
4734            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4735        }
4736    }
4737
4738    @Override
4739    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4740            IntentFilter filter, int match, ComponentName activity) {
4741        final int userId = UserHandle.getCallingUserId();
4742        if (DEBUG_PREFERRED) {
4743            Log.v(TAG, "setLastChosenActivity intent=" + intent
4744                + " resolvedType=" + resolvedType
4745                + " flags=" + flags
4746                + " filter=" + filter
4747                + " match=" + match
4748                + " activity=" + activity);
4749            filter.dump(new PrintStreamPrinter(System.out), "    ");
4750        }
4751        intent.setComponent(null);
4752        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4753                userId);
4754        // Find any earlier preferred or last chosen entries and nuke them
4755        findPreferredActivity(intent, resolvedType,
4756                flags, query, 0, false, true, false, userId);
4757        // Add the new activity as the last chosen for this filter
4758        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4759                "Setting last chosen");
4760    }
4761
4762    @Override
4763    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4764        final int userId = UserHandle.getCallingUserId();
4765        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4766        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4767                userId);
4768        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4769                false, false, false, userId);
4770    }
4771
4772    private boolean isEphemeralDisabled() {
4773        // ephemeral apps have been disabled across the board
4774        if (DISABLE_EPHEMERAL_APPS) {
4775            return true;
4776        }
4777        // system isn't up yet; can't read settings, so, assume no ephemeral apps
4778        if (!mSystemReady) {
4779            return true;
4780        }
4781        return Secure.getInt(mContext.getContentResolver(), Secure.WEB_ACTION_ENABLED, 1) == 0;
4782    }
4783
4784    private boolean isEphemeralAllowed(
4785            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4786            boolean skipPackageCheck) {
4787        // Short circuit and return early if possible.
4788        if (isEphemeralDisabled()) {
4789            return false;
4790        }
4791        final int callingUser = UserHandle.getCallingUserId();
4792        if (callingUser != UserHandle.USER_SYSTEM) {
4793            return false;
4794        }
4795        if (mEphemeralResolverConnection == null) {
4796            return false;
4797        }
4798        if (intent.getComponent() != null) {
4799            return false;
4800        }
4801        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4802            return false;
4803        }
4804        if (!skipPackageCheck && intent.getPackage() != null) {
4805            return false;
4806        }
4807        final boolean isWebUri = hasWebURI(intent);
4808        if (!isWebUri || intent.getData().getHost() == null) {
4809            return false;
4810        }
4811        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4812        synchronized (mPackages) {
4813            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4814            for (int n = 0; n < count; n++) {
4815                ResolveInfo info = resolvedActivities.get(n);
4816                String packageName = info.activityInfo.packageName;
4817                PackageSetting ps = mSettings.mPackages.get(packageName);
4818                if (ps != null) {
4819                    // Try to get the status from User settings first
4820                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4821                    int status = (int) (packedStatus >> 32);
4822                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4823                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4824                        if (DEBUG_EPHEMERAL) {
4825                            Slog.v(TAG, "DENY ephemeral apps;"
4826                                + " pkg: " + packageName + ", status: " + status);
4827                        }
4828                        return false;
4829                    }
4830                }
4831            }
4832        }
4833        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4834        return true;
4835    }
4836
4837    private static EphemeralResolveInfo getEphemeralResolveInfo(
4838            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4839            String resolvedType, int userId, String packageName) {
4840        final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4841                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4842        final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4843                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4844        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4845                ephemeralPrefixCount);
4846        final int[] shaPrefix = digest.getDigestPrefix();
4847        final byte[][] digestBytes = digest.getDigestBytes();
4848        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4849                resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4850        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4851            // No hash prefix match; there are no ephemeral apps for this domain.
4852            return null;
4853        }
4854
4855        // Go in reverse order so we match the narrowest scope first.
4856        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4857            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4858                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4859                    continue;
4860                }
4861                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4862                // No filters; this should never happen.
4863                if (filters.isEmpty()) {
4864                    continue;
4865                }
4866                if (packageName != null
4867                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4868                    continue;
4869                }
4870                // We have a domain match; resolve the filters to see if anything matches.
4871                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4872                for (int j = filters.size() - 1; j >= 0; --j) {
4873                    final EphemeralResolveIntentInfo intentInfo =
4874                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4875                    ephemeralResolver.addFilter(intentInfo);
4876                }
4877                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4878                        intent, resolvedType, false /*defaultOnly*/, userId);
4879                if (!matchedResolveInfoList.isEmpty()) {
4880                    return matchedResolveInfoList.get(0);
4881                }
4882            }
4883        }
4884        // Hash or filter mis-match; no ephemeral apps for this domain.
4885        return null;
4886    }
4887
4888    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4889            int flags, List<ResolveInfo> query, int userId) {
4890        if (query != null) {
4891            final int N = query.size();
4892            if (N == 1) {
4893                return query.get(0);
4894            } else if (N > 1) {
4895                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4896                // If there is more than one activity with the same priority,
4897                // then let the user decide between them.
4898                ResolveInfo r0 = query.get(0);
4899                ResolveInfo r1 = query.get(1);
4900                if (DEBUG_INTENT_MATCHING || debug) {
4901                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4902                            + r1.activityInfo.name + "=" + r1.priority);
4903                }
4904                // If the first activity has a higher priority, or a different
4905                // default, then it is always desirable to pick it.
4906                if (r0.priority != r1.priority
4907                        || r0.preferredOrder != r1.preferredOrder
4908                        || r0.isDefault != r1.isDefault) {
4909                    return query.get(0);
4910                }
4911                // If we have saved a preference for a preferred activity for
4912                // this Intent, use that.
4913                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4914                        flags, query, r0.priority, true, false, debug, userId);
4915                if (ri != null) {
4916                    return ri;
4917                }
4918                ri = new ResolveInfo(mResolveInfo);
4919                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4920                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4921                // If all of the options come from the same package, show the application's
4922                // label and icon instead of the generic resolver's.
4923                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
4924                // and then throw away the ResolveInfo itself, meaning that the caller loses
4925                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
4926                // a fallback for this case; we only set the target package's resources on
4927                // the ResolveInfo, not the ActivityInfo.
4928                final String intentPackage = intent.getPackage();
4929                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
4930                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
4931                    ri.resolvePackageName = intentPackage;
4932                    if (userNeedsBadging(userId)) {
4933                        ri.noResourceId = true;
4934                    } else {
4935                        ri.icon = appi.icon;
4936                    }
4937                    ri.iconResourceId = appi.icon;
4938                    ri.labelRes = appi.labelRes;
4939                }
4940                ri.activityInfo.applicationInfo = new ApplicationInfo(
4941                        ri.activityInfo.applicationInfo);
4942                if (userId != 0) {
4943                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4944                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4945                }
4946                // Make sure that the resolver is displayable in car mode
4947                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4948                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4949                return ri;
4950            }
4951        }
4952        return null;
4953    }
4954
4955    /**
4956     * Return true if the given list is not empty and all of its contents have
4957     * an activityInfo with the given package name.
4958     */
4959    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
4960        if (ArrayUtils.isEmpty(list)) {
4961            return false;
4962        }
4963        for (int i = 0, N = list.size(); i < N; i++) {
4964            final ResolveInfo ri = list.get(i);
4965            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
4966            if (ai == null || !packageName.equals(ai.packageName)) {
4967                return false;
4968            }
4969        }
4970        return true;
4971    }
4972
4973    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4974            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4975        final int N = query.size();
4976        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4977                .get(userId);
4978        // Get the list of persistent preferred activities that handle the intent
4979        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4980        List<PersistentPreferredActivity> pprefs = ppir != null
4981                ? ppir.queryIntent(intent, resolvedType,
4982                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4983                : null;
4984        if (pprefs != null && pprefs.size() > 0) {
4985            final int M = pprefs.size();
4986            for (int i=0; i<M; i++) {
4987                final PersistentPreferredActivity ppa = pprefs.get(i);
4988                if (DEBUG_PREFERRED || debug) {
4989                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4990                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4991                            + "\n  component=" + ppa.mComponent);
4992                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4993                }
4994                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4995                        flags | MATCH_DISABLED_COMPONENTS, userId);
4996                if (DEBUG_PREFERRED || debug) {
4997                    Slog.v(TAG, "Found persistent preferred activity:");
4998                    if (ai != null) {
4999                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5000                    } else {
5001                        Slog.v(TAG, "  null");
5002                    }
5003                }
5004                if (ai == null) {
5005                    // This previously registered persistent preferred activity
5006                    // component is no longer known. Ignore it and do NOT remove it.
5007                    continue;
5008                }
5009                for (int j=0; j<N; j++) {
5010                    final ResolveInfo ri = query.get(j);
5011                    if (!ri.activityInfo.applicationInfo.packageName
5012                            .equals(ai.applicationInfo.packageName)) {
5013                        continue;
5014                    }
5015                    if (!ri.activityInfo.name.equals(ai.name)) {
5016                        continue;
5017                    }
5018                    //  Found a persistent preference that can handle the intent.
5019                    if (DEBUG_PREFERRED || debug) {
5020                        Slog.v(TAG, "Returning persistent preferred activity: " +
5021                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5022                    }
5023                    return ri;
5024                }
5025            }
5026        }
5027        return null;
5028    }
5029
5030    // TODO: handle preferred activities missing while user has amnesia
5031    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5032            List<ResolveInfo> query, int priority, boolean always,
5033            boolean removeMatches, boolean debug, int userId) {
5034        if (!sUserManager.exists(userId)) return null;
5035        flags = updateFlagsForResolve(flags, userId, intent);
5036        // writer
5037        synchronized (mPackages) {
5038            if (intent.getSelector() != null) {
5039                intent = intent.getSelector();
5040            }
5041            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5042
5043            // Try to find a matching persistent preferred activity.
5044            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5045                    debug, userId);
5046
5047            // If a persistent preferred activity matched, use it.
5048            if (pri != null) {
5049                return pri;
5050            }
5051
5052            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5053            // Get the list of preferred activities that handle the intent
5054            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5055            List<PreferredActivity> prefs = pir != null
5056                    ? pir.queryIntent(intent, resolvedType,
5057                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5058                    : null;
5059            if (prefs != null && prefs.size() > 0) {
5060                boolean changed = false;
5061                try {
5062                    // First figure out how good the original match set is.
5063                    // We will only allow preferred activities that came
5064                    // from the same match quality.
5065                    int match = 0;
5066
5067                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5068
5069                    final int N = query.size();
5070                    for (int j=0; j<N; j++) {
5071                        final ResolveInfo ri = query.get(j);
5072                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5073                                + ": 0x" + Integer.toHexString(match));
5074                        if (ri.match > match) {
5075                            match = ri.match;
5076                        }
5077                    }
5078
5079                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5080                            + Integer.toHexString(match));
5081
5082                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5083                    final int M = prefs.size();
5084                    for (int i=0; i<M; i++) {
5085                        final PreferredActivity pa = prefs.get(i);
5086                        if (DEBUG_PREFERRED || debug) {
5087                            Slog.v(TAG, "Checking PreferredActivity ds="
5088                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5089                                    + "\n  component=" + pa.mPref.mComponent);
5090                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5091                        }
5092                        if (pa.mPref.mMatch != match) {
5093                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5094                                    + Integer.toHexString(pa.mPref.mMatch));
5095                            continue;
5096                        }
5097                        // If it's not an "always" type preferred activity and that's what we're
5098                        // looking for, skip it.
5099                        if (always && !pa.mPref.mAlways) {
5100                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5101                            continue;
5102                        }
5103                        final ActivityInfo ai = getActivityInfo(
5104                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5105                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5106                                userId);
5107                        if (DEBUG_PREFERRED || debug) {
5108                            Slog.v(TAG, "Found preferred activity:");
5109                            if (ai != null) {
5110                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5111                            } else {
5112                                Slog.v(TAG, "  null");
5113                            }
5114                        }
5115                        if (ai == null) {
5116                            // This previously registered preferred activity
5117                            // component is no longer known.  Most likely an update
5118                            // to the app was installed and in the new version this
5119                            // component no longer exists.  Clean it up by removing
5120                            // it from the preferred activities list, and skip it.
5121                            Slog.w(TAG, "Removing dangling preferred activity: "
5122                                    + pa.mPref.mComponent);
5123                            pir.removeFilter(pa);
5124                            changed = true;
5125                            continue;
5126                        }
5127                        for (int j=0; j<N; j++) {
5128                            final ResolveInfo ri = query.get(j);
5129                            if (!ri.activityInfo.applicationInfo.packageName
5130                                    .equals(ai.applicationInfo.packageName)) {
5131                                continue;
5132                            }
5133                            if (!ri.activityInfo.name.equals(ai.name)) {
5134                                continue;
5135                            }
5136
5137                            if (removeMatches) {
5138                                pir.removeFilter(pa);
5139                                changed = true;
5140                                if (DEBUG_PREFERRED) {
5141                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5142                                }
5143                                break;
5144                            }
5145
5146                            // Okay we found a previously set preferred or last chosen app.
5147                            // If the result set is different from when this
5148                            // was created, we need to clear it and re-ask the
5149                            // user their preference, if we're looking for an "always" type entry.
5150                            if (always && !pa.mPref.sameSet(query)) {
5151                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5152                                        + intent + " type " + resolvedType);
5153                                if (DEBUG_PREFERRED) {
5154                                    Slog.v(TAG, "Removing preferred activity since set changed "
5155                                            + pa.mPref.mComponent);
5156                                }
5157                                pir.removeFilter(pa);
5158                                // Re-add the filter as a "last chosen" entry (!always)
5159                                PreferredActivity lastChosen = new PreferredActivity(
5160                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5161                                pir.addFilter(lastChosen);
5162                                changed = true;
5163                                return null;
5164                            }
5165
5166                            // Yay! Either the set matched or we're looking for the last chosen
5167                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5168                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5169                            return ri;
5170                        }
5171                    }
5172                } finally {
5173                    if (changed) {
5174                        if (DEBUG_PREFERRED) {
5175                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5176                        }
5177                        scheduleWritePackageRestrictionsLocked(userId);
5178                    }
5179                }
5180            }
5181        }
5182        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5183        return null;
5184    }
5185
5186    /*
5187     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5188     */
5189    @Override
5190    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5191            int targetUserId) {
5192        mContext.enforceCallingOrSelfPermission(
5193                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5194        List<CrossProfileIntentFilter> matches =
5195                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5196        if (matches != null) {
5197            int size = matches.size();
5198            for (int i = 0; i < size; i++) {
5199                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5200            }
5201        }
5202        if (hasWebURI(intent)) {
5203            // cross-profile app linking works only towards the parent.
5204            final UserInfo parent = getProfileParent(sourceUserId);
5205            synchronized(mPackages) {
5206                int flags = updateFlagsForResolve(0, parent.id, intent);
5207                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5208                        intent, resolvedType, flags, sourceUserId, parent.id);
5209                return xpDomainInfo != null;
5210            }
5211        }
5212        return false;
5213    }
5214
5215    private UserInfo getProfileParent(int userId) {
5216        final long identity = Binder.clearCallingIdentity();
5217        try {
5218            return sUserManager.getProfileParent(userId);
5219        } finally {
5220            Binder.restoreCallingIdentity(identity);
5221        }
5222    }
5223
5224    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5225            String resolvedType, int userId) {
5226        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5227        if (resolver != null) {
5228            return resolver.queryIntent(intent, resolvedType, false, userId);
5229        }
5230        return null;
5231    }
5232
5233    @Override
5234    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5235            String resolvedType, int flags, int userId) {
5236        try {
5237            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5238
5239            return new ParceledListSlice<>(
5240                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5241        } finally {
5242            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5243        }
5244    }
5245
5246    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5247            String resolvedType, int flags, int userId) {
5248        if (!sUserManager.exists(userId)) return Collections.emptyList();
5249        flags = updateFlagsForResolve(flags, userId, intent);
5250        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5251                false /* requireFullPermission */, false /* checkShell */,
5252                "query intent activities");
5253        ComponentName comp = intent.getComponent();
5254        if (comp == null) {
5255            if (intent.getSelector() != null) {
5256                intent = intent.getSelector();
5257                comp = intent.getComponent();
5258            }
5259        }
5260
5261        if (comp != null) {
5262            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5263            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5264            if (ai != null) {
5265                final ResolveInfo ri = new ResolveInfo();
5266                ri.activityInfo = ai;
5267                list.add(ri);
5268            }
5269            return list;
5270        }
5271
5272        // reader
5273        boolean sortResult = false;
5274        boolean addEphemeral = false;
5275        boolean matchEphemeralPackage = false;
5276        List<ResolveInfo> result;
5277        final String pkgName = intent.getPackage();
5278        synchronized (mPackages) {
5279            if (pkgName == null) {
5280                List<CrossProfileIntentFilter> matchingFilters =
5281                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5282                // Check for results that need to skip the current profile.
5283                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5284                        resolvedType, flags, userId);
5285                if (xpResolveInfo != null) {
5286                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5287                    xpResult.add(xpResolveInfo);
5288                    return filterIfNotSystemUser(xpResult, userId);
5289                }
5290
5291                // Check for results in the current profile.
5292                result = filterIfNotSystemUser(mActivities.queryIntent(
5293                        intent, resolvedType, flags, userId), userId);
5294                addEphemeral =
5295                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5296
5297                // Check for cross profile results.
5298                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5299                xpResolveInfo = queryCrossProfileIntents(
5300                        matchingFilters, intent, resolvedType, flags, userId,
5301                        hasNonNegativePriorityResult);
5302                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5303                    boolean isVisibleToUser = filterIfNotSystemUser(
5304                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5305                    if (isVisibleToUser) {
5306                        result.add(xpResolveInfo);
5307                        sortResult = true;
5308                    }
5309                }
5310                if (hasWebURI(intent)) {
5311                    CrossProfileDomainInfo xpDomainInfo = null;
5312                    final UserInfo parent = getProfileParent(userId);
5313                    if (parent != null) {
5314                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5315                                flags, userId, parent.id);
5316                    }
5317                    if (xpDomainInfo != null) {
5318                        if (xpResolveInfo != null) {
5319                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5320                            // in the result.
5321                            result.remove(xpResolveInfo);
5322                        }
5323                        if (result.size() == 0 && !addEphemeral) {
5324                            result.add(xpDomainInfo.resolveInfo);
5325                            return result;
5326                        }
5327                    }
5328                    if (result.size() > 1 || addEphemeral) {
5329                        result = filterCandidatesWithDomainPreferredActivitiesLPr(
5330                                intent, flags, result, xpDomainInfo, userId);
5331                        sortResult = true;
5332                    }
5333                }
5334            } else {
5335                final PackageParser.Package pkg = mPackages.get(pkgName);
5336                if (pkg != null) {
5337                    result = filterIfNotSystemUser(
5338                            mActivities.queryIntentForPackage(
5339                                    intent, resolvedType, flags, pkg.activities, userId),
5340                            userId);
5341                } else {
5342                    // the caller wants to resolve for a particular package; however, there
5343                    // were no installed results, so, try to find an ephemeral result
5344                    addEphemeral = isEphemeralAllowed(
5345                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5346                    matchEphemeralPackage = true;
5347                    result = new ArrayList<ResolveInfo>();
5348                }
5349            }
5350        }
5351        if (addEphemeral) {
5352            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5353            final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5354                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5355                    matchEphemeralPackage ? pkgName : null);
5356            if (ai != null) {
5357                if (DEBUG_EPHEMERAL) {
5358                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5359                }
5360                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5361                ephemeralInstaller.ephemeralResolveInfo = ai;
5362                // make sure this resolver is the default
5363                ephemeralInstaller.isDefault = true;
5364                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5365                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5366                // add a non-generic filter
5367                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5368                ephemeralInstaller.filter.addDataPath(
5369                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5370                result.add(ephemeralInstaller);
5371            }
5372            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5373        }
5374        if (sortResult) {
5375            Collections.sort(result, mResolvePrioritySorter);
5376        }
5377        return result;
5378    }
5379
5380    private static class CrossProfileDomainInfo {
5381        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5382        ResolveInfo resolveInfo;
5383        /* Best domain verification status of the activities found in the other profile */
5384        int bestDomainVerificationStatus;
5385    }
5386
5387    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5388            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5389        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5390                sourceUserId)) {
5391            return null;
5392        }
5393        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5394                resolvedType, flags, parentUserId);
5395
5396        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5397            return null;
5398        }
5399        CrossProfileDomainInfo result = null;
5400        int size = resultTargetUser.size();
5401        for (int i = 0; i < size; i++) {
5402            ResolveInfo riTargetUser = resultTargetUser.get(i);
5403            // Intent filter verification is only for filters that specify a host. So don't return
5404            // those that handle all web uris.
5405            if (riTargetUser.handleAllWebDataURI) {
5406                continue;
5407            }
5408            String packageName = riTargetUser.activityInfo.packageName;
5409            PackageSetting ps = mSettings.mPackages.get(packageName);
5410            if (ps == null) {
5411                continue;
5412            }
5413            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5414            int status = (int)(verificationState >> 32);
5415            if (result == null) {
5416                result = new CrossProfileDomainInfo();
5417                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5418                        sourceUserId, parentUserId);
5419                result.bestDomainVerificationStatus = status;
5420            } else {
5421                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5422                        result.bestDomainVerificationStatus);
5423            }
5424        }
5425        // Don't consider matches with status NEVER across profiles.
5426        if (result != null && result.bestDomainVerificationStatus
5427                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5428            return null;
5429        }
5430        return result;
5431    }
5432
5433    /**
5434     * Verification statuses are ordered from the worse to the best, except for
5435     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5436     */
5437    private int bestDomainVerificationStatus(int status1, int status2) {
5438        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5439            return status2;
5440        }
5441        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5442            return status1;
5443        }
5444        return (int) MathUtils.max(status1, status2);
5445    }
5446
5447    private boolean isUserEnabled(int userId) {
5448        long callingId = Binder.clearCallingIdentity();
5449        try {
5450            UserInfo userInfo = sUserManager.getUserInfo(userId);
5451            return userInfo != null && userInfo.isEnabled();
5452        } finally {
5453            Binder.restoreCallingIdentity(callingId);
5454        }
5455    }
5456
5457    /**
5458     * Filter out activities with systemUserOnly flag set, when current user is not System.
5459     *
5460     * @return filtered list
5461     */
5462    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5463        if (userId == UserHandle.USER_SYSTEM) {
5464            return resolveInfos;
5465        }
5466        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5467            ResolveInfo info = resolveInfos.get(i);
5468            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5469                resolveInfos.remove(i);
5470            }
5471        }
5472        return resolveInfos;
5473    }
5474
5475    /**
5476     * @param resolveInfos list of resolve infos in descending priority order
5477     * @return if the list contains a resolve info with non-negative priority
5478     */
5479    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5480        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5481    }
5482
5483    private static boolean hasWebURI(Intent intent) {
5484        if (intent.getData() == null) {
5485            return false;
5486        }
5487        final String scheme = intent.getScheme();
5488        if (TextUtils.isEmpty(scheme)) {
5489            return false;
5490        }
5491        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5492    }
5493
5494    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5495            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5496            int userId) {
5497        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5498
5499        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5500            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5501                    candidates.size());
5502        }
5503
5504        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5505        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5506        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5507        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5508        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5509        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5510
5511        synchronized (mPackages) {
5512            final int count = candidates.size();
5513            // First, try to use linked apps. Partition the candidates into four lists:
5514            // one for the final results, one for the "do not use ever", one for "undefined status"
5515            // and finally one for "browser app type".
5516            for (int n=0; n<count; n++) {
5517                ResolveInfo info = candidates.get(n);
5518                String packageName = info.activityInfo.packageName;
5519                PackageSetting ps = mSettings.mPackages.get(packageName);
5520                if (ps != null) {
5521                    // Add to the special match all list (Browser use case)
5522                    if (info.handleAllWebDataURI) {
5523                        matchAllList.add(info);
5524                        continue;
5525                    }
5526                    // Try to get the status from User settings first
5527                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5528                    int status = (int)(packedStatus >> 32);
5529                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5530                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5531                        if (DEBUG_DOMAIN_VERIFICATION) {
5532                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5533                                    + " : linkgen=" + linkGeneration);
5534                        }
5535                        // Use link-enabled generation as preferredOrder, i.e.
5536                        // prefer newly-enabled over earlier-enabled.
5537                        info.preferredOrder = linkGeneration;
5538                        alwaysList.add(info);
5539                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5540                        if (DEBUG_DOMAIN_VERIFICATION) {
5541                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5542                        }
5543                        neverList.add(info);
5544                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5545                        if (DEBUG_DOMAIN_VERIFICATION) {
5546                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5547                        }
5548                        alwaysAskList.add(info);
5549                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5550                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5551                        if (DEBUG_DOMAIN_VERIFICATION) {
5552                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5553                        }
5554                        undefinedList.add(info);
5555                    }
5556                }
5557            }
5558
5559            // We'll want to include browser possibilities in a few cases
5560            boolean includeBrowser = false;
5561
5562            // First try to add the "always" resolution(s) for the current user, if any
5563            if (alwaysList.size() > 0) {
5564                result.addAll(alwaysList);
5565            } else {
5566                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5567                result.addAll(undefinedList);
5568                // Maybe add one for the other profile.
5569                if (xpDomainInfo != null && (
5570                        xpDomainInfo.bestDomainVerificationStatus
5571                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5572                    result.add(xpDomainInfo.resolveInfo);
5573                }
5574                includeBrowser = true;
5575            }
5576
5577            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5578            // If there were 'always' entries their preferred order has been set, so we also
5579            // back that off to make the alternatives equivalent
5580            if (alwaysAskList.size() > 0) {
5581                for (ResolveInfo i : result) {
5582                    i.preferredOrder = 0;
5583                }
5584                result.addAll(alwaysAskList);
5585                includeBrowser = true;
5586            }
5587
5588            if (includeBrowser) {
5589                // Also add browsers (all of them or only the default one)
5590                if (DEBUG_DOMAIN_VERIFICATION) {
5591                    Slog.v(TAG, "   ...including browsers in candidate set");
5592                }
5593                if ((matchFlags & MATCH_ALL) != 0) {
5594                    result.addAll(matchAllList);
5595                } else {
5596                    // Browser/generic handling case.  If there's a default browser, go straight
5597                    // to that (but only if there is no other higher-priority match).
5598                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5599                    int maxMatchPrio = 0;
5600                    ResolveInfo defaultBrowserMatch = null;
5601                    final int numCandidates = matchAllList.size();
5602                    for (int n = 0; n < numCandidates; n++) {
5603                        ResolveInfo info = matchAllList.get(n);
5604                        // track the highest overall match priority...
5605                        if (info.priority > maxMatchPrio) {
5606                            maxMatchPrio = info.priority;
5607                        }
5608                        // ...and the highest-priority default browser match
5609                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5610                            if (defaultBrowserMatch == null
5611                                    || (defaultBrowserMatch.priority < info.priority)) {
5612                                if (debug) {
5613                                    Slog.v(TAG, "Considering default browser match " + info);
5614                                }
5615                                defaultBrowserMatch = info;
5616                            }
5617                        }
5618                    }
5619                    if (defaultBrowserMatch != null
5620                            && defaultBrowserMatch.priority >= maxMatchPrio
5621                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5622                    {
5623                        if (debug) {
5624                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5625                        }
5626                        result.add(defaultBrowserMatch);
5627                    } else {
5628                        result.addAll(matchAllList);
5629                    }
5630                }
5631
5632                // If there is nothing selected, add all candidates and remove the ones that the user
5633                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5634                if (result.size() == 0) {
5635                    result.addAll(candidates);
5636                    result.removeAll(neverList);
5637                }
5638            }
5639        }
5640        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5641            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5642                    result.size());
5643            for (ResolveInfo info : result) {
5644                Slog.v(TAG, "  + " + info.activityInfo);
5645            }
5646        }
5647        return result;
5648    }
5649
5650    // Returns a packed value as a long:
5651    //
5652    // high 'int'-sized word: link status: undefined/ask/never/always.
5653    // low 'int'-sized word: relative priority among 'always' results.
5654    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5655        long result = ps.getDomainVerificationStatusForUser(userId);
5656        // if none available, get the master status
5657        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5658            if (ps.getIntentFilterVerificationInfo() != null) {
5659                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5660            }
5661        }
5662        return result;
5663    }
5664
5665    private ResolveInfo querySkipCurrentProfileIntents(
5666            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5667            int flags, int sourceUserId) {
5668        if (matchingFilters != null) {
5669            int size = matchingFilters.size();
5670            for (int i = 0; i < size; i ++) {
5671                CrossProfileIntentFilter filter = matchingFilters.get(i);
5672                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5673                    // Checking if there are activities in the target user that can handle the
5674                    // intent.
5675                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5676                            resolvedType, flags, sourceUserId);
5677                    if (resolveInfo != null) {
5678                        return resolveInfo;
5679                    }
5680                }
5681            }
5682        }
5683        return null;
5684    }
5685
5686    // Return matching ResolveInfo in target user if any.
5687    private ResolveInfo queryCrossProfileIntents(
5688            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5689            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5690        if (matchingFilters != null) {
5691            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5692            // match the same intent. For performance reasons, it is better not to
5693            // run queryIntent twice for the same userId
5694            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5695            int size = matchingFilters.size();
5696            for (int i = 0; i < size; i++) {
5697                CrossProfileIntentFilter filter = matchingFilters.get(i);
5698                int targetUserId = filter.getTargetUserId();
5699                boolean skipCurrentProfile =
5700                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5701                boolean skipCurrentProfileIfNoMatchFound =
5702                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5703                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5704                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5705                    // Checking if there are activities in the target user that can handle the
5706                    // intent.
5707                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5708                            resolvedType, flags, sourceUserId);
5709                    if (resolveInfo != null) return resolveInfo;
5710                    alreadyTriedUserIds.put(targetUserId, true);
5711                }
5712            }
5713        }
5714        return null;
5715    }
5716
5717    /**
5718     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5719     * will forward the intent to the filter's target user.
5720     * Otherwise, returns null.
5721     */
5722    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5723            String resolvedType, int flags, int sourceUserId) {
5724        int targetUserId = filter.getTargetUserId();
5725        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5726                resolvedType, flags, targetUserId);
5727        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5728            // If all the matches in the target profile are suspended, return null.
5729            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5730                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5731                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5732                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5733                            targetUserId);
5734                }
5735            }
5736        }
5737        return null;
5738    }
5739
5740    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5741            int sourceUserId, int targetUserId) {
5742        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5743        long ident = Binder.clearCallingIdentity();
5744        boolean targetIsProfile;
5745        try {
5746            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5747        } finally {
5748            Binder.restoreCallingIdentity(ident);
5749        }
5750        String className;
5751        if (targetIsProfile) {
5752            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5753        } else {
5754            className = FORWARD_INTENT_TO_PARENT;
5755        }
5756        ComponentName forwardingActivityComponentName = new ComponentName(
5757                mAndroidApplication.packageName, className);
5758        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5759                sourceUserId);
5760        if (!targetIsProfile) {
5761            forwardingActivityInfo.showUserIcon = targetUserId;
5762            forwardingResolveInfo.noResourceId = true;
5763        }
5764        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5765        forwardingResolveInfo.priority = 0;
5766        forwardingResolveInfo.preferredOrder = 0;
5767        forwardingResolveInfo.match = 0;
5768        forwardingResolveInfo.isDefault = true;
5769        forwardingResolveInfo.filter = filter;
5770        forwardingResolveInfo.targetUserId = targetUserId;
5771        return forwardingResolveInfo;
5772    }
5773
5774    @Override
5775    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5776            Intent[] specifics, String[] specificTypes, Intent intent,
5777            String resolvedType, int flags, int userId) {
5778        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5779                specificTypes, intent, resolvedType, flags, userId));
5780    }
5781
5782    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5783            Intent[] specifics, String[] specificTypes, Intent intent,
5784            String resolvedType, int flags, int userId) {
5785        if (!sUserManager.exists(userId)) return Collections.emptyList();
5786        flags = updateFlagsForResolve(flags, userId, intent);
5787        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5788                false /* requireFullPermission */, false /* checkShell */,
5789                "query intent activity options");
5790        final String resultsAction = intent.getAction();
5791
5792        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5793                | PackageManager.GET_RESOLVED_FILTER, userId);
5794
5795        if (DEBUG_INTENT_MATCHING) {
5796            Log.v(TAG, "Query " + intent + ": " + results);
5797        }
5798
5799        int specificsPos = 0;
5800        int N;
5801
5802        // todo: note that the algorithm used here is O(N^2).  This
5803        // isn't a problem in our current environment, but if we start running
5804        // into situations where we have more than 5 or 10 matches then this
5805        // should probably be changed to something smarter...
5806
5807        // First we go through and resolve each of the specific items
5808        // that were supplied, taking care of removing any corresponding
5809        // duplicate items in the generic resolve list.
5810        if (specifics != null) {
5811            for (int i=0; i<specifics.length; i++) {
5812                final Intent sintent = specifics[i];
5813                if (sintent == null) {
5814                    continue;
5815                }
5816
5817                if (DEBUG_INTENT_MATCHING) {
5818                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5819                }
5820
5821                String action = sintent.getAction();
5822                if (resultsAction != null && resultsAction.equals(action)) {
5823                    // If this action was explicitly requested, then don't
5824                    // remove things that have it.
5825                    action = null;
5826                }
5827
5828                ResolveInfo ri = null;
5829                ActivityInfo ai = null;
5830
5831                ComponentName comp = sintent.getComponent();
5832                if (comp == null) {
5833                    ri = resolveIntent(
5834                        sintent,
5835                        specificTypes != null ? specificTypes[i] : null,
5836                            flags, userId);
5837                    if (ri == null) {
5838                        continue;
5839                    }
5840                    if (ri == mResolveInfo) {
5841                        // ACK!  Must do something better with this.
5842                    }
5843                    ai = ri.activityInfo;
5844                    comp = new ComponentName(ai.applicationInfo.packageName,
5845                            ai.name);
5846                } else {
5847                    ai = getActivityInfo(comp, flags, userId);
5848                    if (ai == null) {
5849                        continue;
5850                    }
5851                }
5852
5853                // Look for any generic query activities that are duplicates
5854                // of this specific one, and remove them from the results.
5855                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5856                N = results.size();
5857                int j;
5858                for (j=specificsPos; j<N; j++) {
5859                    ResolveInfo sri = results.get(j);
5860                    if ((sri.activityInfo.name.equals(comp.getClassName())
5861                            && sri.activityInfo.applicationInfo.packageName.equals(
5862                                    comp.getPackageName()))
5863                        || (action != null && sri.filter.matchAction(action))) {
5864                        results.remove(j);
5865                        if (DEBUG_INTENT_MATCHING) Log.v(
5866                            TAG, "Removing duplicate item from " + j
5867                            + " due to specific " + specificsPos);
5868                        if (ri == null) {
5869                            ri = sri;
5870                        }
5871                        j--;
5872                        N--;
5873                    }
5874                }
5875
5876                // Add this specific item to its proper place.
5877                if (ri == null) {
5878                    ri = new ResolveInfo();
5879                    ri.activityInfo = ai;
5880                }
5881                results.add(specificsPos, ri);
5882                ri.specificIndex = i;
5883                specificsPos++;
5884            }
5885        }
5886
5887        // Now we go through the remaining generic results and remove any
5888        // duplicate actions that are found here.
5889        N = results.size();
5890        for (int i=specificsPos; i<N-1; i++) {
5891            final ResolveInfo rii = results.get(i);
5892            if (rii.filter == null) {
5893                continue;
5894            }
5895
5896            // Iterate over all of the actions of this result's intent
5897            // filter...  typically this should be just one.
5898            final Iterator<String> it = rii.filter.actionsIterator();
5899            if (it == null) {
5900                continue;
5901            }
5902            while (it.hasNext()) {
5903                final String action = it.next();
5904                if (resultsAction != null && resultsAction.equals(action)) {
5905                    // If this action was explicitly requested, then don't
5906                    // remove things that have it.
5907                    continue;
5908                }
5909                for (int j=i+1; j<N; j++) {
5910                    final ResolveInfo rij = results.get(j);
5911                    if (rij.filter != null && rij.filter.hasAction(action)) {
5912                        results.remove(j);
5913                        if (DEBUG_INTENT_MATCHING) Log.v(
5914                            TAG, "Removing duplicate item from " + j
5915                            + " due to action " + action + " at " + i);
5916                        j--;
5917                        N--;
5918                    }
5919                }
5920            }
5921
5922            // If the caller didn't request filter information, drop it now
5923            // so we don't have to marshall/unmarshall it.
5924            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5925                rii.filter = null;
5926            }
5927        }
5928
5929        // Filter out the caller activity if so requested.
5930        if (caller != null) {
5931            N = results.size();
5932            for (int i=0; i<N; i++) {
5933                ActivityInfo ainfo = results.get(i).activityInfo;
5934                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5935                        && caller.getClassName().equals(ainfo.name)) {
5936                    results.remove(i);
5937                    break;
5938                }
5939            }
5940        }
5941
5942        // If the caller didn't request filter information,
5943        // drop them now so we don't have to
5944        // marshall/unmarshall it.
5945        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5946            N = results.size();
5947            for (int i=0; i<N; i++) {
5948                results.get(i).filter = null;
5949            }
5950        }
5951
5952        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5953        return results;
5954    }
5955
5956    @Override
5957    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5958            String resolvedType, int flags, int userId) {
5959        return new ParceledListSlice<>(
5960                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5961    }
5962
5963    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5964            String resolvedType, int flags, int userId) {
5965        if (!sUserManager.exists(userId)) return Collections.emptyList();
5966        flags = updateFlagsForResolve(flags, userId, intent);
5967        ComponentName comp = intent.getComponent();
5968        if (comp == null) {
5969            if (intent.getSelector() != null) {
5970                intent = intent.getSelector();
5971                comp = intent.getComponent();
5972            }
5973        }
5974        if (comp != null) {
5975            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5976            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5977            if (ai != null) {
5978                ResolveInfo ri = new ResolveInfo();
5979                ri.activityInfo = ai;
5980                list.add(ri);
5981            }
5982            return list;
5983        }
5984
5985        // reader
5986        synchronized (mPackages) {
5987            String pkgName = intent.getPackage();
5988            if (pkgName == null) {
5989                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5990            }
5991            final PackageParser.Package pkg = mPackages.get(pkgName);
5992            if (pkg != null) {
5993                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5994                        userId);
5995            }
5996            return Collections.emptyList();
5997        }
5998    }
5999
6000    @Override
6001    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6002        if (!sUserManager.exists(userId)) return null;
6003        flags = updateFlagsForResolve(flags, userId, intent);
6004        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6005        if (query != null) {
6006            if (query.size() >= 1) {
6007                // If there is more than one service with the same priority,
6008                // just arbitrarily pick the first one.
6009                return query.get(0);
6010            }
6011        }
6012        return null;
6013    }
6014
6015    @Override
6016    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6017            String resolvedType, int flags, int userId) {
6018        return new ParceledListSlice<>(
6019                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6020    }
6021
6022    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6023            String resolvedType, int flags, int userId) {
6024        if (!sUserManager.exists(userId)) return Collections.emptyList();
6025        flags = updateFlagsForResolve(flags, userId, intent);
6026        ComponentName comp = intent.getComponent();
6027        if (comp == null) {
6028            if (intent.getSelector() != null) {
6029                intent = intent.getSelector();
6030                comp = intent.getComponent();
6031            }
6032        }
6033        if (comp != null) {
6034            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6035            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6036            if (si != null) {
6037                final ResolveInfo ri = new ResolveInfo();
6038                ri.serviceInfo = si;
6039                list.add(ri);
6040            }
6041            return list;
6042        }
6043
6044        // reader
6045        synchronized (mPackages) {
6046            String pkgName = intent.getPackage();
6047            if (pkgName == null) {
6048                return mServices.queryIntent(intent, resolvedType, flags, userId);
6049            }
6050            final PackageParser.Package pkg = mPackages.get(pkgName);
6051            if (pkg != null) {
6052                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6053                        userId);
6054            }
6055            return Collections.emptyList();
6056        }
6057    }
6058
6059    @Override
6060    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6061            String resolvedType, int flags, int userId) {
6062        return new ParceledListSlice<>(
6063                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6064    }
6065
6066    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6067            Intent intent, String resolvedType, int flags, int userId) {
6068        if (!sUserManager.exists(userId)) return Collections.emptyList();
6069        flags = updateFlagsForResolve(flags, userId, intent);
6070        ComponentName comp = intent.getComponent();
6071        if (comp == null) {
6072            if (intent.getSelector() != null) {
6073                intent = intent.getSelector();
6074                comp = intent.getComponent();
6075            }
6076        }
6077        if (comp != null) {
6078            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6079            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6080            if (pi != null) {
6081                final ResolveInfo ri = new ResolveInfo();
6082                ri.providerInfo = pi;
6083                list.add(ri);
6084            }
6085            return list;
6086        }
6087
6088        // reader
6089        synchronized (mPackages) {
6090            String pkgName = intent.getPackage();
6091            if (pkgName == null) {
6092                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6093            }
6094            final PackageParser.Package pkg = mPackages.get(pkgName);
6095            if (pkg != null) {
6096                return mProviders.queryIntentForPackage(
6097                        intent, resolvedType, flags, pkg.providers, userId);
6098            }
6099            return Collections.emptyList();
6100        }
6101    }
6102
6103    @Override
6104    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6105        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6106        flags = updateFlagsForPackage(flags, userId, null);
6107        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6108        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6109                true /* requireFullPermission */, false /* checkShell */,
6110                "get installed packages");
6111
6112        // writer
6113        synchronized (mPackages) {
6114            ArrayList<PackageInfo> list;
6115            if (listUninstalled) {
6116                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6117                for (PackageSetting ps : mSettings.mPackages.values()) {
6118                    final PackageInfo pi;
6119                    if (ps.pkg != null) {
6120                        pi = generatePackageInfo(ps, flags, userId);
6121                    } else {
6122                        pi = generatePackageInfo(ps, flags, userId);
6123                    }
6124                    if (pi != null) {
6125                        list.add(pi);
6126                    }
6127                }
6128            } else {
6129                list = new ArrayList<PackageInfo>(mPackages.size());
6130                for (PackageParser.Package p : mPackages.values()) {
6131                    final PackageInfo pi =
6132                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6133                    if (pi != null) {
6134                        list.add(pi);
6135                    }
6136                }
6137            }
6138
6139            return new ParceledListSlice<PackageInfo>(list);
6140        }
6141    }
6142
6143    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6144            String[] permissions, boolean[] tmp, int flags, int userId) {
6145        int numMatch = 0;
6146        final PermissionsState permissionsState = ps.getPermissionsState();
6147        for (int i=0; i<permissions.length; i++) {
6148            final String permission = permissions[i];
6149            if (permissionsState.hasPermission(permission, userId)) {
6150                tmp[i] = true;
6151                numMatch++;
6152            } else {
6153                tmp[i] = false;
6154            }
6155        }
6156        if (numMatch == 0) {
6157            return;
6158        }
6159        final PackageInfo pi;
6160        if (ps.pkg != null) {
6161            pi = generatePackageInfo(ps, flags, userId);
6162        } else {
6163            pi = generatePackageInfo(ps, flags, userId);
6164        }
6165        // The above might return null in cases of uninstalled apps or install-state
6166        // skew across users/profiles.
6167        if (pi != null) {
6168            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6169                if (numMatch == permissions.length) {
6170                    pi.requestedPermissions = permissions;
6171                } else {
6172                    pi.requestedPermissions = new String[numMatch];
6173                    numMatch = 0;
6174                    for (int i=0; i<permissions.length; i++) {
6175                        if (tmp[i]) {
6176                            pi.requestedPermissions[numMatch] = permissions[i];
6177                            numMatch++;
6178                        }
6179                    }
6180                }
6181            }
6182            list.add(pi);
6183        }
6184    }
6185
6186    @Override
6187    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6188            String[] permissions, int flags, int userId) {
6189        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6190        flags = updateFlagsForPackage(flags, userId, permissions);
6191        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6192
6193        // writer
6194        synchronized (mPackages) {
6195            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6196            boolean[] tmpBools = new boolean[permissions.length];
6197            if (listUninstalled) {
6198                for (PackageSetting ps : mSettings.mPackages.values()) {
6199                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6200                }
6201            } else {
6202                for (PackageParser.Package pkg : mPackages.values()) {
6203                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6204                    if (ps != null) {
6205                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6206                                userId);
6207                    }
6208                }
6209            }
6210
6211            return new ParceledListSlice<PackageInfo>(list);
6212        }
6213    }
6214
6215    @Override
6216    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6217        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6218        flags = updateFlagsForApplication(flags, userId, null);
6219        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6220
6221        // writer
6222        synchronized (mPackages) {
6223            ArrayList<ApplicationInfo> list;
6224            if (listUninstalled) {
6225                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6226                for (PackageSetting ps : mSettings.mPackages.values()) {
6227                    ApplicationInfo ai;
6228                    if (ps.pkg != null) {
6229                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6230                                ps.readUserState(userId), userId);
6231                    } else {
6232                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6233                    }
6234                    if (ai != null) {
6235                        list.add(ai);
6236                    }
6237                }
6238            } else {
6239                list = new ArrayList<ApplicationInfo>(mPackages.size());
6240                for (PackageParser.Package p : mPackages.values()) {
6241                    if (p.mExtras != null) {
6242                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6243                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6244                        if (ai != null) {
6245                            list.add(ai);
6246                        }
6247                    }
6248                }
6249            }
6250
6251            return new ParceledListSlice<ApplicationInfo>(list);
6252        }
6253    }
6254
6255    @Override
6256    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6257        if (isEphemeralDisabled()) {
6258            return null;
6259        }
6260
6261        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6262                "getEphemeralApplications");
6263        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6264                true /* requireFullPermission */, false /* checkShell */,
6265                "getEphemeralApplications");
6266        synchronized (mPackages) {
6267            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6268                    .getEphemeralApplicationsLPw(userId);
6269            if (ephemeralApps != null) {
6270                return new ParceledListSlice<>(ephemeralApps);
6271            }
6272        }
6273        return null;
6274    }
6275
6276    @Override
6277    public boolean isEphemeralApplication(String packageName, int userId) {
6278        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6279                true /* requireFullPermission */, false /* checkShell */,
6280                "isEphemeral");
6281        if (isEphemeralDisabled()) {
6282            return false;
6283        }
6284
6285        if (!isCallerSameApp(packageName)) {
6286            return false;
6287        }
6288        synchronized (mPackages) {
6289            PackageParser.Package pkg = mPackages.get(packageName);
6290            if (pkg != null) {
6291                return pkg.applicationInfo.isEphemeralApp();
6292            }
6293        }
6294        return false;
6295    }
6296
6297    @Override
6298    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6299        if (isEphemeralDisabled()) {
6300            return null;
6301        }
6302
6303        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6304                true /* requireFullPermission */, false /* checkShell */,
6305                "getCookie");
6306        if (!isCallerSameApp(packageName)) {
6307            return null;
6308        }
6309        synchronized (mPackages) {
6310            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6311                    packageName, userId);
6312        }
6313    }
6314
6315    @Override
6316    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6317        if (isEphemeralDisabled()) {
6318            return true;
6319        }
6320
6321        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6322                true /* requireFullPermission */, true /* checkShell */,
6323                "setCookie");
6324        if (!isCallerSameApp(packageName)) {
6325            return false;
6326        }
6327        synchronized (mPackages) {
6328            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6329                    packageName, cookie, userId);
6330        }
6331    }
6332
6333    @Override
6334    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6335        if (isEphemeralDisabled()) {
6336            return null;
6337        }
6338
6339        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6340                "getEphemeralApplicationIcon");
6341        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6342                true /* requireFullPermission */, false /* checkShell */,
6343                "getEphemeralApplicationIcon");
6344        synchronized (mPackages) {
6345            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6346                    packageName, userId);
6347        }
6348    }
6349
6350    private boolean isCallerSameApp(String packageName) {
6351        PackageParser.Package pkg = mPackages.get(packageName);
6352        return pkg != null
6353                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6354    }
6355
6356    @Override
6357    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6358        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6359    }
6360
6361    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6362        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6363
6364        // reader
6365        synchronized (mPackages) {
6366            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6367            final int userId = UserHandle.getCallingUserId();
6368            while (i.hasNext()) {
6369                final PackageParser.Package p = i.next();
6370                if (p.applicationInfo == null) continue;
6371
6372                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6373                        && !p.applicationInfo.isDirectBootAware();
6374                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6375                        && p.applicationInfo.isDirectBootAware();
6376
6377                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6378                        && (!mSafeMode || isSystemApp(p))
6379                        && (matchesUnaware || matchesAware)) {
6380                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6381                    if (ps != null) {
6382                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6383                                ps.readUserState(userId), userId);
6384                        if (ai != null) {
6385                            finalList.add(ai);
6386                        }
6387                    }
6388                }
6389            }
6390        }
6391
6392        return finalList;
6393    }
6394
6395    @Override
6396    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6397        if (!sUserManager.exists(userId)) return null;
6398        flags = updateFlagsForComponent(flags, userId, name);
6399        // reader
6400        synchronized (mPackages) {
6401            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6402            PackageSetting ps = provider != null
6403                    ? mSettings.mPackages.get(provider.owner.packageName)
6404                    : null;
6405            return ps != null
6406                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6407                    ? PackageParser.generateProviderInfo(provider, flags,
6408                            ps.readUserState(userId), userId)
6409                    : null;
6410        }
6411    }
6412
6413    /**
6414     * @deprecated
6415     */
6416    @Deprecated
6417    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6418        // reader
6419        synchronized (mPackages) {
6420            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6421                    .entrySet().iterator();
6422            final int userId = UserHandle.getCallingUserId();
6423            while (i.hasNext()) {
6424                Map.Entry<String, PackageParser.Provider> entry = i.next();
6425                PackageParser.Provider p = entry.getValue();
6426                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6427
6428                if (ps != null && p.syncable
6429                        && (!mSafeMode || (p.info.applicationInfo.flags
6430                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6431                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6432                            ps.readUserState(userId), userId);
6433                    if (info != null) {
6434                        outNames.add(entry.getKey());
6435                        outInfo.add(info);
6436                    }
6437                }
6438            }
6439        }
6440    }
6441
6442    @Override
6443    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6444            int uid, int flags) {
6445        final int userId = processName != null ? UserHandle.getUserId(uid)
6446                : UserHandle.getCallingUserId();
6447        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6448        flags = updateFlagsForComponent(flags, userId, processName);
6449
6450        ArrayList<ProviderInfo> finalList = null;
6451        // reader
6452        synchronized (mPackages) {
6453            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6454            while (i.hasNext()) {
6455                final PackageParser.Provider p = i.next();
6456                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6457                if (ps != null && p.info.authority != null
6458                        && (processName == null
6459                                || (p.info.processName.equals(processName)
6460                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6461                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6462                    if (finalList == null) {
6463                        finalList = new ArrayList<ProviderInfo>(3);
6464                    }
6465                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6466                            ps.readUserState(userId), userId);
6467                    if (info != null) {
6468                        finalList.add(info);
6469                    }
6470                }
6471            }
6472        }
6473
6474        if (finalList != null) {
6475            Collections.sort(finalList, mProviderInitOrderSorter);
6476            return new ParceledListSlice<ProviderInfo>(finalList);
6477        }
6478
6479        return ParceledListSlice.emptyList();
6480    }
6481
6482    @Override
6483    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6484        // reader
6485        synchronized (mPackages) {
6486            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6487            return PackageParser.generateInstrumentationInfo(i, flags);
6488        }
6489    }
6490
6491    @Override
6492    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6493            String targetPackage, int flags) {
6494        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6495    }
6496
6497    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6498            int flags) {
6499        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6500
6501        // reader
6502        synchronized (mPackages) {
6503            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6504            while (i.hasNext()) {
6505                final PackageParser.Instrumentation p = i.next();
6506                if (targetPackage == null
6507                        || targetPackage.equals(p.info.targetPackage)) {
6508                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6509                            flags);
6510                    if (ii != null) {
6511                        finalList.add(ii);
6512                    }
6513                }
6514            }
6515        }
6516
6517        return finalList;
6518    }
6519
6520    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6521        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6522        if (overlays == null) {
6523            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6524            return;
6525        }
6526        for (PackageParser.Package opkg : overlays.values()) {
6527            // Not much to do if idmap fails: we already logged the error
6528            // and we certainly don't want to abort installation of pkg simply
6529            // because an overlay didn't fit properly. For these reasons,
6530            // ignore the return value of createIdmapForPackagePairLI.
6531            createIdmapForPackagePairLI(pkg, opkg);
6532        }
6533    }
6534
6535    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6536            PackageParser.Package opkg) {
6537        if (!opkg.mTrustedOverlay) {
6538            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6539                    opkg.baseCodePath + ": overlay not trusted");
6540            return false;
6541        }
6542        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6543        if (overlaySet == null) {
6544            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6545                    opkg.baseCodePath + " but target package has no known overlays");
6546            return false;
6547        }
6548        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6549        // TODO: generate idmap for split APKs
6550        try {
6551            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6552        } catch (InstallerException e) {
6553            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6554                    + opkg.baseCodePath);
6555            return false;
6556        }
6557        PackageParser.Package[] overlayArray =
6558            overlaySet.values().toArray(new PackageParser.Package[0]);
6559        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6560            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6561                return p1.mOverlayPriority - p2.mOverlayPriority;
6562            }
6563        };
6564        Arrays.sort(overlayArray, cmp);
6565
6566        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6567        int i = 0;
6568        for (PackageParser.Package p : overlayArray) {
6569            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6570        }
6571        return true;
6572    }
6573
6574    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6575        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6576        try {
6577            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6578        } finally {
6579            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6580        }
6581    }
6582
6583    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6584        final File[] files = dir.listFiles();
6585        if (ArrayUtils.isEmpty(files)) {
6586            Log.d(TAG, "No files in app dir " + dir);
6587            return;
6588        }
6589
6590        if (DEBUG_PACKAGE_SCANNING) {
6591            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6592                    + " flags=0x" + Integer.toHexString(parseFlags));
6593        }
6594
6595        for (File file : files) {
6596            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6597                    && !PackageInstallerService.isStageName(file.getName());
6598            if (!isPackage) {
6599                // Ignore entries which are not packages
6600                continue;
6601            }
6602            try {
6603                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6604                        scanFlags, currentTime, null);
6605            } catch (PackageManagerException e) {
6606                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6607
6608                // Delete invalid userdata apps
6609                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6610                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6611                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6612                    removeCodePathLI(file);
6613                }
6614            }
6615        }
6616    }
6617
6618    private static File getSettingsProblemFile() {
6619        File dataDir = Environment.getDataDirectory();
6620        File systemDir = new File(dataDir, "system");
6621        File fname = new File(systemDir, "uiderrors.txt");
6622        return fname;
6623    }
6624
6625    static void reportSettingsProblem(int priority, String msg) {
6626        logCriticalInfo(priority, msg);
6627    }
6628
6629    static void logCriticalInfo(int priority, String msg) {
6630        Slog.println(priority, TAG, msg);
6631        EventLogTags.writePmCriticalInfo(msg);
6632        try {
6633            File fname = getSettingsProblemFile();
6634            FileOutputStream out = new FileOutputStream(fname, true);
6635            PrintWriter pw = new FastPrintWriter(out);
6636            SimpleDateFormat formatter = new SimpleDateFormat();
6637            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6638            pw.println(dateString + ": " + msg);
6639            pw.close();
6640            FileUtils.setPermissions(
6641                    fname.toString(),
6642                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6643                    -1, -1);
6644        } catch (java.io.IOException e) {
6645        }
6646    }
6647
6648    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6649        if (srcFile.isDirectory()) {
6650            final File baseFile = new File(pkg.baseCodePath);
6651            long maxModifiedTime = baseFile.lastModified();
6652            if (pkg.splitCodePaths != null) {
6653                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6654                    final File splitFile = new File(pkg.splitCodePaths[i]);
6655                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6656                }
6657            }
6658            return maxModifiedTime;
6659        }
6660        return srcFile.lastModified();
6661    }
6662
6663    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6664            final int policyFlags) throws PackageManagerException {
6665        // When upgrading from pre-N MR1, verify the package time stamp using the package
6666        // directory and not the APK file.
6667        final long lastModifiedTime = mIsPreNMR1Upgrade
6668                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6669        if (ps != null
6670                && ps.codePath.equals(srcFile)
6671                && ps.timeStamp == lastModifiedTime
6672                && !isCompatSignatureUpdateNeeded(pkg)
6673                && !isRecoverSignatureUpdateNeeded(pkg)) {
6674            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6675            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6676            ArraySet<PublicKey> signingKs;
6677            synchronized (mPackages) {
6678                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6679            }
6680            if (ps.signatures.mSignatures != null
6681                    && ps.signatures.mSignatures.length != 0
6682                    && signingKs != null) {
6683                // Optimization: reuse the existing cached certificates
6684                // if the package appears to be unchanged.
6685                pkg.mSignatures = ps.signatures.mSignatures;
6686                pkg.mSigningKeys = signingKs;
6687                return;
6688            }
6689
6690            Slog.w(TAG, "PackageSetting for " + ps.name
6691                    + " is missing signatures.  Collecting certs again to recover them.");
6692        } else {
6693            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6694        }
6695
6696        try {
6697            PackageParser.collectCertificates(pkg, policyFlags);
6698        } catch (PackageParserException e) {
6699            throw PackageManagerException.from(e);
6700        }
6701    }
6702
6703    /**
6704     *  Traces a package scan.
6705     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6706     */
6707    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6708            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6709        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6710        try {
6711            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6712        } finally {
6713            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6714        }
6715    }
6716
6717    /**
6718     *  Scans a package and returns the newly parsed package.
6719     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6720     */
6721    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6722            long currentTime, UserHandle user) throws PackageManagerException {
6723        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6724        PackageParser pp = new PackageParser();
6725        pp.setSeparateProcesses(mSeparateProcesses);
6726        pp.setOnlyCoreApps(mOnlyCore);
6727        pp.setDisplayMetrics(mMetrics);
6728
6729        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6730            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6731        }
6732
6733        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6734        final PackageParser.Package pkg;
6735        try {
6736            pkg = pp.parsePackage(scanFile, parseFlags);
6737        } catch (PackageParserException e) {
6738            throw PackageManagerException.from(e);
6739        } finally {
6740            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6741        }
6742
6743        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6744    }
6745
6746    /**
6747     *  Scans a package and returns the newly parsed package.
6748     *  @throws PackageManagerException on a parse error.
6749     */
6750    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6751            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6752            throws PackageManagerException {
6753        // If the package has children and this is the first dive in the function
6754        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6755        // packages (parent and children) would be successfully scanned before the
6756        // actual scan since scanning mutates internal state and we want to atomically
6757        // install the package and its children.
6758        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6759            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6760                scanFlags |= SCAN_CHECK_ONLY;
6761            }
6762        } else {
6763            scanFlags &= ~SCAN_CHECK_ONLY;
6764        }
6765
6766        // Scan the parent
6767        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6768                scanFlags, currentTime, user);
6769
6770        // Scan the children
6771        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6772        for (int i = 0; i < childCount; i++) {
6773            PackageParser.Package childPackage = pkg.childPackages.get(i);
6774            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6775                    currentTime, user);
6776        }
6777
6778
6779        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6780            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6781        }
6782
6783        return scannedPkg;
6784    }
6785
6786    /**
6787     *  Scans a package and returns the newly parsed package.
6788     *  @throws PackageManagerException on a parse error.
6789     */
6790    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6791            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6792            throws PackageManagerException {
6793        PackageSetting ps = null;
6794        PackageSetting updatedPkg;
6795        // reader
6796        synchronized (mPackages) {
6797            // Look to see if we already know about this package.
6798            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6799            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6800                // This package has been renamed to its original name.  Let's
6801                // use that.
6802                ps = mSettings.peekPackageLPr(oldName);
6803            }
6804            // If there was no original package, see one for the real package name.
6805            if (ps == null) {
6806                ps = mSettings.peekPackageLPr(pkg.packageName);
6807            }
6808            // Check to see if this package could be hiding/updating a system
6809            // package.  Must look for it either under the original or real
6810            // package name depending on our state.
6811            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6812            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6813
6814            // If this is a package we don't know about on the system partition, we
6815            // may need to remove disabled child packages on the system partition
6816            // or may need to not add child packages if the parent apk is updated
6817            // on the data partition and no longer defines this child package.
6818            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6819                // If this is a parent package for an updated system app and this system
6820                // app got an OTA update which no longer defines some of the child packages
6821                // we have to prune them from the disabled system packages.
6822                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6823                if (disabledPs != null) {
6824                    final int scannedChildCount = (pkg.childPackages != null)
6825                            ? pkg.childPackages.size() : 0;
6826                    final int disabledChildCount = disabledPs.childPackageNames != null
6827                            ? disabledPs.childPackageNames.size() : 0;
6828                    for (int i = 0; i < disabledChildCount; i++) {
6829                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6830                        boolean disabledPackageAvailable = false;
6831                        for (int j = 0; j < scannedChildCount; j++) {
6832                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6833                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6834                                disabledPackageAvailable = true;
6835                                break;
6836                            }
6837                         }
6838                         if (!disabledPackageAvailable) {
6839                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6840                         }
6841                    }
6842                }
6843            }
6844        }
6845
6846        boolean updatedPkgBetter = false;
6847        // First check if this is a system package that may involve an update
6848        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6849            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6850            // it needs to drop FLAG_PRIVILEGED.
6851            if (locationIsPrivileged(scanFile)) {
6852                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6853            } else {
6854                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6855            }
6856
6857            if (ps != null && !ps.codePath.equals(scanFile)) {
6858                // The path has changed from what was last scanned...  check the
6859                // version of the new path against what we have stored to determine
6860                // what to do.
6861                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6862                if (pkg.mVersionCode <= ps.versionCode) {
6863                    // The system package has been updated and the code path does not match
6864                    // Ignore entry. Skip it.
6865                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6866                            + " ignored: updated version " + ps.versionCode
6867                            + " better than this " + pkg.mVersionCode);
6868                    if (!updatedPkg.codePath.equals(scanFile)) {
6869                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6870                                + ps.name + " changing from " + updatedPkg.codePathString
6871                                + " to " + scanFile);
6872                        updatedPkg.codePath = scanFile;
6873                        updatedPkg.codePathString = scanFile.toString();
6874                        updatedPkg.resourcePath = scanFile;
6875                        updatedPkg.resourcePathString = scanFile.toString();
6876                    }
6877                    updatedPkg.pkg = pkg;
6878                    updatedPkg.versionCode = pkg.mVersionCode;
6879
6880                    // Update the disabled system child packages to point to the package too.
6881                    final int childCount = updatedPkg.childPackageNames != null
6882                            ? updatedPkg.childPackageNames.size() : 0;
6883                    for (int i = 0; i < childCount; i++) {
6884                        String childPackageName = updatedPkg.childPackageNames.get(i);
6885                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6886                                childPackageName);
6887                        if (updatedChildPkg != null) {
6888                            updatedChildPkg.pkg = pkg;
6889                            updatedChildPkg.versionCode = pkg.mVersionCode;
6890                        }
6891                    }
6892
6893                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6894                            + scanFile + " ignored: updated version " + ps.versionCode
6895                            + " better than this " + pkg.mVersionCode);
6896                } else {
6897                    // The current app on the system partition is better than
6898                    // what we have updated to on the data partition; switch
6899                    // back to the system partition version.
6900                    // At this point, its safely assumed that package installation for
6901                    // apps in system partition will go through. If not there won't be a working
6902                    // version of the app
6903                    // writer
6904                    synchronized (mPackages) {
6905                        // Just remove the loaded entries from package lists.
6906                        mPackages.remove(ps.name);
6907                    }
6908
6909                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6910                            + " reverting from " + ps.codePathString
6911                            + ": new version " + pkg.mVersionCode
6912                            + " better than installed " + ps.versionCode);
6913
6914                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6915                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6916                    synchronized (mInstallLock) {
6917                        args.cleanUpResourcesLI();
6918                    }
6919                    synchronized (mPackages) {
6920                        mSettings.enableSystemPackageLPw(ps.name);
6921                    }
6922                    updatedPkgBetter = true;
6923                }
6924            }
6925        }
6926
6927        if (updatedPkg != null) {
6928            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6929            // initially
6930            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6931
6932            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6933            // flag set initially
6934            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6935                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6936            }
6937        }
6938
6939        // Verify certificates against what was last scanned
6940        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6941
6942        /*
6943         * A new system app appeared, but we already had a non-system one of the
6944         * same name installed earlier.
6945         */
6946        boolean shouldHideSystemApp = false;
6947        if (updatedPkg == null && ps != null
6948                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6949            /*
6950             * Check to make sure the signatures match first. If they don't,
6951             * wipe the installed application and its data.
6952             */
6953            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6954                    != PackageManager.SIGNATURE_MATCH) {
6955                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6956                        + " signatures don't match existing userdata copy; removing");
6957                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6958                        "scanPackageInternalLI")) {
6959                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6960                }
6961                ps = null;
6962            } else {
6963                /*
6964                 * If the newly-added system app is an older version than the
6965                 * already installed version, hide it. It will be scanned later
6966                 * and re-added like an update.
6967                 */
6968                if (pkg.mVersionCode <= ps.versionCode) {
6969                    shouldHideSystemApp = true;
6970                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6971                            + " but new version " + pkg.mVersionCode + " better than installed "
6972                            + ps.versionCode + "; hiding system");
6973                } else {
6974                    /*
6975                     * The newly found system app is a newer version that the
6976                     * one previously installed. Simply remove the
6977                     * already-installed application and replace it with our own
6978                     * while keeping the application data.
6979                     */
6980                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6981                            + " reverting from " + ps.codePathString + ": new version "
6982                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6983                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6984                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6985                    synchronized (mInstallLock) {
6986                        args.cleanUpResourcesLI();
6987                    }
6988                }
6989            }
6990        }
6991
6992        // The apk is forward locked (not public) if its code and resources
6993        // are kept in different files. (except for app in either system or
6994        // vendor path).
6995        // TODO grab this value from PackageSettings
6996        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6997            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6998                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
6999            }
7000        }
7001
7002        // TODO: extend to support forward-locked splits
7003        String resourcePath = null;
7004        String baseResourcePath = null;
7005        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7006            if (ps != null && ps.resourcePathString != null) {
7007                resourcePath = ps.resourcePathString;
7008                baseResourcePath = ps.resourcePathString;
7009            } else {
7010                // Should not happen at all. Just log an error.
7011                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7012            }
7013        } else {
7014            resourcePath = pkg.codePath;
7015            baseResourcePath = pkg.baseCodePath;
7016        }
7017
7018        // Set application objects path explicitly.
7019        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7020        pkg.setApplicationInfoCodePath(pkg.codePath);
7021        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7022        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7023        pkg.setApplicationInfoResourcePath(resourcePath);
7024        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7025        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7026
7027        // Note that we invoke the following method only if we are about to unpack an application
7028        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7029                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7030
7031        /*
7032         * If the system app should be overridden by a previously installed
7033         * data, hide the system app now and let the /data/app scan pick it up
7034         * again.
7035         */
7036        if (shouldHideSystemApp) {
7037            synchronized (mPackages) {
7038                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7039            }
7040        }
7041
7042        return scannedPkg;
7043    }
7044
7045    private static String fixProcessName(String defProcessName,
7046            String processName, int uid) {
7047        if (processName == null) {
7048            return defProcessName;
7049        }
7050        return processName;
7051    }
7052
7053    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7054            throws PackageManagerException {
7055        if (pkgSetting.signatures.mSignatures != null) {
7056            // Already existing package. Make sure signatures match
7057            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7058                    == PackageManager.SIGNATURE_MATCH;
7059            if (!match) {
7060                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7061                        == PackageManager.SIGNATURE_MATCH;
7062            }
7063            if (!match) {
7064                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7065                        == PackageManager.SIGNATURE_MATCH;
7066            }
7067            if (!match) {
7068                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7069                        + pkg.packageName + " signatures do not match the "
7070                        + "previously installed version; ignoring!");
7071            }
7072        }
7073
7074        // Check for shared user signatures
7075        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7076            // Already existing package. Make sure signatures match
7077            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7078                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7079            if (!match) {
7080                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7081                        == PackageManager.SIGNATURE_MATCH;
7082            }
7083            if (!match) {
7084                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7085                        == PackageManager.SIGNATURE_MATCH;
7086            }
7087            if (!match) {
7088                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7089                        "Package " + pkg.packageName
7090                        + " has no signatures that match those in shared user "
7091                        + pkgSetting.sharedUser.name + "; ignoring!");
7092            }
7093        }
7094    }
7095
7096    /**
7097     * Enforces that only the system UID or root's UID can call a method exposed
7098     * via Binder.
7099     *
7100     * @param message used as message if SecurityException is thrown
7101     * @throws SecurityException if the caller is not system or root
7102     */
7103    private static final void enforceSystemOrRoot(String message) {
7104        final int uid = Binder.getCallingUid();
7105        if (uid != Process.SYSTEM_UID && uid != 0) {
7106            throw new SecurityException(message);
7107        }
7108    }
7109
7110    @Override
7111    public void performFstrimIfNeeded() {
7112        enforceSystemOrRoot("Only the system can request fstrim");
7113
7114        // Before everything else, see whether we need to fstrim.
7115        try {
7116            IMountService ms = PackageHelper.getMountService();
7117            if (ms != null) {
7118                boolean doTrim = false;
7119                final long interval = android.provider.Settings.Global.getLong(
7120                        mContext.getContentResolver(),
7121                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7122                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7123                if (interval > 0) {
7124                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7125                    if (timeSinceLast > interval) {
7126                        doTrim = true;
7127                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7128                                + "; running immediately");
7129                    }
7130                }
7131                if (doTrim) {
7132                    if (!isFirstBoot()) {
7133                        try {
7134                            ActivityManagerNative.getDefault().showBootMessage(
7135                                    mContext.getResources().getString(
7136                                            R.string.android_upgrading_fstrim), true);
7137                        } catch (RemoteException e) {
7138                        }
7139                    }
7140                    ms.runMaintenance();
7141                }
7142            } else {
7143                Slog.e(TAG, "Mount service unavailable!");
7144            }
7145        } catch (RemoteException e) {
7146            // Can't happen; MountService is local
7147        }
7148    }
7149
7150    @Override
7151    public void updatePackagesIfNeeded() {
7152        enforceSystemOrRoot("Only the system can request package update");
7153
7154        // We need to re-extract after an OTA.
7155        boolean causeUpgrade = isUpgrade();
7156
7157        // First boot or factory reset.
7158        // Note: we also handle devices that are upgrading to N right now as if it is their
7159        //       first boot, as they do not have profile data.
7160        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7161
7162        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7163        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7164
7165        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7166            return;
7167        }
7168
7169        List<PackageParser.Package> pkgs;
7170        synchronized (mPackages) {
7171            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7172        }
7173
7174        final long startTime = System.nanoTime();
7175        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7176                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7177
7178        final int elapsedTimeSeconds =
7179                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7180
7181        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7182        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7183        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7184        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7185        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7186    }
7187
7188    /**
7189     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7190     * containing statistics about the invocation. The array consists of three elements,
7191     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7192     * and {@code numberOfPackagesFailed}.
7193     */
7194    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7195            String compilerFilter) {
7196
7197        int numberOfPackagesVisited = 0;
7198        int numberOfPackagesOptimized = 0;
7199        int numberOfPackagesSkipped = 0;
7200        int numberOfPackagesFailed = 0;
7201        final int numberOfPackagesToDexopt = pkgs.size();
7202
7203        for (PackageParser.Package pkg : pkgs) {
7204            numberOfPackagesVisited++;
7205
7206            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7207                if (DEBUG_DEXOPT) {
7208                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7209                }
7210                numberOfPackagesSkipped++;
7211                continue;
7212            }
7213
7214            if (DEBUG_DEXOPT) {
7215                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7216                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7217            }
7218
7219            if (showDialog) {
7220                try {
7221                    ActivityManagerNative.getDefault().showBootMessage(
7222                            mContext.getResources().getString(R.string.android_upgrading_apk,
7223                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7224                } catch (RemoteException e) {
7225                }
7226            }
7227
7228            // If the OTA updates a system app which was previously preopted to a non-preopted state
7229            // the app might end up being verified at runtime. That's because by default the apps
7230            // are verify-profile but for preopted apps there's no profile.
7231            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7232            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7233            // filter (by default interpret-only).
7234            // Note that at this stage unused apps are already filtered.
7235            if (isSystemApp(pkg) &&
7236                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7237                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7238                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7239            }
7240
7241            // checkProfiles is false to avoid merging profiles during boot which
7242            // might interfere with background compilation (b/28612421).
7243            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7244            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7245            // trade-off worth doing to save boot time work.
7246            int dexOptStatus = performDexOptTraced(pkg.packageName,
7247                    false /* checkProfiles */,
7248                    compilerFilter,
7249                    false /* force */);
7250            switch (dexOptStatus) {
7251                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7252                    numberOfPackagesOptimized++;
7253                    break;
7254                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7255                    numberOfPackagesSkipped++;
7256                    break;
7257                case PackageDexOptimizer.DEX_OPT_FAILED:
7258                    numberOfPackagesFailed++;
7259                    break;
7260                default:
7261                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7262                    break;
7263            }
7264        }
7265
7266        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7267                numberOfPackagesFailed };
7268    }
7269
7270    @Override
7271    public void notifyPackageUse(String packageName, int reason) {
7272        synchronized (mPackages) {
7273            PackageParser.Package p = mPackages.get(packageName);
7274            if (p == null) {
7275                return;
7276            }
7277            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7278        }
7279    }
7280
7281    // TODO: this is not used nor needed. Delete it.
7282    @Override
7283    public boolean performDexOptIfNeeded(String packageName) {
7284        int dexOptStatus = performDexOptTraced(packageName,
7285                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7286        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7287    }
7288
7289    @Override
7290    public boolean performDexOpt(String packageName,
7291            boolean checkProfiles, int compileReason, boolean force) {
7292        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7293                getCompilerFilterForReason(compileReason), force);
7294        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7295    }
7296
7297    @Override
7298    public boolean performDexOptMode(String packageName,
7299            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7300        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7301                targetCompilerFilter, force);
7302        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7303    }
7304
7305    private int performDexOptTraced(String packageName,
7306                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7307        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7308        try {
7309            return performDexOptInternal(packageName, checkProfiles,
7310                    targetCompilerFilter, force);
7311        } finally {
7312            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7313        }
7314    }
7315
7316    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7317    // if the package can now be considered up to date for the given filter.
7318    private int performDexOptInternal(String packageName,
7319                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7320        PackageParser.Package p;
7321        synchronized (mPackages) {
7322            p = mPackages.get(packageName);
7323            if (p == null) {
7324                // Package could not be found. Report failure.
7325                return PackageDexOptimizer.DEX_OPT_FAILED;
7326            }
7327            mPackageUsage.maybeWriteAsync(mPackages);
7328            mCompilerStats.maybeWriteAsync();
7329        }
7330        long callingId = Binder.clearCallingIdentity();
7331        try {
7332            synchronized (mInstallLock) {
7333                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7334                        targetCompilerFilter, force);
7335            }
7336        } finally {
7337            Binder.restoreCallingIdentity(callingId);
7338        }
7339    }
7340
7341    public ArraySet<String> getOptimizablePackages() {
7342        ArraySet<String> pkgs = new ArraySet<String>();
7343        synchronized (mPackages) {
7344            for (PackageParser.Package p : mPackages.values()) {
7345                if (PackageDexOptimizer.canOptimizePackage(p)) {
7346                    pkgs.add(p.packageName);
7347                }
7348            }
7349        }
7350        return pkgs;
7351    }
7352
7353    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7354            boolean checkProfiles, String targetCompilerFilter,
7355            boolean force) {
7356        // Select the dex optimizer based on the force parameter.
7357        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7358        //       allocate an object here.
7359        PackageDexOptimizer pdo = force
7360                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7361                : mPackageDexOptimizer;
7362
7363        // Optimize all dependencies first. Note: we ignore the return value and march on
7364        // on errors.
7365        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7366        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7367        if (!deps.isEmpty()) {
7368            for (PackageParser.Package depPackage : deps) {
7369                // TODO: Analyze and investigate if we (should) profile libraries.
7370                // Currently this will do a full compilation of the library by default.
7371                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7372                        false /* checkProfiles */,
7373                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7374                        getOrCreateCompilerPackageStats(depPackage));
7375            }
7376        }
7377        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7378                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7379    }
7380
7381    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7382        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7383            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7384            Set<String> collectedNames = new HashSet<>();
7385            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7386
7387            retValue.remove(p);
7388
7389            return retValue;
7390        } else {
7391            return Collections.emptyList();
7392        }
7393    }
7394
7395    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7396            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7397        if (!collectedNames.contains(p.packageName)) {
7398            collectedNames.add(p.packageName);
7399            collected.add(p);
7400
7401            if (p.usesLibraries != null) {
7402                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7403            }
7404            if (p.usesOptionalLibraries != null) {
7405                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7406                        collectedNames);
7407            }
7408        }
7409    }
7410
7411    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7412            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7413        for (String libName : libs) {
7414            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7415            if (libPkg != null) {
7416                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7417            }
7418        }
7419    }
7420
7421    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7422        synchronized (mPackages) {
7423            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7424            if (lib != null && lib.apk != null) {
7425                return mPackages.get(lib.apk);
7426            }
7427        }
7428        return null;
7429    }
7430
7431    public void shutdown() {
7432        mPackageUsage.writeNow(mPackages);
7433        mCompilerStats.writeNow();
7434    }
7435
7436    @Override
7437    public void dumpProfiles(String packageName) {
7438        PackageParser.Package pkg;
7439        synchronized (mPackages) {
7440            pkg = mPackages.get(packageName);
7441            if (pkg == null) {
7442                throw new IllegalArgumentException("Unknown package: " + packageName);
7443            }
7444        }
7445        /* Only the shell, root, or the app user should be able to dump profiles. */
7446        int callingUid = Binder.getCallingUid();
7447        if (callingUid != Process.SHELL_UID &&
7448            callingUid != Process.ROOT_UID &&
7449            callingUid != pkg.applicationInfo.uid) {
7450            throw new SecurityException("dumpProfiles");
7451        }
7452
7453        synchronized (mInstallLock) {
7454            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7455            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7456            try {
7457                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7458                String gid = Integer.toString(sharedGid);
7459                String codePaths = TextUtils.join(";", allCodePaths);
7460                mInstaller.dumpProfiles(gid, packageName, codePaths);
7461            } catch (InstallerException e) {
7462                Slog.w(TAG, "Failed to dump profiles", e);
7463            }
7464            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7465        }
7466    }
7467
7468    @Override
7469    public void forceDexOpt(String packageName) {
7470        enforceSystemOrRoot("forceDexOpt");
7471
7472        PackageParser.Package pkg;
7473        synchronized (mPackages) {
7474            pkg = mPackages.get(packageName);
7475            if (pkg == null) {
7476                throw new IllegalArgumentException("Unknown package: " + packageName);
7477            }
7478        }
7479
7480        synchronized (mInstallLock) {
7481            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7482
7483            // Whoever is calling forceDexOpt wants a fully compiled package.
7484            // Don't use profiles since that may cause compilation to be skipped.
7485            final int res = performDexOptInternalWithDependenciesLI(pkg,
7486                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7487                    true /* force */);
7488
7489            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7490            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7491                throw new IllegalStateException("Failed to dexopt: " + res);
7492            }
7493        }
7494    }
7495
7496    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7497        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7498            Slog.w(TAG, "Unable to update from " + oldPkg.name
7499                    + " to " + newPkg.packageName
7500                    + ": old package not in system partition");
7501            return false;
7502        } else if (mPackages.get(oldPkg.name) != null) {
7503            Slog.w(TAG, "Unable to update from " + oldPkg.name
7504                    + " to " + newPkg.packageName
7505                    + ": old package still exists");
7506            return false;
7507        }
7508        return true;
7509    }
7510
7511    void removeCodePathLI(File codePath) {
7512        if (codePath.isDirectory()) {
7513            try {
7514                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7515            } catch (InstallerException e) {
7516                Slog.w(TAG, "Failed to remove code path", e);
7517            }
7518        } else {
7519            codePath.delete();
7520        }
7521    }
7522
7523    private int[] resolveUserIds(int userId) {
7524        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7525    }
7526
7527    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7528        if (pkg == null) {
7529            Slog.wtf(TAG, "Package was null!", new Throwable());
7530            return;
7531        }
7532        clearAppDataLeafLIF(pkg, userId, flags);
7533        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7534        for (int i = 0; i < childCount; i++) {
7535            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7536        }
7537    }
7538
7539    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7540        final PackageSetting ps;
7541        synchronized (mPackages) {
7542            ps = mSettings.mPackages.get(pkg.packageName);
7543        }
7544        for (int realUserId : resolveUserIds(userId)) {
7545            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7546            try {
7547                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7548                        ceDataInode);
7549            } catch (InstallerException e) {
7550                Slog.w(TAG, String.valueOf(e));
7551            }
7552        }
7553    }
7554
7555    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7556        if (pkg == null) {
7557            Slog.wtf(TAG, "Package was null!", new Throwable());
7558            return;
7559        }
7560        destroyAppDataLeafLIF(pkg, userId, flags);
7561        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7562        for (int i = 0; i < childCount; i++) {
7563            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7564        }
7565    }
7566
7567    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7568        final PackageSetting ps;
7569        synchronized (mPackages) {
7570            ps = mSettings.mPackages.get(pkg.packageName);
7571        }
7572        for (int realUserId : resolveUserIds(userId)) {
7573            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7574            try {
7575                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7576                        ceDataInode);
7577            } catch (InstallerException e) {
7578                Slog.w(TAG, String.valueOf(e));
7579            }
7580        }
7581    }
7582
7583    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7584        if (pkg == null) {
7585            Slog.wtf(TAG, "Package was null!", new Throwable());
7586            return;
7587        }
7588        destroyAppProfilesLeafLIF(pkg);
7589        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7590        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7591        for (int i = 0; i < childCount; i++) {
7592            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7593            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7594                    true /* removeBaseMarker */);
7595        }
7596    }
7597
7598    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7599            boolean removeBaseMarker) {
7600        if (pkg.isForwardLocked()) {
7601            return;
7602        }
7603
7604        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7605            try {
7606                path = PackageManagerServiceUtils.realpath(new File(path));
7607            } catch (IOException e) {
7608                // TODO: Should we return early here ?
7609                Slog.w(TAG, "Failed to get canonical path", e);
7610                continue;
7611            }
7612
7613            final String useMarker = path.replace('/', '@');
7614            for (int realUserId : resolveUserIds(userId)) {
7615                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7616                if (removeBaseMarker) {
7617                    File foreignUseMark = new File(profileDir, useMarker);
7618                    if (foreignUseMark.exists()) {
7619                        if (!foreignUseMark.delete()) {
7620                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7621                                    + pkg.packageName);
7622                        }
7623                    }
7624                }
7625
7626                File[] markers = profileDir.listFiles();
7627                if (markers != null) {
7628                    final String searchString = "@" + pkg.packageName + "@";
7629                    // We also delete all markers that contain the package name we're
7630                    // uninstalling. These are associated with secondary dex-files belonging
7631                    // to the package. Reconstructing the path of these dex files is messy
7632                    // in general.
7633                    for (File marker : markers) {
7634                        if (marker.getName().indexOf(searchString) > 0) {
7635                            if (!marker.delete()) {
7636                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7637                                    + pkg.packageName);
7638                            }
7639                        }
7640                    }
7641                }
7642            }
7643        }
7644    }
7645
7646    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7647        try {
7648            mInstaller.destroyAppProfiles(pkg.packageName);
7649        } catch (InstallerException e) {
7650            Slog.w(TAG, String.valueOf(e));
7651        }
7652    }
7653
7654    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7655        if (pkg == null) {
7656            Slog.wtf(TAG, "Package was null!", new Throwable());
7657            return;
7658        }
7659        clearAppProfilesLeafLIF(pkg);
7660        // We don't remove the base foreign use marker when clearing profiles because
7661        // we will rename it when the app is updated. Unlike the actual profile contents,
7662        // the foreign use marker is good across installs.
7663        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7664        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7665        for (int i = 0; i < childCount; i++) {
7666            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7667        }
7668    }
7669
7670    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7671        try {
7672            mInstaller.clearAppProfiles(pkg.packageName);
7673        } catch (InstallerException e) {
7674            Slog.w(TAG, String.valueOf(e));
7675        }
7676    }
7677
7678    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7679            long lastUpdateTime) {
7680        // Set parent install/update time
7681        PackageSetting ps = (PackageSetting) pkg.mExtras;
7682        if (ps != null) {
7683            ps.firstInstallTime = firstInstallTime;
7684            ps.lastUpdateTime = lastUpdateTime;
7685        }
7686        // Set children install/update time
7687        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7688        for (int i = 0; i < childCount; i++) {
7689            PackageParser.Package childPkg = pkg.childPackages.get(i);
7690            ps = (PackageSetting) childPkg.mExtras;
7691            if (ps != null) {
7692                ps.firstInstallTime = firstInstallTime;
7693                ps.lastUpdateTime = lastUpdateTime;
7694            }
7695        }
7696    }
7697
7698    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7699            PackageParser.Package changingLib) {
7700        if (file.path != null) {
7701            usesLibraryFiles.add(file.path);
7702            return;
7703        }
7704        PackageParser.Package p = mPackages.get(file.apk);
7705        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7706            // If we are doing this while in the middle of updating a library apk,
7707            // then we need to make sure to use that new apk for determining the
7708            // dependencies here.  (We haven't yet finished committing the new apk
7709            // to the package manager state.)
7710            if (p == null || p.packageName.equals(changingLib.packageName)) {
7711                p = changingLib;
7712            }
7713        }
7714        if (p != null) {
7715            usesLibraryFiles.addAll(p.getAllCodePaths());
7716        }
7717    }
7718
7719    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7720            PackageParser.Package changingLib) throws PackageManagerException {
7721        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7722            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7723            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7724            for (int i=0; i<N; i++) {
7725                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7726                if (file == null) {
7727                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7728                            "Package " + pkg.packageName + " requires unavailable shared library "
7729                            + pkg.usesLibraries.get(i) + "; failing!");
7730                }
7731                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7732            }
7733            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7734            for (int i=0; i<N; i++) {
7735                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7736                if (file == null) {
7737                    Slog.w(TAG, "Package " + pkg.packageName
7738                            + " desires unavailable shared library "
7739                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7740                } else {
7741                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7742                }
7743            }
7744            N = usesLibraryFiles.size();
7745            if (N > 0) {
7746                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7747            } else {
7748                pkg.usesLibraryFiles = null;
7749            }
7750        }
7751    }
7752
7753    private static boolean hasString(List<String> list, List<String> which) {
7754        if (list == null) {
7755            return false;
7756        }
7757        for (int i=list.size()-1; i>=0; i--) {
7758            for (int j=which.size()-1; j>=0; j--) {
7759                if (which.get(j).equals(list.get(i))) {
7760                    return true;
7761                }
7762            }
7763        }
7764        return false;
7765    }
7766
7767    private void updateAllSharedLibrariesLPw() {
7768        for (PackageParser.Package pkg : mPackages.values()) {
7769            try {
7770                updateSharedLibrariesLPw(pkg, null);
7771            } catch (PackageManagerException e) {
7772                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7773            }
7774        }
7775    }
7776
7777    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7778            PackageParser.Package changingPkg) {
7779        ArrayList<PackageParser.Package> res = null;
7780        for (PackageParser.Package pkg : mPackages.values()) {
7781            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7782                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7783                if (res == null) {
7784                    res = new ArrayList<PackageParser.Package>();
7785                }
7786                res.add(pkg);
7787                try {
7788                    updateSharedLibrariesLPw(pkg, changingPkg);
7789                } catch (PackageManagerException e) {
7790                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7791                }
7792            }
7793        }
7794        return res;
7795    }
7796
7797    /**
7798     * Derive the value of the {@code cpuAbiOverride} based on the provided
7799     * value and an optional stored value from the package settings.
7800     */
7801    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7802        String cpuAbiOverride = null;
7803
7804        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7805            cpuAbiOverride = null;
7806        } else if (abiOverride != null) {
7807            cpuAbiOverride = abiOverride;
7808        } else if (settings != null) {
7809            cpuAbiOverride = settings.cpuAbiOverrideString;
7810        }
7811
7812        return cpuAbiOverride;
7813    }
7814
7815    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7816            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7817                    throws PackageManagerException {
7818        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7819        // If the package has children and this is the first dive in the function
7820        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7821        // whether all packages (parent and children) would be successfully scanned
7822        // before the actual scan since scanning mutates internal state and we want
7823        // to atomically install the package and its children.
7824        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7825            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7826                scanFlags |= SCAN_CHECK_ONLY;
7827            }
7828        } else {
7829            scanFlags &= ~SCAN_CHECK_ONLY;
7830        }
7831
7832        final PackageParser.Package scannedPkg;
7833        try {
7834            // Scan the parent
7835            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7836            // Scan the children
7837            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7838            for (int i = 0; i < childCount; i++) {
7839                PackageParser.Package childPkg = pkg.childPackages.get(i);
7840                scanPackageLI(childPkg, policyFlags,
7841                        scanFlags, currentTime, user);
7842            }
7843        } finally {
7844            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7845        }
7846
7847        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7848            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7849        }
7850
7851        return scannedPkg;
7852    }
7853
7854    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7855            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7856        boolean success = false;
7857        try {
7858            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7859                    currentTime, user);
7860            success = true;
7861            return res;
7862        } finally {
7863            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7864                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7865                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7866                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7867                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7868            }
7869        }
7870    }
7871
7872    /**
7873     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7874     */
7875    private static boolean apkHasCode(String fileName) {
7876        StrictJarFile jarFile = null;
7877        try {
7878            jarFile = new StrictJarFile(fileName,
7879                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7880            return jarFile.findEntry("classes.dex") != null;
7881        } catch (IOException ignore) {
7882        } finally {
7883            try {
7884                if (jarFile != null) {
7885                    jarFile.close();
7886                }
7887            } catch (IOException ignore) {}
7888        }
7889        return false;
7890    }
7891
7892    /**
7893     * Enforces code policy for the package. This ensures that if an APK has
7894     * declared hasCode="true" in its manifest that the APK actually contains
7895     * code.
7896     *
7897     * @throws PackageManagerException If bytecode could not be found when it should exist
7898     */
7899    private static void enforceCodePolicy(PackageParser.Package pkg)
7900            throws PackageManagerException {
7901        final boolean shouldHaveCode =
7902                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7903        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7904            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7905                    "Package " + pkg.baseCodePath + " code is missing");
7906        }
7907
7908        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7909            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7910                final boolean splitShouldHaveCode =
7911                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7912                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7913                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7914                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7915                }
7916            }
7917        }
7918    }
7919
7920    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7921            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7922            throws PackageManagerException {
7923        final File scanFile = new File(pkg.codePath);
7924        if (pkg.applicationInfo.getCodePath() == null ||
7925                pkg.applicationInfo.getResourcePath() == null) {
7926            // Bail out. The resource and code paths haven't been set.
7927            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7928                    "Code and resource paths haven't been set correctly");
7929        }
7930
7931        // Apply policy
7932        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7933            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7934            if (pkg.applicationInfo.isDirectBootAware()) {
7935                // we're direct boot aware; set for all components
7936                for (PackageParser.Service s : pkg.services) {
7937                    s.info.encryptionAware = s.info.directBootAware = true;
7938                }
7939                for (PackageParser.Provider p : pkg.providers) {
7940                    p.info.encryptionAware = p.info.directBootAware = true;
7941                }
7942                for (PackageParser.Activity a : pkg.activities) {
7943                    a.info.encryptionAware = a.info.directBootAware = true;
7944                }
7945                for (PackageParser.Activity r : pkg.receivers) {
7946                    r.info.encryptionAware = r.info.directBootAware = true;
7947                }
7948            }
7949        } else {
7950            // Only allow system apps to be flagged as core apps.
7951            pkg.coreApp = false;
7952            // clear flags not applicable to regular apps
7953            pkg.applicationInfo.privateFlags &=
7954                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7955            pkg.applicationInfo.privateFlags &=
7956                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7957        }
7958        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7959
7960        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7961            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7962        }
7963
7964        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7965            enforceCodePolicy(pkg);
7966        }
7967
7968        if (mCustomResolverComponentName != null &&
7969                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7970            setUpCustomResolverActivity(pkg);
7971        }
7972
7973        if (pkg.packageName.equals("android")) {
7974            synchronized (mPackages) {
7975                if (mAndroidApplication != null) {
7976                    Slog.w(TAG, "*************************************************");
7977                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7978                    Slog.w(TAG, " file=" + scanFile);
7979                    Slog.w(TAG, "*************************************************");
7980                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7981                            "Core android package being redefined.  Skipping.");
7982                }
7983
7984                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7985                    // Set up information for our fall-back user intent resolution activity.
7986                    mPlatformPackage = pkg;
7987                    pkg.mVersionCode = mSdkVersion;
7988                    mAndroidApplication = pkg.applicationInfo;
7989
7990                    if (!mResolverReplaced) {
7991                        mResolveActivity.applicationInfo = mAndroidApplication;
7992                        mResolveActivity.name = ResolverActivity.class.getName();
7993                        mResolveActivity.packageName = mAndroidApplication.packageName;
7994                        mResolveActivity.processName = "system:ui";
7995                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7996                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7997                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7998                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
7999                        mResolveActivity.exported = true;
8000                        mResolveActivity.enabled = true;
8001                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8002                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8003                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8004                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8005                                | ActivityInfo.CONFIG_ORIENTATION
8006                                | ActivityInfo.CONFIG_KEYBOARD
8007                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8008                        mResolveInfo.activityInfo = mResolveActivity;
8009                        mResolveInfo.priority = 0;
8010                        mResolveInfo.preferredOrder = 0;
8011                        mResolveInfo.match = 0;
8012                        mResolveComponentName = new ComponentName(
8013                                mAndroidApplication.packageName, mResolveActivity.name);
8014                    }
8015                }
8016            }
8017        }
8018
8019        if (DEBUG_PACKAGE_SCANNING) {
8020            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8021                Log.d(TAG, "Scanning package " + pkg.packageName);
8022        }
8023
8024        synchronized (mPackages) {
8025            if (mPackages.containsKey(pkg.packageName)
8026                    || mSharedLibraries.containsKey(pkg.packageName)) {
8027                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8028                        "Application package " + pkg.packageName
8029                                + " already installed.  Skipping duplicate.");
8030            }
8031
8032            // If we're only installing presumed-existing packages, require that the
8033            // scanned APK is both already known and at the path previously established
8034            // for it.  Previously unknown packages we pick up normally, but if we have an
8035            // a priori expectation about this package's install presence, enforce it.
8036            // With a singular exception for new system packages. When an OTA contains
8037            // a new system package, we allow the codepath to change from a system location
8038            // to the user-installed location. If we don't allow this change, any newer,
8039            // user-installed version of the application will be ignored.
8040            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8041                if (mExpectingBetter.containsKey(pkg.packageName)) {
8042                    logCriticalInfo(Log.WARN,
8043                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8044                } else {
8045                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8046                    if (known != null) {
8047                        if (DEBUG_PACKAGE_SCANNING) {
8048                            Log.d(TAG, "Examining " + pkg.codePath
8049                                    + " and requiring known paths " + known.codePathString
8050                                    + " & " + known.resourcePathString);
8051                        }
8052                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8053                                || !pkg.applicationInfo.getResourcePath().equals(
8054                                known.resourcePathString)) {
8055                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8056                                    "Application package " + pkg.packageName
8057                                            + " found at " + pkg.applicationInfo.getCodePath()
8058                                            + " but expected at " + known.codePathString
8059                                            + "; ignoring.");
8060                        }
8061                    }
8062                }
8063            }
8064        }
8065
8066        // Initialize package source and resource directories
8067        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8068        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8069
8070        SharedUserSetting suid = null;
8071        PackageSetting pkgSetting = null;
8072
8073        if (!isSystemApp(pkg)) {
8074            // Only system apps can use these features.
8075            pkg.mOriginalPackages = null;
8076            pkg.mRealPackage = null;
8077            pkg.mAdoptPermissions = null;
8078        }
8079
8080        // Getting the package setting may have a side-effect, so if we
8081        // are only checking if scan would succeed, stash a copy of the
8082        // old setting to restore at the end.
8083        PackageSetting nonMutatedPs = null;
8084
8085        // writer
8086        synchronized (mPackages) {
8087            if (pkg.mSharedUserId != null) {
8088                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8089                if (suid == null) {
8090                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8091                            "Creating application package " + pkg.packageName
8092                            + " for shared user failed");
8093                }
8094                if (DEBUG_PACKAGE_SCANNING) {
8095                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8096                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8097                                + "): packages=" + suid.packages);
8098                }
8099            }
8100
8101            // Check if we are renaming from an original package name.
8102            PackageSetting origPackage = null;
8103            String realName = null;
8104            if (pkg.mOriginalPackages != null) {
8105                // This package may need to be renamed to a previously
8106                // installed name.  Let's check on that...
8107                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8108                if (pkg.mOriginalPackages.contains(renamed)) {
8109                    // This package had originally been installed as the
8110                    // original name, and we have already taken care of
8111                    // transitioning to the new one.  Just update the new
8112                    // one to continue using the old name.
8113                    realName = pkg.mRealPackage;
8114                    if (!pkg.packageName.equals(renamed)) {
8115                        // Callers into this function may have already taken
8116                        // care of renaming the package; only do it here if
8117                        // it is not already done.
8118                        pkg.setPackageName(renamed);
8119                    }
8120
8121                } else {
8122                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8123                        if ((origPackage = mSettings.peekPackageLPr(
8124                                pkg.mOriginalPackages.get(i))) != null) {
8125                            // We do have the package already installed under its
8126                            // original name...  should we use it?
8127                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8128                                // New package is not compatible with original.
8129                                origPackage = null;
8130                                continue;
8131                            } else if (origPackage.sharedUser != null) {
8132                                // Make sure uid is compatible between packages.
8133                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8134                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8135                                            + " to " + pkg.packageName + ": old uid "
8136                                            + origPackage.sharedUser.name
8137                                            + " differs from " + pkg.mSharedUserId);
8138                                    origPackage = null;
8139                                    continue;
8140                                }
8141                                // TODO: Add case when shared user id is added [b/28144775]
8142                            } else {
8143                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8144                                        + pkg.packageName + " to old name " + origPackage.name);
8145                            }
8146                            break;
8147                        }
8148                    }
8149                }
8150            }
8151
8152            if (mTransferedPackages.contains(pkg.packageName)) {
8153                Slog.w(TAG, "Package " + pkg.packageName
8154                        + " was transferred to another, but its .apk remains");
8155            }
8156
8157            // See comments in nonMutatedPs declaration
8158            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8159                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8160                if (foundPs != null) {
8161                    nonMutatedPs = new PackageSetting(foundPs);
8162                }
8163            }
8164
8165            // Just create the setting, don't add it yet. For already existing packages
8166            // the PkgSetting exists already and doesn't have to be created.
8167            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8168                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8169                    pkg.applicationInfo.primaryCpuAbi,
8170                    pkg.applicationInfo.secondaryCpuAbi,
8171                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8172                    user, false);
8173            if (pkgSetting == null) {
8174                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8175                        "Creating application package " + pkg.packageName + " failed");
8176            }
8177
8178            if (pkgSetting.origPackage != null) {
8179                // If we are first transitioning from an original package,
8180                // fix up the new package's name now.  We need to do this after
8181                // looking up the package under its new name, so getPackageLP
8182                // can take care of fiddling things correctly.
8183                pkg.setPackageName(origPackage.name);
8184
8185                // File a report about this.
8186                String msg = "New package " + pkgSetting.realName
8187                        + " renamed to replace old package " + pkgSetting.name;
8188                reportSettingsProblem(Log.WARN, msg);
8189
8190                // Make a note of it.
8191                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8192                    mTransferedPackages.add(origPackage.name);
8193                }
8194
8195                // No longer need to retain this.
8196                pkgSetting.origPackage = null;
8197            }
8198
8199            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8200                // Make a note of it.
8201                mTransferedPackages.add(pkg.packageName);
8202            }
8203
8204            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8205                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8206            }
8207
8208            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8209                // Check all shared libraries and map to their actual file path.
8210                // We only do this here for apps not on a system dir, because those
8211                // are the only ones that can fail an install due to this.  We
8212                // will take care of the system apps by updating all of their
8213                // library paths after the scan is done.
8214                updateSharedLibrariesLPw(pkg, null);
8215            }
8216
8217            if (mFoundPolicyFile) {
8218                SELinuxMMAC.assignSeinfoValue(pkg);
8219            }
8220
8221            pkg.applicationInfo.uid = pkgSetting.appId;
8222            pkg.mExtras = pkgSetting;
8223            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8224                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8225                    // We just determined the app is signed correctly, so bring
8226                    // over the latest parsed certs.
8227                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8228                } else {
8229                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8230                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8231                                "Package " + pkg.packageName + " upgrade keys do not match the "
8232                                + "previously installed version");
8233                    } else {
8234                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8235                        String msg = "System package " + pkg.packageName
8236                            + " signature changed; retaining data.";
8237                        reportSettingsProblem(Log.WARN, msg);
8238                    }
8239                }
8240            } else {
8241                try {
8242                    verifySignaturesLP(pkgSetting, pkg);
8243                    // We just determined the app is signed correctly, so bring
8244                    // over the latest parsed certs.
8245                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8246                } catch (PackageManagerException e) {
8247                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8248                        throw e;
8249                    }
8250                    // The signature has changed, but this package is in the system
8251                    // image...  let's recover!
8252                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8253                    // However...  if this package is part of a shared user, but it
8254                    // doesn't match the signature of the shared user, let's fail.
8255                    // What this means is that you can't change the signatures
8256                    // associated with an overall shared user, which doesn't seem all
8257                    // that unreasonable.
8258                    if (pkgSetting.sharedUser != null) {
8259                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8260                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8261                            throw new PackageManagerException(
8262                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8263                                            "Signature mismatch for shared user: "
8264                                            + pkgSetting.sharedUser);
8265                        }
8266                    }
8267                    // File a report about this.
8268                    String msg = "System package " + pkg.packageName
8269                        + " signature changed; retaining data.";
8270                    reportSettingsProblem(Log.WARN, msg);
8271                }
8272            }
8273            // Verify that this new package doesn't have any content providers
8274            // that conflict with existing packages.  Only do this if the
8275            // package isn't already installed, since we don't want to break
8276            // things that are installed.
8277            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8278                final int N = pkg.providers.size();
8279                int i;
8280                for (i=0; i<N; i++) {
8281                    PackageParser.Provider p = pkg.providers.get(i);
8282                    if (p.info.authority != null) {
8283                        String names[] = p.info.authority.split(";");
8284                        for (int j = 0; j < names.length; j++) {
8285                            if (mProvidersByAuthority.containsKey(names[j])) {
8286                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8287                                final String otherPackageName =
8288                                        ((other != null && other.getComponentName() != null) ?
8289                                                other.getComponentName().getPackageName() : "?");
8290                                throw new PackageManagerException(
8291                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8292                                                "Can't install because provider name " + names[j]
8293                                                + " (in package " + pkg.applicationInfo.packageName
8294                                                + ") is already used by " + otherPackageName);
8295                            }
8296                        }
8297                    }
8298                }
8299            }
8300
8301            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8302                // This package wants to adopt ownership of permissions from
8303                // another package.
8304                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8305                    final String origName = pkg.mAdoptPermissions.get(i);
8306                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8307                    if (orig != null) {
8308                        if (verifyPackageUpdateLPr(orig, pkg)) {
8309                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8310                                    + pkg.packageName);
8311                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8312                        }
8313                    }
8314                }
8315            }
8316        }
8317
8318        final String pkgName = pkg.packageName;
8319
8320        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8321        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8322        pkg.applicationInfo.processName = fixProcessName(
8323                pkg.applicationInfo.packageName,
8324                pkg.applicationInfo.processName,
8325                pkg.applicationInfo.uid);
8326
8327        if (pkg != mPlatformPackage) {
8328            // Get all of our default paths setup
8329            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8330        }
8331
8332        final String path = scanFile.getPath();
8333        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8334
8335        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8336            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8337
8338            // Some system apps still use directory structure for native libraries
8339            // in which case we might end up not detecting abi solely based on apk
8340            // structure. Try to detect abi based on directory structure.
8341            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8342                    pkg.applicationInfo.primaryCpuAbi == null) {
8343                setBundledAppAbisAndRoots(pkg, pkgSetting);
8344                setNativeLibraryPaths(pkg);
8345            }
8346
8347        } else {
8348            if ((scanFlags & SCAN_MOVE) != 0) {
8349                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8350                // but we already have this packages package info in the PackageSetting. We just
8351                // use that and derive the native library path based on the new codepath.
8352                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8353                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8354            }
8355
8356            // Set native library paths again. For moves, the path will be updated based on the
8357            // ABIs we've determined above. For non-moves, the path will be updated based on the
8358            // ABIs we determined during compilation, but the path will depend on the final
8359            // package path (after the rename away from the stage path).
8360            setNativeLibraryPaths(pkg);
8361        }
8362
8363        // This is a special case for the "system" package, where the ABI is
8364        // dictated by the zygote configuration (and init.rc). We should keep track
8365        // of this ABI so that we can deal with "normal" applications that run under
8366        // the same UID correctly.
8367        if (mPlatformPackage == pkg) {
8368            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8369                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8370        }
8371
8372        // If there's a mismatch between the abi-override in the package setting
8373        // and the abiOverride specified for the install. Warn about this because we
8374        // would've already compiled the app without taking the package setting into
8375        // account.
8376        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8377            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8378                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8379                        " for package " + pkg.packageName);
8380            }
8381        }
8382
8383        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8384        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8385        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8386
8387        // Copy the derived override back to the parsed package, so that we can
8388        // update the package settings accordingly.
8389        pkg.cpuAbiOverride = cpuAbiOverride;
8390
8391        if (DEBUG_ABI_SELECTION) {
8392            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8393                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8394                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8395        }
8396
8397        // Push the derived path down into PackageSettings so we know what to
8398        // clean up at uninstall time.
8399        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8400
8401        if (DEBUG_ABI_SELECTION) {
8402            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8403                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8404                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8405        }
8406
8407        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8408            // We don't do this here during boot because we can do it all
8409            // at once after scanning all existing packages.
8410            //
8411            // We also do this *before* we perform dexopt on this package, so that
8412            // we can avoid redundant dexopts, and also to make sure we've got the
8413            // code and package path correct.
8414            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8415                    pkg, true /* boot complete */);
8416        }
8417
8418        if (mFactoryTest && pkg.requestedPermissions.contains(
8419                android.Manifest.permission.FACTORY_TEST)) {
8420            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8421        }
8422
8423        if (isSystemApp(pkg)) {
8424            pkgSetting.isOrphaned = true;
8425        }
8426
8427        ArrayList<PackageParser.Package> clientLibPkgs = null;
8428
8429        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8430            if (nonMutatedPs != null) {
8431                synchronized (mPackages) {
8432                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8433                }
8434            }
8435            return pkg;
8436        }
8437
8438        // Only privileged apps and updated privileged apps can add child packages.
8439        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8440            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8441                throw new PackageManagerException("Only privileged apps and updated "
8442                        + "privileged apps can add child packages. Ignoring package "
8443                        + pkg.packageName);
8444            }
8445            final int childCount = pkg.childPackages.size();
8446            for (int i = 0; i < childCount; i++) {
8447                PackageParser.Package childPkg = pkg.childPackages.get(i);
8448                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8449                        childPkg.packageName)) {
8450                    throw new PackageManagerException("Cannot override a child package of "
8451                            + "another disabled system app. Ignoring package " + pkg.packageName);
8452                }
8453            }
8454        }
8455
8456        // writer
8457        synchronized (mPackages) {
8458            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8459                // Only system apps can add new shared libraries.
8460                if (pkg.libraryNames != null) {
8461                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8462                        String name = pkg.libraryNames.get(i);
8463                        boolean allowed = false;
8464                        if (pkg.isUpdatedSystemApp()) {
8465                            // New library entries can only be added through the
8466                            // system image.  This is important to get rid of a lot
8467                            // of nasty edge cases: for example if we allowed a non-
8468                            // system update of the app to add a library, then uninstalling
8469                            // the update would make the library go away, and assumptions
8470                            // we made such as through app install filtering would now
8471                            // have allowed apps on the device which aren't compatible
8472                            // with it.  Better to just have the restriction here, be
8473                            // conservative, and create many fewer cases that can negatively
8474                            // impact the user experience.
8475                            final PackageSetting sysPs = mSettings
8476                                    .getDisabledSystemPkgLPr(pkg.packageName);
8477                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8478                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8479                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8480                                        allowed = true;
8481                                        break;
8482                                    }
8483                                }
8484                            }
8485                        } else {
8486                            allowed = true;
8487                        }
8488                        if (allowed) {
8489                            if (!mSharedLibraries.containsKey(name)) {
8490                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8491                            } else if (!name.equals(pkg.packageName)) {
8492                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8493                                        + name + " already exists; skipping");
8494                            }
8495                        } else {
8496                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8497                                    + name + " that is not declared on system image; skipping");
8498                        }
8499                    }
8500                    if ((scanFlags & SCAN_BOOTING) == 0) {
8501                        // If we are not booting, we need to update any applications
8502                        // that are clients of our shared library.  If we are booting,
8503                        // this will all be done once the scan is complete.
8504                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8505                    }
8506                }
8507            }
8508        }
8509
8510        if ((scanFlags & SCAN_BOOTING) != 0) {
8511            // No apps can run during boot scan, so they don't need to be frozen
8512        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8513            // Caller asked to not kill app, so it's probably not frozen
8514        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8515            // Caller asked us to ignore frozen check for some reason; they
8516            // probably didn't know the package name
8517        } else {
8518            // We're doing major surgery on this package, so it better be frozen
8519            // right now to keep it from launching
8520            checkPackageFrozen(pkgName);
8521        }
8522
8523        // Also need to kill any apps that are dependent on the library.
8524        if (clientLibPkgs != null) {
8525            for (int i=0; i<clientLibPkgs.size(); i++) {
8526                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8527                killApplication(clientPkg.applicationInfo.packageName,
8528                        clientPkg.applicationInfo.uid, "update lib");
8529            }
8530        }
8531
8532        // Make sure we're not adding any bogus keyset info
8533        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8534        ksms.assertScannedPackageValid(pkg);
8535
8536        // writer
8537        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8538
8539        boolean createIdmapFailed = false;
8540        synchronized (mPackages) {
8541            // We don't expect installation to fail beyond this point
8542
8543            if (pkgSetting.pkg != null) {
8544                // Note that |user| might be null during the initial boot scan. If a codePath
8545                // for an app has changed during a boot scan, it's due to an app update that's
8546                // part of the system partition and marker changes must be applied to all users.
8547                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8548                    (user != null) ? user : UserHandle.ALL);
8549            }
8550
8551            // Add the new setting to mSettings
8552            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8553            // Add the new setting to mPackages
8554            mPackages.put(pkg.applicationInfo.packageName, pkg);
8555            // Make sure we don't accidentally delete its data.
8556            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8557            while (iter.hasNext()) {
8558                PackageCleanItem item = iter.next();
8559                if (pkgName.equals(item.packageName)) {
8560                    iter.remove();
8561                }
8562            }
8563
8564            // Take care of first install / last update times.
8565            if (currentTime != 0) {
8566                if (pkgSetting.firstInstallTime == 0) {
8567                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8568                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8569                    pkgSetting.lastUpdateTime = currentTime;
8570                }
8571            } else if (pkgSetting.firstInstallTime == 0) {
8572                // We need *something*.  Take time time stamp of the file.
8573                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8574            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8575                if (scanFileTime != pkgSetting.timeStamp) {
8576                    // A package on the system image has changed; consider this
8577                    // to be an update.
8578                    pkgSetting.lastUpdateTime = scanFileTime;
8579                }
8580            }
8581
8582            // Add the package's KeySets to the global KeySetManagerService
8583            ksms.addScannedPackageLPw(pkg);
8584
8585            int N = pkg.providers.size();
8586            StringBuilder r = null;
8587            int i;
8588            for (i=0; i<N; i++) {
8589                PackageParser.Provider p = pkg.providers.get(i);
8590                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8591                        p.info.processName, pkg.applicationInfo.uid);
8592                mProviders.addProvider(p);
8593                p.syncable = p.info.isSyncable;
8594                if (p.info.authority != null) {
8595                    String names[] = p.info.authority.split(";");
8596                    p.info.authority = null;
8597                    for (int j = 0; j < names.length; j++) {
8598                        if (j == 1 && p.syncable) {
8599                            // We only want the first authority for a provider to possibly be
8600                            // syncable, so if we already added this provider using a different
8601                            // authority clear the syncable flag. We copy the provider before
8602                            // changing it because the mProviders object contains a reference
8603                            // to a provider that we don't want to change.
8604                            // Only do this for the second authority since the resulting provider
8605                            // object can be the same for all future authorities for this provider.
8606                            p = new PackageParser.Provider(p);
8607                            p.syncable = false;
8608                        }
8609                        if (!mProvidersByAuthority.containsKey(names[j])) {
8610                            mProvidersByAuthority.put(names[j], p);
8611                            if (p.info.authority == null) {
8612                                p.info.authority = names[j];
8613                            } else {
8614                                p.info.authority = p.info.authority + ";" + names[j];
8615                            }
8616                            if (DEBUG_PACKAGE_SCANNING) {
8617                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8618                                    Log.d(TAG, "Registered content provider: " + names[j]
8619                                            + ", className = " + p.info.name + ", isSyncable = "
8620                                            + p.info.isSyncable);
8621                            }
8622                        } else {
8623                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8624                            Slog.w(TAG, "Skipping provider name " + names[j] +
8625                                    " (in package " + pkg.applicationInfo.packageName +
8626                                    "): name already used by "
8627                                    + ((other != null && other.getComponentName() != null)
8628                                            ? other.getComponentName().getPackageName() : "?"));
8629                        }
8630                    }
8631                }
8632                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8633                    if (r == null) {
8634                        r = new StringBuilder(256);
8635                    } else {
8636                        r.append(' ');
8637                    }
8638                    r.append(p.info.name);
8639                }
8640            }
8641            if (r != null) {
8642                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8643            }
8644
8645            N = pkg.services.size();
8646            r = null;
8647            for (i=0; i<N; i++) {
8648                PackageParser.Service s = pkg.services.get(i);
8649                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8650                        s.info.processName, pkg.applicationInfo.uid);
8651                mServices.addService(s);
8652                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8653                    if (r == null) {
8654                        r = new StringBuilder(256);
8655                    } else {
8656                        r.append(' ');
8657                    }
8658                    r.append(s.info.name);
8659                }
8660            }
8661            if (r != null) {
8662                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8663            }
8664
8665            N = pkg.receivers.size();
8666            r = null;
8667            for (i=0; i<N; i++) {
8668                PackageParser.Activity a = pkg.receivers.get(i);
8669                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8670                        a.info.processName, pkg.applicationInfo.uid);
8671                mReceivers.addActivity(a, "receiver");
8672                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8673                    if (r == null) {
8674                        r = new StringBuilder(256);
8675                    } else {
8676                        r.append(' ');
8677                    }
8678                    r.append(a.info.name);
8679                }
8680            }
8681            if (r != null) {
8682                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8683            }
8684
8685            N = pkg.activities.size();
8686            r = null;
8687            for (i=0; i<N; i++) {
8688                PackageParser.Activity a = pkg.activities.get(i);
8689                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8690                        a.info.processName, pkg.applicationInfo.uid);
8691                mActivities.addActivity(a, "activity");
8692                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8693                    if (r == null) {
8694                        r = new StringBuilder(256);
8695                    } else {
8696                        r.append(' ');
8697                    }
8698                    r.append(a.info.name);
8699                }
8700            }
8701            if (r != null) {
8702                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8703            }
8704
8705            N = pkg.permissionGroups.size();
8706            r = null;
8707            for (i=0; i<N; i++) {
8708                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8709                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8710                final String curPackageName = cur == null ? null : cur.info.packageName;
8711                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8712                if (cur == null || isPackageUpdate) {
8713                    mPermissionGroups.put(pg.info.name, pg);
8714                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8715                        if (r == null) {
8716                            r = new StringBuilder(256);
8717                        } else {
8718                            r.append(' ');
8719                        }
8720                        if (isPackageUpdate) {
8721                            r.append("UPD:");
8722                        }
8723                        r.append(pg.info.name);
8724                    }
8725                } else {
8726                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8727                            + pg.info.packageName + " ignored: original from "
8728                            + cur.info.packageName);
8729                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8730                        if (r == null) {
8731                            r = new StringBuilder(256);
8732                        } else {
8733                            r.append(' ');
8734                        }
8735                        r.append("DUP:");
8736                        r.append(pg.info.name);
8737                    }
8738                }
8739            }
8740            if (r != null) {
8741                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8742            }
8743
8744            N = pkg.permissions.size();
8745            r = null;
8746            for (i=0; i<N; i++) {
8747                PackageParser.Permission p = pkg.permissions.get(i);
8748
8749                // Assume by default that we did not install this permission into the system.
8750                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8751
8752                // Now that permission groups have a special meaning, we ignore permission
8753                // groups for legacy apps to prevent unexpected behavior. In particular,
8754                // permissions for one app being granted to someone just becase they happen
8755                // to be in a group defined by another app (before this had no implications).
8756                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8757                    p.group = mPermissionGroups.get(p.info.group);
8758                    // Warn for a permission in an unknown group.
8759                    if (p.info.group != null && p.group == null) {
8760                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8761                                + p.info.packageName + " in an unknown group " + p.info.group);
8762                    }
8763                }
8764
8765                ArrayMap<String, BasePermission> permissionMap =
8766                        p.tree ? mSettings.mPermissionTrees
8767                                : mSettings.mPermissions;
8768                BasePermission bp = permissionMap.get(p.info.name);
8769
8770                // Allow system apps to redefine non-system permissions
8771                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8772                    final boolean currentOwnerIsSystem = (bp.perm != null
8773                            && isSystemApp(bp.perm.owner));
8774                    if (isSystemApp(p.owner)) {
8775                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8776                            // It's a built-in permission and no owner, take ownership now
8777                            bp.packageSetting = pkgSetting;
8778                            bp.perm = p;
8779                            bp.uid = pkg.applicationInfo.uid;
8780                            bp.sourcePackage = p.info.packageName;
8781                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8782                        } else if (!currentOwnerIsSystem) {
8783                            String msg = "New decl " + p.owner + " of permission  "
8784                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8785                            reportSettingsProblem(Log.WARN, msg);
8786                            bp = null;
8787                        }
8788                    }
8789                }
8790
8791                if (bp == null) {
8792                    bp = new BasePermission(p.info.name, p.info.packageName,
8793                            BasePermission.TYPE_NORMAL);
8794                    permissionMap.put(p.info.name, bp);
8795                }
8796
8797                if (bp.perm == null) {
8798                    if (bp.sourcePackage == null
8799                            || bp.sourcePackage.equals(p.info.packageName)) {
8800                        BasePermission tree = findPermissionTreeLP(p.info.name);
8801                        if (tree == null
8802                                || tree.sourcePackage.equals(p.info.packageName)) {
8803                            bp.packageSetting = pkgSetting;
8804                            bp.perm = p;
8805                            bp.uid = pkg.applicationInfo.uid;
8806                            bp.sourcePackage = p.info.packageName;
8807                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8808                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8809                                if (r == null) {
8810                                    r = new StringBuilder(256);
8811                                } else {
8812                                    r.append(' ');
8813                                }
8814                                r.append(p.info.name);
8815                            }
8816                        } else {
8817                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8818                                    + p.info.packageName + " ignored: base tree "
8819                                    + tree.name + " is from package "
8820                                    + tree.sourcePackage);
8821                        }
8822                    } else {
8823                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8824                                + p.info.packageName + " ignored: original from "
8825                                + bp.sourcePackage);
8826                    }
8827                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8828                    if (r == null) {
8829                        r = new StringBuilder(256);
8830                    } else {
8831                        r.append(' ');
8832                    }
8833                    r.append("DUP:");
8834                    r.append(p.info.name);
8835                }
8836                if (bp.perm == p) {
8837                    bp.protectionLevel = p.info.protectionLevel;
8838                }
8839            }
8840
8841            if (r != null) {
8842                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8843            }
8844
8845            N = pkg.instrumentation.size();
8846            r = null;
8847            for (i=0; i<N; i++) {
8848                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8849                a.info.packageName = pkg.applicationInfo.packageName;
8850                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8851                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8852                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8853                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8854                a.info.dataDir = pkg.applicationInfo.dataDir;
8855                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8856                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8857
8858                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8859                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8860                mInstrumentation.put(a.getComponentName(), a);
8861                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8862                    if (r == null) {
8863                        r = new StringBuilder(256);
8864                    } else {
8865                        r.append(' ');
8866                    }
8867                    r.append(a.info.name);
8868                }
8869            }
8870            if (r != null) {
8871                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8872            }
8873
8874            if (pkg.protectedBroadcasts != null) {
8875                N = pkg.protectedBroadcasts.size();
8876                for (i=0; i<N; i++) {
8877                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8878                }
8879            }
8880
8881            pkgSetting.setTimeStamp(scanFileTime);
8882
8883            // Create idmap files for pairs of (packages, overlay packages).
8884            // Note: "android", ie framework-res.apk, is handled by native layers.
8885            if (pkg.mOverlayTarget != null) {
8886                // This is an overlay package.
8887                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8888                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8889                        mOverlays.put(pkg.mOverlayTarget,
8890                                new ArrayMap<String, PackageParser.Package>());
8891                    }
8892                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8893                    map.put(pkg.packageName, pkg);
8894                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8895                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8896                        createIdmapFailed = true;
8897                    }
8898                }
8899            } else if (mOverlays.containsKey(pkg.packageName) &&
8900                    !pkg.packageName.equals("android")) {
8901                // This is a regular package, with one or more known overlay packages.
8902                createIdmapsForPackageLI(pkg);
8903            }
8904        }
8905
8906        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8907
8908        if (createIdmapFailed) {
8909            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8910                    "scanPackageLI failed to createIdmap");
8911        }
8912        return pkg;
8913    }
8914
8915    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8916            PackageParser.Package update, UserHandle user) {
8917        if (existing.applicationInfo == null || update.applicationInfo == null) {
8918            // This isn't due to an app installation.
8919            return;
8920        }
8921
8922        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8923        final File newCodePath = new File(update.applicationInfo.getCodePath());
8924
8925        // The codePath hasn't changed, so there's nothing for us to do.
8926        if (Objects.equals(oldCodePath, newCodePath)) {
8927            return;
8928        }
8929
8930        File canonicalNewCodePath;
8931        try {
8932            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
8933        } catch (IOException e) {
8934            Slog.w(TAG, "Failed to get canonical path.", e);
8935            return;
8936        }
8937
8938        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
8939        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
8940        // that the last component of the path (i.e, the name) doesn't need canonicalization
8941        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
8942        // but may change in the future. Hopefully this function won't exist at that point.
8943        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
8944                oldCodePath.getName());
8945
8946        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
8947        // with "@".
8948        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
8949        if (!oldMarkerPrefix.endsWith("@")) {
8950            oldMarkerPrefix += "@";
8951        }
8952        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
8953        if (!newMarkerPrefix.endsWith("@")) {
8954            newMarkerPrefix += "@";
8955        }
8956
8957        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
8958        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
8959        for (String updatedPath : updatedPaths) {
8960            String updatedPathName = new File(updatedPath).getName();
8961            markerSuffixes.add(updatedPathName.replace('/', '@'));
8962        }
8963
8964        for (int userId : resolveUserIds(user.getIdentifier())) {
8965            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
8966
8967            for (String markerSuffix : markerSuffixes) {
8968                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
8969                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
8970                if (oldForeignUseMark.exists()) {
8971                    try {
8972                        Os.rename(oldForeignUseMark.getAbsolutePath(),
8973                                newForeignUseMark.getAbsolutePath());
8974                    } catch (ErrnoException e) {
8975                        Slog.w(TAG, "Failed to rename foreign use marker", e);
8976                        oldForeignUseMark.delete();
8977                    }
8978                }
8979            }
8980        }
8981    }
8982
8983    /**
8984     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8985     * is derived purely on the basis of the contents of {@code scanFile} and
8986     * {@code cpuAbiOverride}.
8987     *
8988     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8989     */
8990    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8991                                 String cpuAbiOverride, boolean extractLibs)
8992            throws PackageManagerException {
8993        // TODO: We can probably be smarter about this stuff. For installed apps,
8994        // we can calculate this information at install time once and for all. For
8995        // system apps, we can probably assume that this information doesn't change
8996        // after the first boot scan. As things stand, we do lots of unnecessary work.
8997
8998        // Give ourselves some initial paths; we'll come back for another
8999        // pass once we've determined ABI below.
9000        setNativeLibraryPaths(pkg);
9001
9002        // We would never need to extract libs for forward-locked and external packages,
9003        // since the container service will do it for us. We shouldn't attempt to
9004        // extract libs from system app when it was not updated.
9005        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9006                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9007            extractLibs = false;
9008        }
9009
9010        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9011        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9012
9013        NativeLibraryHelper.Handle handle = null;
9014        try {
9015            handle = NativeLibraryHelper.Handle.create(pkg);
9016            // TODO(multiArch): This can be null for apps that didn't go through the
9017            // usual installation process. We can calculate it again, like we
9018            // do during install time.
9019            //
9020            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9021            // unnecessary.
9022            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9023
9024            // Null out the abis so that they can be recalculated.
9025            pkg.applicationInfo.primaryCpuAbi = null;
9026            pkg.applicationInfo.secondaryCpuAbi = null;
9027            if (isMultiArch(pkg.applicationInfo)) {
9028                // Warn if we've set an abiOverride for multi-lib packages..
9029                // By definition, we need to copy both 32 and 64 bit libraries for
9030                // such packages.
9031                if (pkg.cpuAbiOverride != null
9032                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9033                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9034                }
9035
9036                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9037                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9038                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9039                    if (extractLibs) {
9040                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9041                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9042                                useIsaSpecificSubdirs);
9043                    } else {
9044                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9045                    }
9046                }
9047
9048                maybeThrowExceptionForMultiArchCopy(
9049                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9050
9051                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9052                    if (extractLibs) {
9053                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9054                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9055                                useIsaSpecificSubdirs);
9056                    } else {
9057                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9058                    }
9059                }
9060
9061                maybeThrowExceptionForMultiArchCopy(
9062                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9063
9064                if (abi64 >= 0) {
9065                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9066                }
9067
9068                if (abi32 >= 0) {
9069                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9070                    if (abi64 >= 0) {
9071                        if (pkg.use32bitAbi) {
9072                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9073                            pkg.applicationInfo.primaryCpuAbi = abi;
9074                        } else {
9075                            pkg.applicationInfo.secondaryCpuAbi = abi;
9076                        }
9077                    } else {
9078                        pkg.applicationInfo.primaryCpuAbi = abi;
9079                    }
9080                }
9081
9082            } else {
9083                String[] abiList = (cpuAbiOverride != null) ?
9084                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9085
9086                // Enable gross and lame hacks for apps that are built with old
9087                // SDK tools. We must scan their APKs for renderscript bitcode and
9088                // not launch them if it's present. Don't bother checking on devices
9089                // that don't have 64 bit support.
9090                boolean needsRenderScriptOverride = false;
9091                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9092                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9093                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9094                    needsRenderScriptOverride = true;
9095                }
9096
9097                final int copyRet;
9098                if (extractLibs) {
9099                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9100                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9101                } else {
9102                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9103                }
9104
9105                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9106                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9107                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9108                }
9109
9110                if (copyRet >= 0) {
9111                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9112                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9113                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9114                } else if (needsRenderScriptOverride) {
9115                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9116                }
9117            }
9118        } catch (IOException ioe) {
9119            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9120        } finally {
9121            IoUtils.closeQuietly(handle);
9122        }
9123
9124        // Now that we've calculated the ABIs and determined if it's an internal app,
9125        // we will go ahead and populate the nativeLibraryPath.
9126        setNativeLibraryPaths(pkg);
9127    }
9128
9129    /**
9130     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9131     * i.e, so that all packages can be run inside a single process if required.
9132     *
9133     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9134     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9135     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9136     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9137     * updating a package that belongs to a shared user.
9138     *
9139     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9140     * adds unnecessary complexity.
9141     */
9142    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9143            PackageParser.Package scannedPackage, boolean bootComplete) {
9144        String requiredInstructionSet = null;
9145        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9146            requiredInstructionSet = VMRuntime.getInstructionSet(
9147                     scannedPackage.applicationInfo.primaryCpuAbi);
9148        }
9149
9150        PackageSetting requirer = null;
9151        for (PackageSetting ps : packagesForUser) {
9152            // If packagesForUser contains scannedPackage, we skip it. This will happen
9153            // when scannedPackage is an update of an existing package. Without this check,
9154            // we will never be able to change the ABI of any package belonging to a shared
9155            // user, even if it's compatible with other packages.
9156            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9157                if (ps.primaryCpuAbiString == null) {
9158                    continue;
9159                }
9160
9161                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9162                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9163                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9164                    // this but there's not much we can do.
9165                    String errorMessage = "Instruction set mismatch, "
9166                            + ((requirer == null) ? "[caller]" : requirer)
9167                            + " requires " + requiredInstructionSet + " whereas " + ps
9168                            + " requires " + instructionSet;
9169                    Slog.w(TAG, errorMessage);
9170                }
9171
9172                if (requiredInstructionSet == null) {
9173                    requiredInstructionSet = instructionSet;
9174                    requirer = ps;
9175                }
9176            }
9177        }
9178
9179        if (requiredInstructionSet != null) {
9180            String adjustedAbi;
9181            if (requirer != null) {
9182                // requirer != null implies that either scannedPackage was null or that scannedPackage
9183                // did not require an ABI, in which case we have to adjust scannedPackage to match
9184                // the ABI of the set (which is the same as requirer's ABI)
9185                adjustedAbi = requirer.primaryCpuAbiString;
9186                if (scannedPackage != null) {
9187                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9188                }
9189            } else {
9190                // requirer == null implies that we're updating all ABIs in the set to
9191                // match scannedPackage.
9192                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9193            }
9194
9195            for (PackageSetting ps : packagesForUser) {
9196                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9197                    if (ps.primaryCpuAbiString != null) {
9198                        continue;
9199                    }
9200
9201                    ps.primaryCpuAbiString = adjustedAbi;
9202                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9203                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9204                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9205                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9206                                + " (requirer="
9207                                + (requirer == null ? "null" : requirer.pkg.packageName)
9208                                + ", scannedPackage="
9209                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9210                                + ")");
9211                        try {
9212                            mInstaller.rmdex(ps.codePathString,
9213                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9214                        } catch (InstallerException ignored) {
9215                        }
9216                    }
9217                }
9218            }
9219        }
9220    }
9221
9222    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9223        synchronized (mPackages) {
9224            mResolverReplaced = true;
9225            // Set up information for custom user intent resolution activity.
9226            mResolveActivity.applicationInfo = pkg.applicationInfo;
9227            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9228            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9229            mResolveActivity.processName = pkg.applicationInfo.packageName;
9230            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9231            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9232                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9233            mResolveActivity.theme = 0;
9234            mResolveActivity.exported = true;
9235            mResolveActivity.enabled = true;
9236            mResolveInfo.activityInfo = mResolveActivity;
9237            mResolveInfo.priority = 0;
9238            mResolveInfo.preferredOrder = 0;
9239            mResolveInfo.match = 0;
9240            mResolveComponentName = mCustomResolverComponentName;
9241            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9242                    mResolveComponentName);
9243        }
9244    }
9245
9246    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9247        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9248
9249        // Set up information for ephemeral installer activity
9250        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9251        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9252        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9253        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9254        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9255        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9256                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9257        mEphemeralInstallerActivity.theme = 0;
9258        mEphemeralInstallerActivity.exported = true;
9259        mEphemeralInstallerActivity.enabled = true;
9260        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9261        mEphemeralInstallerInfo.priority = 0;
9262        mEphemeralInstallerInfo.preferredOrder = 1;
9263        mEphemeralInstallerInfo.isDefault = true;
9264        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9265                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9266
9267        if (DEBUG_EPHEMERAL) {
9268            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9269        }
9270    }
9271
9272    private static String calculateBundledApkRoot(final String codePathString) {
9273        final File codePath = new File(codePathString);
9274        final File codeRoot;
9275        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9276            codeRoot = Environment.getRootDirectory();
9277        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9278            codeRoot = Environment.getOemDirectory();
9279        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9280            codeRoot = Environment.getVendorDirectory();
9281        } else {
9282            // Unrecognized code path; take its top real segment as the apk root:
9283            // e.g. /something/app/blah.apk => /something
9284            try {
9285                File f = codePath.getCanonicalFile();
9286                File parent = f.getParentFile();    // non-null because codePath is a file
9287                File tmp;
9288                while ((tmp = parent.getParentFile()) != null) {
9289                    f = parent;
9290                    parent = tmp;
9291                }
9292                codeRoot = f;
9293                Slog.w(TAG, "Unrecognized code path "
9294                        + codePath + " - using " + codeRoot);
9295            } catch (IOException e) {
9296                // Can't canonicalize the code path -- shenanigans?
9297                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9298                return Environment.getRootDirectory().getPath();
9299            }
9300        }
9301        return codeRoot.getPath();
9302    }
9303
9304    /**
9305     * Derive and set the location of native libraries for the given package,
9306     * which varies depending on where and how the package was installed.
9307     */
9308    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9309        final ApplicationInfo info = pkg.applicationInfo;
9310        final String codePath = pkg.codePath;
9311        final File codeFile = new File(codePath);
9312        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9313        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9314
9315        info.nativeLibraryRootDir = null;
9316        info.nativeLibraryRootRequiresIsa = false;
9317        info.nativeLibraryDir = null;
9318        info.secondaryNativeLibraryDir = null;
9319
9320        if (isApkFile(codeFile)) {
9321            // Monolithic install
9322            if (bundledApp) {
9323                // If "/system/lib64/apkname" exists, assume that is the per-package
9324                // native library directory to use; otherwise use "/system/lib/apkname".
9325                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9326                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9327                        getPrimaryInstructionSet(info));
9328
9329                // This is a bundled system app so choose the path based on the ABI.
9330                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9331                // is just the default path.
9332                final String apkName = deriveCodePathName(codePath);
9333                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9334                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9335                        apkName).getAbsolutePath();
9336
9337                if (info.secondaryCpuAbi != null) {
9338                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9339                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9340                            secondaryLibDir, apkName).getAbsolutePath();
9341                }
9342            } else if (asecApp) {
9343                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9344                        .getAbsolutePath();
9345            } else {
9346                final String apkName = deriveCodePathName(codePath);
9347                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9348                        .getAbsolutePath();
9349            }
9350
9351            info.nativeLibraryRootRequiresIsa = false;
9352            info.nativeLibraryDir = info.nativeLibraryRootDir;
9353        } else {
9354            // Cluster install
9355            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9356            info.nativeLibraryRootRequiresIsa = true;
9357
9358            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9359                    getPrimaryInstructionSet(info)).getAbsolutePath();
9360
9361            if (info.secondaryCpuAbi != null) {
9362                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9363                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9364            }
9365        }
9366    }
9367
9368    /**
9369     * Calculate the abis and roots for a bundled app. These can uniquely
9370     * be determined from the contents of the system partition, i.e whether
9371     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9372     * of this information, and instead assume that the system was built
9373     * sensibly.
9374     */
9375    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9376                                           PackageSetting pkgSetting) {
9377        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9378
9379        // If "/system/lib64/apkname" exists, assume that is the per-package
9380        // native library directory to use; otherwise use "/system/lib/apkname".
9381        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9382        setBundledAppAbi(pkg, apkRoot, apkName);
9383        // pkgSetting might be null during rescan following uninstall of updates
9384        // to a bundled app, so accommodate that possibility.  The settings in
9385        // that case will be established later from the parsed package.
9386        //
9387        // If the settings aren't null, sync them up with what we've just derived.
9388        // note that apkRoot isn't stored in the package settings.
9389        if (pkgSetting != null) {
9390            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9391            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9392        }
9393    }
9394
9395    /**
9396     * Deduces the ABI of a bundled app and sets the relevant fields on the
9397     * parsed pkg object.
9398     *
9399     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9400     *        under which system libraries are installed.
9401     * @param apkName the name of the installed package.
9402     */
9403    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9404        final File codeFile = new File(pkg.codePath);
9405
9406        final boolean has64BitLibs;
9407        final boolean has32BitLibs;
9408        if (isApkFile(codeFile)) {
9409            // Monolithic install
9410            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9411            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9412        } else {
9413            // Cluster install
9414            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9415            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9416                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9417                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9418                has64BitLibs = (new File(rootDir, isa)).exists();
9419            } else {
9420                has64BitLibs = false;
9421            }
9422            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9423                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9424                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9425                has32BitLibs = (new File(rootDir, isa)).exists();
9426            } else {
9427                has32BitLibs = false;
9428            }
9429        }
9430
9431        if (has64BitLibs && !has32BitLibs) {
9432            // The package has 64 bit libs, but not 32 bit libs. Its primary
9433            // ABI should be 64 bit. We can safely assume here that the bundled
9434            // native libraries correspond to the most preferred ABI in the list.
9435
9436            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9437            pkg.applicationInfo.secondaryCpuAbi = null;
9438        } else if (has32BitLibs && !has64BitLibs) {
9439            // The package has 32 bit libs but not 64 bit libs. Its primary
9440            // ABI should be 32 bit.
9441
9442            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9443            pkg.applicationInfo.secondaryCpuAbi = null;
9444        } else if (has32BitLibs && has64BitLibs) {
9445            // The application has both 64 and 32 bit bundled libraries. We check
9446            // here that the app declares multiArch support, and warn if it doesn't.
9447            //
9448            // We will be lenient here and record both ABIs. The primary will be the
9449            // ABI that's higher on the list, i.e, a device that's configured to prefer
9450            // 64 bit apps will see a 64 bit primary ABI,
9451
9452            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9453                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9454            }
9455
9456            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9457                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9458                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9459            } else {
9460                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9461                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9462            }
9463        } else {
9464            pkg.applicationInfo.primaryCpuAbi = null;
9465            pkg.applicationInfo.secondaryCpuAbi = null;
9466        }
9467    }
9468
9469    private void killApplication(String pkgName, int appId, String reason) {
9470        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9471    }
9472
9473    private void killApplication(String pkgName, int appId, int userId, String reason) {
9474        // Request the ActivityManager to kill the process(only for existing packages)
9475        // so that we do not end up in a confused state while the user is still using the older
9476        // version of the application while the new one gets installed.
9477        final long token = Binder.clearCallingIdentity();
9478        try {
9479            IActivityManager am = ActivityManagerNative.getDefault();
9480            if (am != null) {
9481                try {
9482                    am.killApplication(pkgName, appId, userId, reason);
9483                } catch (RemoteException e) {
9484                }
9485            }
9486        } finally {
9487            Binder.restoreCallingIdentity(token);
9488        }
9489    }
9490
9491    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9492        // Remove the parent package setting
9493        PackageSetting ps = (PackageSetting) pkg.mExtras;
9494        if (ps != null) {
9495            removePackageLI(ps, chatty);
9496        }
9497        // Remove the child package setting
9498        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9499        for (int i = 0; i < childCount; i++) {
9500            PackageParser.Package childPkg = pkg.childPackages.get(i);
9501            ps = (PackageSetting) childPkg.mExtras;
9502            if (ps != null) {
9503                removePackageLI(ps, chatty);
9504            }
9505        }
9506    }
9507
9508    void removePackageLI(PackageSetting ps, boolean chatty) {
9509        if (DEBUG_INSTALL) {
9510            if (chatty)
9511                Log.d(TAG, "Removing package " + ps.name);
9512        }
9513
9514        // writer
9515        synchronized (mPackages) {
9516            mPackages.remove(ps.name);
9517            final PackageParser.Package pkg = ps.pkg;
9518            if (pkg != null) {
9519                cleanPackageDataStructuresLILPw(pkg, chatty);
9520            }
9521        }
9522    }
9523
9524    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9525        if (DEBUG_INSTALL) {
9526            if (chatty)
9527                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9528        }
9529
9530        // writer
9531        synchronized (mPackages) {
9532            // Remove the parent package
9533            mPackages.remove(pkg.applicationInfo.packageName);
9534            cleanPackageDataStructuresLILPw(pkg, chatty);
9535
9536            // Remove the child packages
9537            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9538            for (int i = 0; i < childCount; i++) {
9539                PackageParser.Package childPkg = pkg.childPackages.get(i);
9540                mPackages.remove(childPkg.applicationInfo.packageName);
9541                cleanPackageDataStructuresLILPw(childPkg, chatty);
9542            }
9543        }
9544    }
9545
9546    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9547        int N = pkg.providers.size();
9548        StringBuilder r = null;
9549        int i;
9550        for (i=0; i<N; i++) {
9551            PackageParser.Provider p = pkg.providers.get(i);
9552            mProviders.removeProvider(p);
9553            if (p.info.authority == null) {
9554
9555                /* There was another ContentProvider with this authority when
9556                 * this app was installed so this authority is null,
9557                 * Ignore it as we don't have to unregister the provider.
9558                 */
9559                continue;
9560            }
9561            String names[] = p.info.authority.split(";");
9562            for (int j = 0; j < names.length; j++) {
9563                if (mProvidersByAuthority.get(names[j]) == p) {
9564                    mProvidersByAuthority.remove(names[j]);
9565                    if (DEBUG_REMOVE) {
9566                        if (chatty)
9567                            Log.d(TAG, "Unregistered content provider: " + names[j]
9568                                    + ", className = " + p.info.name + ", isSyncable = "
9569                                    + p.info.isSyncable);
9570                    }
9571                }
9572            }
9573            if (DEBUG_REMOVE && chatty) {
9574                if (r == null) {
9575                    r = new StringBuilder(256);
9576                } else {
9577                    r.append(' ');
9578                }
9579                r.append(p.info.name);
9580            }
9581        }
9582        if (r != null) {
9583            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9584        }
9585
9586        N = pkg.services.size();
9587        r = null;
9588        for (i=0; i<N; i++) {
9589            PackageParser.Service s = pkg.services.get(i);
9590            mServices.removeService(s);
9591            if (chatty) {
9592                if (r == null) {
9593                    r = new StringBuilder(256);
9594                } else {
9595                    r.append(' ');
9596                }
9597                r.append(s.info.name);
9598            }
9599        }
9600        if (r != null) {
9601            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9602        }
9603
9604        N = pkg.receivers.size();
9605        r = null;
9606        for (i=0; i<N; i++) {
9607            PackageParser.Activity a = pkg.receivers.get(i);
9608            mReceivers.removeActivity(a, "receiver");
9609            if (DEBUG_REMOVE && chatty) {
9610                if (r == null) {
9611                    r = new StringBuilder(256);
9612                } else {
9613                    r.append(' ');
9614                }
9615                r.append(a.info.name);
9616            }
9617        }
9618        if (r != null) {
9619            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9620        }
9621
9622        N = pkg.activities.size();
9623        r = null;
9624        for (i=0; i<N; i++) {
9625            PackageParser.Activity a = pkg.activities.get(i);
9626            mActivities.removeActivity(a, "activity");
9627            if (DEBUG_REMOVE && chatty) {
9628                if (r == null) {
9629                    r = new StringBuilder(256);
9630                } else {
9631                    r.append(' ');
9632                }
9633                r.append(a.info.name);
9634            }
9635        }
9636        if (r != null) {
9637            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9638        }
9639
9640        N = pkg.permissions.size();
9641        r = null;
9642        for (i=0; i<N; i++) {
9643            PackageParser.Permission p = pkg.permissions.get(i);
9644            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9645            if (bp == null) {
9646                bp = mSettings.mPermissionTrees.get(p.info.name);
9647            }
9648            if (bp != null && bp.perm == p) {
9649                bp.perm = null;
9650                if (DEBUG_REMOVE && chatty) {
9651                    if (r == null) {
9652                        r = new StringBuilder(256);
9653                    } else {
9654                        r.append(' ');
9655                    }
9656                    r.append(p.info.name);
9657                }
9658            }
9659            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9660                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9661                if (appOpPkgs != null) {
9662                    appOpPkgs.remove(pkg.packageName);
9663                }
9664            }
9665        }
9666        if (r != null) {
9667            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9668        }
9669
9670        N = pkg.requestedPermissions.size();
9671        r = null;
9672        for (i=0; i<N; i++) {
9673            String perm = pkg.requestedPermissions.get(i);
9674            BasePermission bp = mSettings.mPermissions.get(perm);
9675            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9676                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9677                if (appOpPkgs != null) {
9678                    appOpPkgs.remove(pkg.packageName);
9679                    if (appOpPkgs.isEmpty()) {
9680                        mAppOpPermissionPackages.remove(perm);
9681                    }
9682                }
9683            }
9684        }
9685        if (r != null) {
9686            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9687        }
9688
9689        N = pkg.instrumentation.size();
9690        r = null;
9691        for (i=0; i<N; i++) {
9692            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9693            mInstrumentation.remove(a.getComponentName());
9694            if (DEBUG_REMOVE && chatty) {
9695                if (r == null) {
9696                    r = new StringBuilder(256);
9697                } else {
9698                    r.append(' ');
9699                }
9700                r.append(a.info.name);
9701            }
9702        }
9703        if (r != null) {
9704            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9705        }
9706
9707        r = null;
9708        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9709            // Only system apps can hold shared libraries.
9710            if (pkg.libraryNames != null) {
9711                for (i=0; i<pkg.libraryNames.size(); i++) {
9712                    String name = pkg.libraryNames.get(i);
9713                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9714                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9715                        mSharedLibraries.remove(name);
9716                        if (DEBUG_REMOVE && chatty) {
9717                            if (r == null) {
9718                                r = new StringBuilder(256);
9719                            } else {
9720                                r.append(' ');
9721                            }
9722                            r.append(name);
9723                        }
9724                    }
9725                }
9726            }
9727        }
9728        if (r != null) {
9729            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9730        }
9731    }
9732
9733    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9734        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9735            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9736                return true;
9737            }
9738        }
9739        return false;
9740    }
9741
9742    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9743    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9744    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9745
9746    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9747        // Update the parent permissions
9748        updatePermissionsLPw(pkg.packageName, pkg, flags);
9749        // Update the child permissions
9750        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9751        for (int i = 0; i < childCount; i++) {
9752            PackageParser.Package childPkg = pkg.childPackages.get(i);
9753            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9754        }
9755    }
9756
9757    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9758            int flags) {
9759        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9760        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9761    }
9762
9763    private void updatePermissionsLPw(String changingPkg,
9764            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9765        // Make sure there are no dangling permission trees.
9766        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9767        while (it.hasNext()) {
9768            final BasePermission bp = it.next();
9769            if (bp.packageSetting == null) {
9770                // We may not yet have parsed the package, so just see if
9771                // we still know about its settings.
9772                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9773            }
9774            if (bp.packageSetting == null) {
9775                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9776                        + " from package " + bp.sourcePackage);
9777                it.remove();
9778            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9779                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9780                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9781                            + " from package " + bp.sourcePackage);
9782                    flags |= UPDATE_PERMISSIONS_ALL;
9783                    it.remove();
9784                }
9785            }
9786        }
9787
9788        // Make sure all dynamic permissions have been assigned to a package,
9789        // and make sure there are no dangling permissions.
9790        it = mSettings.mPermissions.values().iterator();
9791        while (it.hasNext()) {
9792            final BasePermission bp = it.next();
9793            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9794                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9795                        + bp.name + " pkg=" + bp.sourcePackage
9796                        + " info=" + bp.pendingInfo);
9797                if (bp.packageSetting == null && bp.pendingInfo != null) {
9798                    final BasePermission tree = findPermissionTreeLP(bp.name);
9799                    if (tree != null && tree.perm != null) {
9800                        bp.packageSetting = tree.packageSetting;
9801                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9802                                new PermissionInfo(bp.pendingInfo));
9803                        bp.perm.info.packageName = tree.perm.info.packageName;
9804                        bp.perm.info.name = bp.name;
9805                        bp.uid = tree.uid;
9806                    }
9807                }
9808            }
9809            if (bp.packageSetting == null) {
9810                // We may not yet have parsed the package, so just see if
9811                // we still know about its settings.
9812                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9813            }
9814            if (bp.packageSetting == null) {
9815                Slog.w(TAG, "Removing dangling permission: " + bp.name
9816                        + " from package " + bp.sourcePackage);
9817                it.remove();
9818            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9819                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9820                    Slog.i(TAG, "Removing old permission: " + bp.name
9821                            + " from package " + bp.sourcePackage);
9822                    flags |= UPDATE_PERMISSIONS_ALL;
9823                    it.remove();
9824                }
9825            }
9826        }
9827
9828        // Now update the permissions for all packages, in particular
9829        // replace the granted permissions of the system packages.
9830        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9831            for (PackageParser.Package pkg : mPackages.values()) {
9832                if (pkg != pkgInfo) {
9833                    // Only replace for packages on requested volume
9834                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9835                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9836                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9837                    grantPermissionsLPw(pkg, replace, changingPkg);
9838                }
9839            }
9840        }
9841
9842        if (pkgInfo != null) {
9843            // Only replace for packages on requested volume
9844            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9845            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9846                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9847            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9848        }
9849    }
9850
9851    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9852            String packageOfInterest) {
9853        // IMPORTANT: There are two types of permissions: install and runtime.
9854        // Install time permissions are granted when the app is installed to
9855        // all device users and users added in the future. Runtime permissions
9856        // are granted at runtime explicitly to specific users. Normal and signature
9857        // protected permissions are install time permissions. Dangerous permissions
9858        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9859        // otherwise they are runtime permissions. This function does not manage
9860        // runtime permissions except for the case an app targeting Lollipop MR1
9861        // being upgraded to target a newer SDK, in which case dangerous permissions
9862        // are transformed from install time to runtime ones.
9863
9864        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9865        if (ps == null) {
9866            return;
9867        }
9868
9869        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9870
9871        PermissionsState permissionsState = ps.getPermissionsState();
9872        PermissionsState origPermissions = permissionsState;
9873
9874        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9875
9876        boolean runtimePermissionsRevoked = false;
9877        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9878
9879        boolean changedInstallPermission = false;
9880
9881        if (replace) {
9882            ps.installPermissionsFixed = false;
9883            if (!ps.isSharedUser()) {
9884                origPermissions = new PermissionsState(permissionsState);
9885                permissionsState.reset();
9886            } else {
9887                // We need to know only about runtime permission changes since the
9888                // calling code always writes the install permissions state but
9889                // the runtime ones are written only if changed. The only cases of
9890                // changed runtime permissions here are promotion of an install to
9891                // runtime and revocation of a runtime from a shared user.
9892                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9893                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9894                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9895                    runtimePermissionsRevoked = true;
9896                }
9897            }
9898        }
9899
9900        permissionsState.setGlobalGids(mGlobalGids);
9901
9902        final int N = pkg.requestedPermissions.size();
9903        for (int i=0; i<N; i++) {
9904            final String name = pkg.requestedPermissions.get(i);
9905            final BasePermission bp = mSettings.mPermissions.get(name);
9906
9907            if (DEBUG_INSTALL) {
9908                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9909            }
9910
9911            if (bp == null || bp.packageSetting == null) {
9912                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9913                    Slog.w(TAG, "Unknown permission " + name
9914                            + " in package " + pkg.packageName);
9915                }
9916                continue;
9917            }
9918
9919            final String perm = bp.name;
9920            boolean allowedSig = false;
9921            int grant = GRANT_DENIED;
9922
9923            // Keep track of app op permissions.
9924            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9925                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9926                if (pkgs == null) {
9927                    pkgs = new ArraySet<>();
9928                    mAppOpPermissionPackages.put(bp.name, pkgs);
9929                }
9930                pkgs.add(pkg.packageName);
9931            }
9932
9933            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9934            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9935                    >= Build.VERSION_CODES.M;
9936            switch (level) {
9937                case PermissionInfo.PROTECTION_NORMAL: {
9938                    // For all apps normal permissions are install time ones.
9939                    grant = GRANT_INSTALL;
9940                } break;
9941
9942                case PermissionInfo.PROTECTION_DANGEROUS: {
9943                    // If a permission review is required for legacy apps we represent
9944                    // their permissions as always granted runtime ones since we need
9945                    // to keep the review required permission flag per user while an
9946                    // install permission's state is shared across all users.
9947                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9948                        // For legacy apps dangerous permissions are install time ones.
9949                        grant = GRANT_INSTALL;
9950                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9951                        // For legacy apps that became modern, install becomes runtime.
9952                        grant = GRANT_UPGRADE;
9953                    } else if (mPromoteSystemApps
9954                            && isSystemApp(ps)
9955                            && mExistingSystemPackages.contains(ps.name)) {
9956                        // For legacy system apps, install becomes runtime.
9957                        // We cannot check hasInstallPermission() for system apps since those
9958                        // permissions were granted implicitly and not persisted pre-M.
9959                        grant = GRANT_UPGRADE;
9960                    } else {
9961                        // For modern apps keep runtime permissions unchanged.
9962                        grant = GRANT_RUNTIME;
9963                    }
9964                } break;
9965
9966                case PermissionInfo.PROTECTION_SIGNATURE: {
9967                    // For all apps signature permissions are install time ones.
9968                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9969                    if (allowedSig) {
9970                        grant = GRANT_INSTALL;
9971                    }
9972                } break;
9973            }
9974
9975            if (DEBUG_INSTALL) {
9976                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9977            }
9978
9979            if (grant != GRANT_DENIED) {
9980                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9981                    // If this is an existing, non-system package, then
9982                    // we can't add any new permissions to it.
9983                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9984                        // Except...  if this is a permission that was added
9985                        // to the platform (note: need to only do this when
9986                        // updating the platform).
9987                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9988                            grant = GRANT_DENIED;
9989                        }
9990                    }
9991                }
9992
9993                switch (grant) {
9994                    case GRANT_INSTALL: {
9995                        // Revoke this as runtime permission to handle the case of
9996                        // a runtime permission being downgraded to an install one.
9997                        // Also in permission review mode we keep dangerous permissions
9998                        // for legacy apps
9999                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10000                            if (origPermissions.getRuntimePermissionState(
10001                                    bp.name, userId) != null) {
10002                                // Revoke the runtime permission and clear the flags.
10003                                origPermissions.revokeRuntimePermission(bp, userId);
10004                                origPermissions.updatePermissionFlags(bp, userId,
10005                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10006                                // If we revoked a permission permission, we have to write.
10007                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10008                                        changedRuntimePermissionUserIds, userId);
10009                            }
10010                        }
10011                        // Grant an install permission.
10012                        if (permissionsState.grantInstallPermission(bp) !=
10013                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10014                            changedInstallPermission = true;
10015                        }
10016                    } break;
10017
10018                    case GRANT_RUNTIME: {
10019                        // Grant previously granted runtime permissions.
10020                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10021                            PermissionState permissionState = origPermissions
10022                                    .getRuntimePermissionState(bp.name, userId);
10023                            int flags = permissionState != null
10024                                    ? permissionState.getFlags() : 0;
10025                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10026                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10027                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10028                                    // If we cannot put the permission as it was, we have to write.
10029                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10030                                            changedRuntimePermissionUserIds, userId);
10031                                }
10032                                // If the app supports runtime permissions no need for a review.
10033                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10034                                        && appSupportsRuntimePermissions
10035                                        && (flags & PackageManager
10036                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10037                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10038                                    // Since we changed the flags, we have to write.
10039                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10040                                            changedRuntimePermissionUserIds, userId);
10041                                }
10042                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10043                                    && !appSupportsRuntimePermissions) {
10044                                // For legacy apps that need a permission review, every new
10045                                // runtime permission is granted but it is pending a review.
10046                                // We also need to review only platform defined runtime
10047                                // permissions as these are the only ones the platform knows
10048                                // how to disable the API to simulate revocation as legacy
10049                                // apps don't expect to run with revoked permissions.
10050                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10051                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10052                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10053                                        // We changed the flags, hence have to write.
10054                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10055                                                changedRuntimePermissionUserIds, userId);
10056                                    }
10057                                }
10058                                if (permissionsState.grantRuntimePermission(bp, userId)
10059                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10060                                    // We changed the permission, hence have to write.
10061                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10062                                            changedRuntimePermissionUserIds, userId);
10063                                }
10064                            }
10065                            // Propagate the permission flags.
10066                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10067                        }
10068                    } break;
10069
10070                    case GRANT_UPGRADE: {
10071                        // Grant runtime permissions for a previously held install permission.
10072                        PermissionState permissionState = origPermissions
10073                                .getInstallPermissionState(bp.name);
10074                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10075
10076                        if (origPermissions.revokeInstallPermission(bp)
10077                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10078                            // We will be transferring the permission flags, so clear them.
10079                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10080                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10081                            changedInstallPermission = true;
10082                        }
10083
10084                        // If the permission is not to be promoted to runtime we ignore it and
10085                        // also its other flags as they are not applicable to install permissions.
10086                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10087                            for (int userId : currentUserIds) {
10088                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10089                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10090                                    // Transfer the permission flags.
10091                                    permissionsState.updatePermissionFlags(bp, userId,
10092                                            flags, flags);
10093                                    // If we granted the permission, we have to write.
10094                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10095                                            changedRuntimePermissionUserIds, userId);
10096                                }
10097                            }
10098                        }
10099                    } break;
10100
10101                    default: {
10102                        if (packageOfInterest == null
10103                                || packageOfInterest.equals(pkg.packageName)) {
10104                            Slog.w(TAG, "Not granting permission " + perm
10105                                    + " to package " + pkg.packageName
10106                                    + " because it was previously installed without");
10107                        }
10108                    } break;
10109                }
10110            } else {
10111                if (permissionsState.revokeInstallPermission(bp) !=
10112                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10113                    // Also drop the permission flags.
10114                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10115                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10116                    changedInstallPermission = true;
10117                    Slog.i(TAG, "Un-granting permission " + perm
10118                            + " from package " + pkg.packageName
10119                            + " (protectionLevel=" + bp.protectionLevel
10120                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10121                            + ")");
10122                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10123                    // Don't print warning for app op permissions, since it is fine for them
10124                    // not to be granted, there is a UI for the user to decide.
10125                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10126                        Slog.w(TAG, "Not granting permission " + perm
10127                                + " to package " + pkg.packageName
10128                                + " (protectionLevel=" + bp.protectionLevel
10129                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10130                                + ")");
10131                    }
10132                }
10133            }
10134        }
10135
10136        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10137                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10138            // This is the first that we have heard about this package, so the
10139            // permissions we have now selected are fixed until explicitly
10140            // changed.
10141            ps.installPermissionsFixed = true;
10142        }
10143
10144        // Persist the runtime permissions state for users with changes. If permissions
10145        // were revoked because no app in the shared user declares them we have to
10146        // write synchronously to avoid losing runtime permissions state.
10147        for (int userId : changedRuntimePermissionUserIds) {
10148            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10149        }
10150
10151        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10152    }
10153
10154    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10155        boolean allowed = false;
10156        final int NP = PackageParser.NEW_PERMISSIONS.length;
10157        for (int ip=0; ip<NP; ip++) {
10158            final PackageParser.NewPermissionInfo npi
10159                    = PackageParser.NEW_PERMISSIONS[ip];
10160            if (npi.name.equals(perm)
10161                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10162                allowed = true;
10163                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10164                        + pkg.packageName);
10165                break;
10166            }
10167        }
10168        return allowed;
10169    }
10170
10171    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10172            BasePermission bp, PermissionsState origPermissions) {
10173        boolean allowed;
10174        allowed = (compareSignatures(
10175                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10176                        == PackageManager.SIGNATURE_MATCH)
10177                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10178                        == PackageManager.SIGNATURE_MATCH);
10179        if (!allowed && (bp.protectionLevel
10180                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10181            if (isSystemApp(pkg)) {
10182                // For updated system applications, a system permission
10183                // is granted only if it had been defined by the original application.
10184                if (pkg.isUpdatedSystemApp()) {
10185                    final PackageSetting sysPs = mSettings
10186                            .getDisabledSystemPkgLPr(pkg.packageName);
10187                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10188                        // If the original was granted this permission, we take
10189                        // that grant decision as read and propagate it to the
10190                        // update.
10191                        if (sysPs.isPrivileged()) {
10192                            allowed = true;
10193                        }
10194                    } else {
10195                        // The system apk may have been updated with an older
10196                        // version of the one on the data partition, but which
10197                        // granted a new system permission that it didn't have
10198                        // before.  In this case we do want to allow the app to
10199                        // now get the new permission if the ancestral apk is
10200                        // privileged to get it.
10201                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10202                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10203                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10204                                    allowed = true;
10205                                    break;
10206                                }
10207                            }
10208                        }
10209                        // Also if a privileged parent package on the system image or any of
10210                        // its children requested a privileged permission, the updated child
10211                        // packages can also get the permission.
10212                        if (pkg.parentPackage != null) {
10213                            final PackageSetting disabledSysParentPs = mSettings
10214                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10215                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10216                                    && disabledSysParentPs.isPrivileged()) {
10217                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10218                                    allowed = true;
10219                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10220                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10221                                    for (int i = 0; i < count; i++) {
10222                                        PackageParser.Package disabledSysChildPkg =
10223                                                disabledSysParentPs.pkg.childPackages.get(i);
10224                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10225                                                perm)) {
10226                                            allowed = true;
10227                                            break;
10228                                        }
10229                                    }
10230                                }
10231                            }
10232                        }
10233                    }
10234                } else {
10235                    allowed = isPrivilegedApp(pkg);
10236                }
10237            }
10238        }
10239        if (!allowed) {
10240            if (!allowed && (bp.protectionLevel
10241                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10242                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10243                // If this was a previously normal/dangerous permission that got moved
10244                // to a system permission as part of the runtime permission redesign, then
10245                // we still want to blindly grant it to old apps.
10246                allowed = true;
10247            }
10248            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10249                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10250                // If this permission is to be granted to the system installer and
10251                // this app is an installer, then it gets the permission.
10252                allowed = true;
10253            }
10254            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10255                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10256                // If this permission is to be granted to the system verifier and
10257                // this app is a verifier, then it gets the permission.
10258                allowed = true;
10259            }
10260            if (!allowed && (bp.protectionLevel
10261                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10262                    && isSystemApp(pkg)) {
10263                // Any pre-installed system app is allowed to get this permission.
10264                allowed = true;
10265            }
10266            if (!allowed && (bp.protectionLevel
10267                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10268                // For development permissions, a development permission
10269                // is granted only if it was already granted.
10270                allowed = origPermissions.hasInstallPermission(perm);
10271            }
10272            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10273                    && pkg.packageName.equals(mSetupWizardPackage)) {
10274                // If this permission is to be granted to the system setup wizard and
10275                // this app is a setup wizard, then it gets the permission.
10276                allowed = true;
10277            }
10278        }
10279        return allowed;
10280    }
10281
10282    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10283        final int permCount = pkg.requestedPermissions.size();
10284        for (int j = 0; j < permCount; j++) {
10285            String requestedPermission = pkg.requestedPermissions.get(j);
10286            if (permission.equals(requestedPermission)) {
10287                return true;
10288            }
10289        }
10290        return false;
10291    }
10292
10293    final class ActivityIntentResolver
10294            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10295        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10296                boolean defaultOnly, int userId) {
10297            if (!sUserManager.exists(userId)) return null;
10298            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10299            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10300        }
10301
10302        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10303                int userId) {
10304            if (!sUserManager.exists(userId)) return null;
10305            mFlags = flags;
10306            return super.queryIntent(intent, resolvedType,
10307                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10308        }
10309
10310        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10311                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10312            if (!sUserManager.exists(userId)) return null;
10313            if (packageActivities == null) {
10314                return null;
10315            }
10316            mFlags = flags;
10317            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10318            final int N = packageActivities.size();
10319            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10320                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10321
10322            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10323            for (int i = 0; i < N; ++i) {
10324                intentFilters = packageActivities.get(i).intents;
10325                if (intentFilters != null && intentFilters.size() > 0) {
10326                    PackageParser.ActivityIntentInfo[] array =
10327                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10328                    intentFilters.toArray(array);
10329                    listCut.add(array);
10330                }
10331            }
10332            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10333        }
10334
10335        /**
10336         * Finds a privileged activity that matches the specified activity names.
10337         */
10338        private PackageParser.Activity findMatchingActivity(
10339                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10340            for (PackageParser.Activity sysActivity : activityList) {
10341                if (sysActivity.info.name.equals(activityInfo.name)) {
10342                    return sysActivity;
10343                }
10344                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10345                    return sysActivity;
10346                }
10347                if (sysActivity.info.targetActivity != null) {
10348                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10349                        return sysActivity;
10350                    }
10351                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10352                        return sysActivity;
10353                    }
10354                }
10355            }
10356            return null;
10357        }
10358
10359        public class IterGenerator<E> {
10360            public Iterator<E> generate(ActivityIntentInfo info) {
10361                return null;
10362            }
10363        }
10364
10365        public class ActionIterGenerator extends IterGenerator<String> {
10366            @Override
10367            public Iterator<String> generate(ActivityIntentInfo info) {
10368                return info.actionsIterator();
10369            }
10370        }
10371
10372        public class CategoriesIterGenerator extends IterGenerator<String> {
10373            @Override
10374            public Iterator<String> generate(ActivityIntentInfo info) {
10375                return info.categoriesIterator();
10376            }
10377        }
10378
10379        public class SchemesIterGenerator extends IterGenerator<String> {
10380            @Override
10381            public Iterator<String> generate(ActivityIntentInfo info) {
10382                return info.schemesIterator();
10383            }
10384        }
10385
10386        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10387            @Override
10388            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10389                return info.authoritiesIterator();
10390            }
10391        }
10392
10393        /**
10394         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10395         * MODIFIED. Do not pass in a list that should not be changed.
10396         */
10397        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10398                IterGenerator<T> generator, Iterator<T> searchIterator) {
10399            // loop through the set of actions; every one must be found in the intent filter
10400            while (searchIterator.hasNext()) {
10401                // we must have at least one filter in the list to consider a match
10402                if (intentList.size() == 0) {
10403                    break;
10404                }
10405
10406                final T searchAction = searchIterator.next();
10407
10408                // loop through the set of intent filters
10409                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10410                while (intentIter.hasNext()) {
10411                    final ActivityIntentInfo intentInfo = intentIter.next();
10412                    boolean selectionFound = false;
10413
10414                    // loop through the intent filter's selection criteria; at least one
10415                    // of them must match the searched criteria
10416                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10417                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10418                        final T intentSelection = intentSelectionIter.next();
10419                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10420                            selectionFound = true;
10421                            break;
10422                        }
10423                    }
10424
10425                    // the selection criteria wasn't found in this filter's set; this filter
10426                    // is not a potential match
10427                    if (!selectionFound) {
10428                        intentIter.remove();
10429                    }
10430                }
10431            }
10432        }
10433
10434        private boolean isProtectedAction(ActivityIntentInfo filter) {
10435            final Iterator<String> actionsIter = filter.actionsIterator();
10436            while (actionsIter != null && actionsIter.hasNext()) {
10437                final String filterAction = actionsIter.next();
10438                if (PROTECTED_ACTIONS.contains(filterAction)) {
10439                    return true;
10440                }
10441            }
10442            return false;
10443        }
10444
10445        /**
10446         * Adjusts the priority of the given intent filter according to policy.
10447         * <p>
10448         * <ul>
10449         * <li>The priority for non privileged applications is capped to '0'</li>
10450         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10451         * <li>The priority for unbundled updates to privileged applications is capped to the
10452         *      priority defined on the system partition</li>
10453         * </ul>
10454         * <p>
10455         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10456         * allowed to obtain any priority on any action.
10457         */
10458        private void adjustPriority(
10459                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10460            // nothing to do; priority is fine as-is
10461            if (intent.getPriority() <= 0) {
10462                return;
10463            }
10464
10465            final ActivityInfo activityInfo = intent.activity.info;
10466            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10467
10468            final boolean privilegedApp =
10469                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10470            if (!privilegedApp) {
10471                // non-privileged applications can never define a priority >0
10472                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10473                        + " package: " + applicationInfo.packageName
10474                        + " activity: " + intent.activity.className
10475                        + " origPrio: " + intent.getPriority());
10476                intent.setPriority(0);
10477                return;
10478            }
10479
10480            if (systemActivities == null) {
10481                // the system package is not disabled; we're parsing the system partition
10482                if (isProtectedAction(intent)) {
10483                    if (mDeferProtectedFilters) {
10484                        // We can't deal with these just yet. No component should ever obtain a
10485                        // >0 priority for a protected actions, with ONE exception -- the setup
10486                        // wizard. The setup wizard, however, cannot be known until we're able to
10487                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10488                        // until all intent filters have been processed. Chicken, meet egg.
10489                        // Let the filter temporarily have a high priority and rectify the
10490                        // priorities after all system packages have been scanned.
10491                        mProtectedFilters.add(intent);
10492                        if (DEBUG_FILTERS) {
10493                            Slog.i(TAG, "Protected action; save for later;"
10494                                    + " package: " + applicationInfo.packageName
10495                                    + " activity: " + intent.activity.className
10496                                    + " origPrio: " + intent.getPriority());
10497                        }
10498                        return;
10499                    } else {
10500                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10501                            Slog.i(TAG, "No setup wizard;"
10502                                + " All protected intents capped to priority 0");
10503                        }
10504                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10505                            if (DEBUG_FILTERS) {
10506                                Slog.i(TAG, "Found setup wizard;"
10507                                    + " allow priority " + intent.getPriority() + ";"
10508                                    + " package: " + intent.activity.info.packageName
10509                                    + " activity: " + intent.activity.className
10510                                    + " priority: " + intent.getPriority());
10511                            }
10512                            // setup wizard gets whatever it wants
10513                            return;
10514                        }
10515                        Slog.w(TAG, "Protected action; cap priority to 0;"
10516                                + " package: " + intent.activity.info.packageName
10517                                + " activity: " + intent.activity.className
10518                                + " origPrio: " + intent.getPriority());
10519                        intent.setPriority(0);
10520                        return;
10521                    }
10522                }
10523                // privileged apps on the system image get whatever priority they request
10524                return;
10525            }
10526
10527            // privileged app unbundled update ... try to find the same activity
10528            final PackageParser.Activity foundActivity =
10529                    findMatchingActivity(systemActivities, activityInfo);
10530            if (foundActivity == null) {
10531                // this is a new activity; it cannot obtain >0 priority
10532                if (DEBUG_FILTERS) {
10533                    Slog.i(TAG, "New activity; cap priority to 0;"
10534                            + " package: " + applicationInfo.packageName
10535                            + " activity: " + intent.activity.className
10536                            + " origPrio: " + intent.getPriority());
10537                }
10538                intent.setPriority(0);
10539                return;
10540            }
10541
10542            // found activity, now check for filter equivalence
10543
10544            // a shallow copy is enough; we modify the list, not its contents
10545            final List<ActivityIntentInfo> intentListCopy =
10546                    new ArrayList<>(foundActivity.intents);
10547            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10548
10549            // find matching action subsets
10550            final Iterator<String> actionsIterator = intent.actionsIterator();
10551            if (actionsIterator != null) {
10552                getIntentListSubset(
10553                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10554                if (intentListCopy.size() == 0) {
10555                    // no more intents to match; we're not equivalent
10556                    if (DEBUG_FILTERS) {
10557                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10558                                + " package: " + applicationInfo.packageName
10559                                + " activity: " + intent.activity.className
10560                                + " origPrio: " + intent.getPriority());
10561                    }
10562                    intent.setPriority(0);
10563                    return;
10564                }
10565            }
10566
10567            // find matching category subsets
10568            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10569            if (categoriesIterator != null) {
10570                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10571                        categoriesIterator);
10572                if (intentListCopy.size() == 0) {
10573                    // no more intents to match; we're not equivalent
10574                    if (DEBUG_FILTERS) {
10575                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10576                                + " package: " + applicationInfo.packageName
10577                                + " activity: " + intent.activity.className
10578                                + " origPrio: " + intent.getPriority());
10579                    }
10580                    intent.setPriority(0);
10581                    return;
10582                }
10583            }
10584
10585            // find matching schemes subsets
10586            final Iterator<String> schemesIterator = intent.schemesIterator();
10587            if (schemesIterator != null) {
10588                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10589                        schemesIterator);
10590                if (intentListCopy.size() == 0) {
10591                    // no more intents to match; we're not equivalent
10592                    if (DEBUG_FILTERS) {
10593                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10594                                + " package: " + applicationInfo.packageName
10595                                + " activity: " + intent.activity.className
10596                                + " origPrio: " + intent.getPriority());
10597                    }
10598                    intent.setPriority(0);
10599                    return;
10600                }
10601            }
10602
10603            // find matching authorities subsets
10604            final Iterator<IntentFilter.AuthorityEntry>
10605                    authoritiesIterator = intent.authoritiesIterator();
10606            if (authoritiesIterator != null) {
10607                getIntentListSubset(intentListCopy,
10608                        new AuthoritiesIterGenerator(),
10609                        authoritiesIterator);
10610                if (intentListCopy.size() == 0) {
10611                    // no more intents to match; we're not equivalent
10612                    if (DEBUG_FILTERS) {
10613                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10614                                + " package: " + applicationInfo.packageName
10615                                + " activity: " + intent.activity.className
10616                                + " origPrio: " + intent.getPriority());
10617                    }
10618                    intent.setPriority(0);
10619                    return;
10620                }
10621            }
10622
10623            // we found matching filter(s); app gets the max priority of all intents
10624            int cappedPriority = 0;
10625            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10626                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10627            }
10628            if (intent.getPriority() > cappedPriority) {
10629                if (DEBUG_FILTERS) {
10630                    Slog.i(TAG, "Found matching filter(s);"
10631                            + " cap priority to " + cappedPriority + ";"
10632                            + " package: " + applicationInfo.packageName
10633                            + " activity: " + intent.activity.className
10634                            + " origPrio: " + intent.getPriority());
10635                }
10636                intent.setPriority(cappedPriority);
10637                return;
10638            }
10639            // all this for nothing; the requested priority was <= what was on the system
10640        }
10641
10642        public final void addActivity(PackageParser.Activity a, String type) {
10643            mActivities.put(a.getComponentName(), a);
10644            if (DEBUG_SHOW_INFO)
10645                Log.v(
10646                TAG, "  " + type + " " +
10647                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10648            if (DEBUG_SHOW_INFO)
10649                Log.v(TAG, "    Class=" + a.info.name);
10650            final int NI = a.intents.size();
10651            for (int j=0; j<NI; j++) {
10652                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10653                if ("activity".equals(type)) {
10654                    final PackageSetting ps =
10655                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10656                    final List<PackageParser.Activity> systemActivities =
10657                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10658                    adjustPriority(systemActivities, intent);
10659                }
10660                if (DEBUG_SHOW_INFO) {
10661                    Log.v(TAG, "    IntentFilter:");
10662                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10663                }
10664                if (!intent.debugCheck()) {
10665                    Log.w(TAG, "==> For Activity " + a.info.name);
10666                }
10667                addFilter(intent);
10668            }
10669        }
10670
10671        public final void removeActivity(PackageParser.Activity a, String type) {
10672            mActivities.remove(a.getComponentName());
10673            if (DEBUG_SHOW_INFO) {
10674                Log.v(TAG, "  " + type + " "
10675                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10676                                : a.info.name) + ":");
10677                Log.v(TAG, "    Class=" + a.info.name);
10678            }
10679            final int NI = a.intents.size();
10680            for (int j=0; j<NI; j++) {
10681                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10682                if (DEBUG_SHOW_INFO) {
10683                    Log.v(TAG, "    IntentFilter:");
10684                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10685                }
10686                removeFilter(intent);
10687            }
10688        }
10689
10690        @Override
10691        protected boolean allowFilterResult(
10692                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10693            ActivityInfo filterAi = filter.activity.info;
10694            for (int i=dest.size()-1; i>=0; i--) {
10695                ActivityInfo destAi = dest.get(i).activityInfo;
10696                if (destAi.name == filterAi.name
10697                        && destAi.packageName == filterAi.packageName) {
10698                    return false;
10699                }
10700            }
10701            return true;
10702        }
10703
10704        @Override
10705        protected ActivityIntentInfo[] newArray(int size) {
10706            return new ActivityIntentInfo[size];
10707        }
10708
10709        @Override
10710        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10711            if (!sUserManager.exists(userId)) return true;
10712            PackageParser.Package p = filter.activity.owner;
10713            if (p != null) {
10714                PackageSetting ps = (PackageSetting)p.mExtras;
10715                if (ps != null) {
10716                    // System apps are never considered stopped for purposes of
10717                    // filtering, because there may be no way for the user to
10718                    // actually re-launch them.
10719                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10720                            && ps.getStopped(userId);
10721                }
10722            }
10723            return false;
10724        }
10725
10726        @Override
10727        protected boolean isPackageForFilter(String packageName,
10728                PackageParser.ActivityIntentInfo info) {
10729            return packageName.equals(info.activity.owner.packageName);
10730        }
10731
10732        @Override
10733        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10734                int match, int userId) {
10735            if (!sUserManager.exists(userId)) return null;
10736            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10737                return null;
10738            }
10739            final PackageParser.Activity activity = info.activity;
10740            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10741            if (ps == null) {
10742                return null;
10743            }
10744            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10745                    ps.readUserState(userId), userId);
10746            if (ai == null) {
10747                return null;
10748            }
10749            final ResolveInfo res = new ResolveInfo();
10750            res.activityInfo = ai;
10751            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10752                res.filter = info;
10753            }
10754            if (info != null) {
10755                res.handleAllWebDataURI = info.handleAllWebDataURI();
10756            }
10757            res.priority = info.getPriority();
10758            res.preferredOrder = activity.owner.mPreferredOrder;
10759            //System.out.println("Result: " + res.activityInfo.className +
10760            //                   " = " + res.priority);
10761            res.match = match;
10762            res.isDefault = info.hasDefault;
10763            res.labelRes = info.labelRes;
10764            res.nonLocalizedLabel = info.nonLocalizedLabel;
10765            if (userNeedsBadging(userId)) {
10766                res.noResourceId = true;
10767            } else {
10768                res.icon = info.icon;
10769            }
10770            res.iconResourceId = info.icon;
10771            res.system = res.activityInfo.applicationInfo.isSystemApp();
10772            return res;
10773        }
10774
10775        @Override
10776        protected void sortResults(List<ResolveInfo> results) {
10777            Collections.sort(results, mResolvePrioritySorter);
10778        }
10779
10780        @Override
10781        protected void dumpFilter(PrintWriter out, String prefix,
10782                PackageParser.ActivityIntentInfo filter) {
10783            out.print(prefix); out.print(
10784                    Integer.toHexString(System.identityHashCode(filter.activity)));
10785                    out.print(' ');
10786                    filter.activity.printComponentShortName(out);
10787                    out.print(" filter ");
10788                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10789        }
10790
10791        @Override
10792        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10793            return filter.activity;
10794        }
10795
10796        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10797            PackageParser.Activity activity = (PackageParser.Activity)label;
10798            out.print(prefix); out.print(
10799                    Integer.toHexString(System.identityHashCode(activity)));
10800                    out.print(' ');
10801                    activity.printComponentShortName(out);
10802            if (count > 1) {
10803                out.print(" ("); out.print(count); out.print(" filters)");
10804            }
10805            out.println();
10806        }
10807
10808        // Keys are String (activity class name), values are Activity.
10809        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10810                = new ArrayMap<ComponentName, PackageParser.Activity>();
10811        private int mFlags;
10812    }
10813
10814    private final class ServiceIntentResolver
10815            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10816        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10817                boolean defaultOnly, int userId) {
10818            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10819            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10820        }
10821
10822        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10823                int userId) {
10824            if (!sUserManager.exists(userId)) return null;
10825            mFlags = flags;
10826            return super.queryIntent(intent, resolvedType,
10827                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10828        }
10829
10830        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10831                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10832            if (!sUserManager.exists(userId)) return null;
10833            if (packageServices == null) {
10834                return null;
10835            }
10836            mFlags = flags;
10837            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10838            final int N = packageServices.size();
10839            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10840                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10841
10842            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10843            for (int i = 0; i < N; ++i) {
10844                intentFilters = packageServices.get(i).intents;
10845                if (intentFilters != null && intentFilters.size() > 0) {
10846                    PackageParser.ServiceIntentInfo[] array =
10847                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10848                    intentFilters.toArray(array);
10849                    listCut.add(array);
10850                }
10851            }
10852            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10853        }
10854
10855        public final void addService(PackageParser.Service s) {
10856            mServices.put(s.getComponentName(), s);
10857            if (DEBUG_SHOW_INFO) {
10858                Log.v(TAG, "  "
10859                        + (s.info.nonLocalizedLabel != null
10860                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10861                Log.v(TAG, "    Class=" + s.info.name);
10862            }
10863            final int NI = s.intents.size();
10864            int j;
10865            for (j=0; j<NI; j++) {
10866                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10867                if (DEBUG_SHOW_INFO) {
10868                    Log.v(TAG, "    IntentFilter:");
10869                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10870                }
10871                if (!intent.debugCheck()) {
10872                    Log.w(TAG, "==> For Service " + s.info.name);
10873                }
10874                addFilter(intent);
10875            }
10876        }
10877
10878        public final void removeService(PackageParser.Service s) {
10879            mServices.remove(s.getComponentName());
10880            if (DEBUG_SHOW_INFO) {
10881                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10882                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10883                Log.v(TAG, "    Class=" + s.info.name);
10884            }
10885            final int NI = s.intents.size();
10886            int j;
10887            for (j=0; j<NI; j++) {
10888                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10889                if (DEBUG_SHOW_INFO) {
10890                    Log.v(TAG, "    IntentFilter:");
10891                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10892                }
10893                removeFilter(intent);
10894            }
10895        }
10896
10897        @Override
10898        protected boolean allowFilterResult(
10899                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10900            ServiceInfo filterSi = filter.service.info;
10901            for (int i=dest.size()-1; i>=0; i--) {
10902                ServiceInfo destAi = dest.get(i).serviceInfo;
10903                if (destAi.name == filterSi.name
10904                        && destAi.packageName == filterSi.packageName) {
10905                    return false;
10906                }
10907            }
10908            return true;
10909        }
10910
10911        @Override
10912        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10913            return new PackageParser.ServiceIntentInfo[size];
10914        }
10915
10916        @Override
10917        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10918            if (!sUserManager.exists(userId)) return true;
10919            PackageParser.Package p = filter.service.owner;
10920            if (p != null) {
10921                PackageSetting ps = (PackageSetting)p.mExtras;
10922                if (ps != null) {
10923                    // System apps are never considered stopped for purposes of
10924                    // filtering, because there may be no way for the user to
10925                    // actually re-launch them.
10926                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10927                            && ps.getStopped(userId);
10928                }
10929            }
10930            return false;
10931        }
10932
10933        @Override
10934        protected boolean isPackageForFilter(String packageName,
10935                PackageParser.ServiceIntentInfo info) {
10936            return packageName.equals(info.service.owner.packageName);
10937        }
10938
10939        @Override
10940        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10941                int match, int userId) {
10942            if (!sUserManager.exists(userId)) return null;
10943            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10944            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10945                return null;
10946            }
10947            final PackageParser.Service service = info.service;
10948            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10949            if (ps == null) {
10950                return null;
10951            }
10952            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10953                    ps.readUserState(userId), userId);
10954            if (si == null) {
10955                return null;
10956            }
10957            final ResolveInfo res = new ResolveInfo();
10958            res.serviceInfo = si;
10959            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10960                res.filter = filter;
10961            }
10962            res.priority = info.getPriority();
10963            res.preferredOrder = service.owner.mPreferredOrder;
10964            res.match = match;
10965            res.isDefault = info.hasDefault;
10966            res.labelRes = info.labelRes;
10967            res.nonLocalizedLabel = info.nonLocalizedLabel;
10968            res.icon = info.icon;
10969            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10970            return res;
10971        }
10972
10973        @Override
10974        protected void sortResults(List<ResolveInfo> results) {
10975            Collections.sort(results, mResolvePrioritySorter);
10976        }
10977
10978        @Override
10979        protected void dumpFilter(PrintWriter out, String prefix,
10980                PackageParser.ServiceIntentInfo filter) {
10981            out.print(prefix); out.print(
10982                    Integer.toHexString(System.identityHashCode(filter.service)));
10983                    out.print(' ');
10984                    filter.service.printComponentShortName(out);
10985                    out.print(" filter ");
10986                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10987        }
10988
10989        @Override
10990        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10991            return filter.service;
10992        }
10993
10994        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10995            PackageParser.Service service = (PackageParser.Service)label;
10996            out.print(prefix); out.print(
10997                    Integer.toHexString(System.identityHashCode(service)));
10998                    out.print(' ');
10999                    service.printComponentShortName(out);
11000            if (count > 1) {
11001                out.print(" ("); out.print(count); out.print(" filters)");
11002            }
11003            out.println();
11004        }
11005
11006//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11007//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11008//            final List<ResolveInfo> retList = Lists.newArrayList();
11009//            while (i.hasNext()) {
11010//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11011//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11012//                    retList.add(resolveInfo);
11013//                }
11014//            }
11015//            return retList;
11016//        }
11017
11018        // Keys are String (activity class name), values are Activity.
11019        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11020                = new ArrayMap<ComponentName, PackageParser.Service>();
11021        private int mFlags;
11022    };
11023
11024    private final class ProviderIntentResolver
11025            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11026        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11027                boolean defaultOnly, int userId) {
11028            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11029            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11030        }
11031
11032        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11033                int userId) {
11034            if (!sUserManager.exists(userId))
11035                return null;
11036            mFlags = flags;
11037            return super.queryIntent(intent, resolvedType,
11038                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11039        }
11040
11041        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11042                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11043            if (!sUserManager.exists(userId))
11044                return null;
11045            if (packageProviders == null) {
11046                return null;
11047            }
11048            mFlags = flags;
11049            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11050            final int N = packageProviders.size();
11051            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11052                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11053
11054            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11055            for (int i = 0; i < N; ++i) {
11056                intentFilters = packageProviders.get(i).intents;
11057                if (intentFilters != null && intentFilters.size() > 0) {
11058                    PackageParser.ProviderIntentInfo[] array =
11059                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11060                    intentFilters.toArray(array);
11061                    listCut.add(array);
11062                }
11063            }
11064            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11065        }
11066
11067        public final void addProvider(PackageParser.Provider p) {
11068            if (mProviders.containsKey(p.getComponentName())) {
11069                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11070                return;
11071            }
11072
11073            mProviders.put(p.getComponentName(), p);
11074            if (DEBUG_SHOW_INFO) {
11075                Log.v(TAG, "  "
11076                        + (p.info.nonLocalizedLabel != null
11077                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11078                Log.v(TAG, "    Class=" + p.info.name);
11079            }
11080            final int NI = p.intents.size();
11081            int j;
11082            for (j = 0; j < NI; j++) {
11083                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11084                if (DEBUG_SHOW_INFO) {
11085                    Log.v(TAG, "    IntentFilter:");
11086                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11087                }
11088                if (!intent.debugCheck()) {
11089                    Log.w(TAG, "==> For Provider " + p.info.name);
11090                }
11091                addFilter(intent);
11092            }
11093        }
11094
11095        public final void removeProvider(PackageParser.Provider p) {
11096            mProviders.remove(p.getComponentName());
11097            if (DEBUG_SHOW_INFO) {
11098                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11099                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11100                Log.v(TAG, "    Class=" + p.info.name);
11101            }
11102            final int NI = p.intents.size();
11103            int j;
11104            for (j = 0; j < NI; j++) {
11105                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11106                if (DEBUG_SHOW_INFO) {
11107                    Log.v(TAG, "    IntentFilter:");
11108                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11109                }
11110                removeFilter(intent);
11111            }
11112        }
11113
11114        @Override
11115        protected boolean allowFilterResult(
11116                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11117            ProviderInfo filterPi = filter.provider.info;
11118            for (int i = dest.size() - 1; i >= 0; i--) {
11119                ProviderInfo destPi = dest.get(i).providerInfo;
11120                if (destPi.name == filterPi.name
11121                        && destPi.packageName == filterPi.packageName) {
11122                    return false;
11123                }
11124            }
11125            return true;
11126        }
11127
11128        @Override
11129        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11130            return new PackageParser.ProviderIntentInfo[size];
11131        }
11132
11133        @Override
11134        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11135            if (!sUserManager.exists(userId))
11136                return true;
11137            PackageParser.Package p = filter.provider.owner;
11138            if (p != null) {
11139                PackageSetting ps = (PackageSetting) p.mExtras;
11140                if (ps != null) {
11141                    // System apps are never considered stopped for purposes of
11142                    // filtering, because there may be no way for the user to
11143                    // actually re-launch them.
11144                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11145                            && ps.getStopped(userId);
11146                }
11147            }
11148            return false;
11149        }
11150
11151        @Override
11152        protected boolean isPackageForFilter(String packageName,
11153                PackageParser.ProviderIntentInfo info) {
11154            return packageName.equals(info.provider.owner.packageName);
11155        }
11156
11157        @Override
11158        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11159                int match, int userId) {
11160            if (!sUserManager.exists(userId))
11161                return null;
11162            final PackageParser.ProviderIntentInfo info = filter;
11163            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11164                return null;
11165            }
11166            final PackageParser.Provider provider = info.provider;
11167            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11168            if (ps == null) {
11169                return null;
11170            }
11171            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11172                    ps.readUserState(userId), userId);
11173            if (pi == null) {
11174                return null;
11175            }
11176            final ResolveInfo res = new ResolveInfo();
11177            res.providerInfo = pi;
11178            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11179                res.filter = filter;
11180            }
11181            res.priority = info.getPriority();
11182            res.preferredOrder = provider.owner.mPreferredOrder;
11183            res.match = match;
11184            res.isDefault = info.hasDefault;
11185            res.labelRes = info.labelRes;
11186            res.nonLocalizedLabel = info.nonLocalizedLabel;
11187            res.icon = info.icon;
11188            res.system = res.providerInfo.applicationInfo.isSystemApp();
11189            return res;
11190        }
11191
11192        @Override
11193        protected void sortResults(List<ResolveInfo> results) {
11194            Collections.sort(results, mResolvePrioritySorter);
11195        }
11196
11197        @Override
11198        protected void dumpFilter(PrintWriter out, String prefix,
11199                PackageParser.ProviderIntentInfo filter) {
11200            out.print(prefix);
11201            out.print(
11202                    Integer.toHexString(System.identityHashCode(filter.provider)));
11203            out.print(' ');
11204            filter.provider.printComponentShortName(out);
11205            out.print(" filter ");
11206            out.println(Integer.toHexString(System.identityHashCode(filter)));
11207        }
11208
11209        @Override
11210        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11211            return filter.provider;
11212        }
11213
11214        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11215            PackageParser.Provider provider = (PackageParser.Provider)label;
11216            out.print(prefix); out.print(
11217                    Integer.toHexString(System.identityHashCode(provider)));
11218                    out.print(' ');
11219                    provider.printComponentShortName(out);
11220            if (count > 1) {
11221                out.print(" ("); out.print(count); out.print(" filters)");
11222            }
11223            out.println();
11224        }
11225
11226        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11227                = new ArrayMap<ComponentName, PackageParser.Provider>();
11228        private int mFlags;
11229    }
11230
11231    private static final class EphemeralIntentResolver
11232            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11233        /**
11234         * The result that has the highest defined order. Ordering applies on a
11235         * per-package basis. Mapping is from package name to Pair of order and
11236         * EphemeralResolveInfo.
11237         * <p>
11238         * NOTE: This is implemented as a field variable for convenience and efficiency.
11239         * By having a field variable, we're able to track filter ordering as soon as
11240         * a non-zero order is defined. Otherwise, multiple loops across the result set
11241         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11242         * this needs to be contained entirely within {@link #filterResults()}.
11243         */
11244        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11245
11246        @Override
11247        protected EphemeralResolveIntentInfo[] newArray(int size) {
11248            return new EphemeralResolveIntentInfo[size];
11249        }
11250
11251        @Override
11252        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11253            return true;
11254        }
11255
11256        @Override
11257        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11258                int userId) {
11259            if (!sUserManager.exists(userId)) {
11260                return null;
11261            }
11262            final String packageName = info.getEphemeralResolveInfo().getPackageName();
11263            final Integer order = info.getOrder();
11264            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11265                    mOrderResult.get(packageName);
11266            // ordering is enabled and this item's order isn't high enough
11267            if (lastOrderResult != null && lastOrderResult.first >= order) {
11268                return null;
11269            }
11270            final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11271            if (order > 0) {
11272                // non-zero order, enable ordering
11273                mOrderResult.put(packageName, new Pair<>(order, res));
11274            }
11275            return res;
11276        }
11277
11278        @Override
11279        protected void filterResults(List<EphemeralResolveInfo> results) {
11280            // only do work if ordering is enabled [most of the time it won't be]
11281            if (mOrderResult.size() == 0) {
11282                return;
11283            }
11284            int resultSize = results.size();
11285            for (int i = 0; i < resultSize; i++) {
11286                final EphemeralResolveInfo info = results.get(i);
11287                final String packageName = info.getPackageName();
11288                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11289                if (savedInfo == null) {
11290                    // package doesn't having ordering
11291                    continue;
11292                }
11293                if (savedInfo.second == info) {
11294                    // circled back to the highest ordered item; remove from order list
11295                    mOrderResult.remove(savedInfo);
11296                    if (mOrderResult.size() == 0) {
11297                        // no more ordered items
11298                        break;
11299                    }
11300                    continue;
11301                }
11302                // item has a worse order, remove it from the result list
11303                results.remove(i);
11304                resultSize--;
11305                i--;
11306            }
11307        }
11308    }
11309
11310    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11311            new Comparator<ResolveInfo>() {
11312        public int compare(ResolveInfo r1, ResolveInfo r2) {
11313            int v1 = r1.priority;
11314            int v2 = r2.priority;
11315            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11316            if (v1 != v2) {
11317                return (v1 > v2) ? -1 : 1;
11318            }
11319            v1 = r1.preferredOrder;
11320            v2 = r2.preferredOrder;
11321            if (v1 != v2) {
11322                return (v1 > v2) ? -1 : 1;
11323            }
11324            if (r1.isDefault != r2.isDefault) {
11325                return r1.isDefault ? -1 : 1;
11326            }
11327            v1 = r1.match;
11328            v2 = r2.match;
11329            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11330            if (v1 != v2) {
11331                return (v1 > v2) ? -1 : 1;
11332            }
11333            if (r1.system != r2.system) {
11334                return r1.system ? -1 : 1;
11335            }
11336            if (r1.activityInfo != null) {
11337                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11338            }
11339            if (r1.serviceInfo != null) {
11340                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11341            }
11342            if (r1.providerInfo != null) {
11343                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11344            }
11345            return 0;
11346        }
11347    };
11348
11349    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11350            new Comparator<ProviderInfo>() {
11351        public int compare(ProviderInfo p1, ProviderInfo p2) {
11352            final int v1 = p1.initOrder;
11353            final int v2 = p2.initOrder;
11354            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11355        }
11356    };
11357
11358    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11359            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11360            final int[] userIds) {
11361        mHandler.post(new Runnable() {
11362            @Override
11363            public void run() {
11364                try {
11365                    final IActivityManager am = ActivityManagerNative.getDefault();
11366                    if (am == null) return;
11367                    final int[] resolvedUserIds;
11368                    if (userIds == null) {
11369                        resolvedUserIds = am.getRunningUserIds();
11370                    } else {
11371                        resolvedUserIds = userIds;
11372                    }
11373                    for (int id : resolvedUserIds) {
11374                        final Intent intent = new Intent(action,
11375                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11376                        if (extras != null) {
11377                            intent.putExtras(extras);
11378                        }
11379                        if (targetPkg != null) {
11380                            intent.setPackage(targetPkg);
11381                        }
11382                        // Modify the UID when posting to other users
11383                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11384                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11385                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11386                            intent.putExtra(Intent.EXTRA_UID, uid);
11387                        }
11388                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11389                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11390                        if (DEBUG_BROADCASTS) {
11391                            RuntimeException here = new RuntimeException("here");
11392                            here.fillInStackTrace();
11393                            Slog.d(TAG, "Sending to user " + id + ": "
11394                                    + intent.toShortString(false, true, false, false)
11395                                    + " " + intent.getExtras(), here);
11396                        }
11397                        am.broadcastIntent(null, intent, null, finishedReceiver,
11398                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11399                                null, finishedReceiver != null, false, id);
11400                    }
11401                } catch (RemoteException ex) {
11402                }
11403            }
11404        });
11405    }
11406
11407    /**
11408     * Check if the external storage media is available. This is true if there
11409     * is a mounted external storage medium or if the external storage is
11410     * emulated.
11411     */
11412    private boolean isExternalMediaAvailable() {
11413        return mMediaMounted || Environment.isExternalStorageEmulated();
11414    }
11415
11416    @Override
11417    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11418        // writer
11419        synchronized (mPackages) {
11420            if (!isExternalMediaAvailable()) {
11421                // If the external storage is no longer mounted at this point,
11422                // the caller may not have been able to delete all of this
11423                // packages files and can not delete any more.  Bail.
11424                return null;
11425            }
11426            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11427            if (lastPackage != null) {
11428                pkgs.remove(lastPackage);
11429            }
11430            if (pkgs.size() > 0) {
11431                return pkgs.get(0);
11432            }
11433        }
11434        return null;
11435    }
11436
11437    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11438        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11439                userId, andCode ? 1 : 0, packageName);
11440        if (mSystemReady) {
11441            msg.sendToTarget();
11442        } else {
11443            if (mPostSystemReadyMessages == null) {
11444                mPostSystemReadyMessages = new ArrayList<>();
11445            }
11446            mPostSystemReadyMessages.add(msg);
11447        }
11448    }
11449
11450    void startCleaningPackages() {
11451        // reader
11452        if (!isExternalMediaAvailable()) {
11453            return;
11454        }
11455        synchronized (mPackages) {
11456            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11457                return;
11458            }
11459        }
11460        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11461        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11462        IActivityManager am = ActivityManagerNative.getDefault();
11463        if (am != null) {
11464            try {
11465                am.startService(null, intent, null, mContext.getOpPackageName(),
11466                        UserHandle.USER_SYSTEM);
11467            } catch (RemoteException e) {
11468            }
11469        }
11470    }
11471
11472    @Override
11473    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11474            int installFlags, String installerPackageName, int userId) {
11475        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11476
11477        final int callingUid = Binder.getCallingUid();
11478        enforceCrossUserPermission(callingUid, userId,
11479                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11480
11481        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11482            try {
11483                if (observer != null) {
11484                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11485                }
11486            } catch (RemoteException re) {
11487            }
11488            return;
11489        }
11490
11491        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11492            installFlags |= PackageManager.INSTALL_FROM_ADB;
11493
11494        } else {
11495            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11496            // about installerPackageName.
11497
11498            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11499            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11500        }
11501
11502        UserHandle user;
11503        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11504            user = UserHandle.ALL;
11505        } else {
11506            user = new UserHandle(userId);
11507        }
11508
11509        // Only system components can circumvent runtime permissions when installing.
11510        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11511                && mContext.checkCallingOrSelfPermission(Manifest.permission
11512                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11513            throw new SecurityException("You need the "
11514                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11515                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11516        }
11517
11518        final File originFile = new File(originPath);
11519        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11520
11521        final Message msg = mHandler.obtainMessage(INIT_COPY);
11522        final VerificationInfo verificationInfo = new VerificationInfo(
11523                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11524        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11525                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11526                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11527                null /*certificates*/);
11528        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11529        msg.obj = params;
11530
11531        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
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    void installStage(String packageName, File stagedDir, String stagedCid,
11540            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11541            String installerPackageName, int installerUid, UserHandle user,
11542            Certificate[][] certificates) {
11543        if (DEBUG_EPHEMERAL) {
11544            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11545                Slog.d(TAG, "Ephemeral install of " + packageName);
11546            }
11547        }
11548        final VerificationInfo verificationInfo = new VerificationInfo(
11549                sessionParams.originatingUri, sessionParams.referrerUri,
11550                sessionParams.originatingUid, installerUid);
11551
11552        final OriginInfo origin;
11553        if (stagedDir != null) {
11554            origin = OriginInfo.fromStagedFile(stagedDir);
11555        } else {
11556            origin = OriginInfo.fromStagedContainer(stagedCid);
11557        }
11558
11559        final Message msg = mHandler.obtainMessage(INIT_COPY);
11560        final InstallParams params = new InstallParams(origin, null, observer,
11561                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11562                verificationInfo, user, sessionParams.abiOverride,
11563                sessionParams.grantedRuntimePermissions, certificates);
11564        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11565        msg.obj = params;
11566
11567        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11568                System.identityHashCode(msg.obj));
11569        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11570                System.identityHashCode(msg.obj));
11571
11572        mHandler.sendMessage(msg);
11573    }
11574
11575    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11576            int userId) {
11577        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11578        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11579    }
11580
11581    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11582            int appId, int userId) {
11583        Bundle extras = new Bundle(1);
11584        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11585
11586        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11587                packageName, extras, 0, null, null, new int[] {userId});
11588        try {
11589            IActivityManager am = ActivityManagerNative.getDefault();
11590            if (isSystem && am.isUserRunning(userId, 0)) {
11591                // The just-installed/enabled app is bundled on the system, so presumed
11592                // to be able to run automatically without needing an explicit launch.
11593                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11594                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11595                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11596                        .setPackage(packageName);
11597                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11598                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11599            }
11600        } catch (RemoteException e) {
11601            // shouldn't happen
11602            Slog.w(TAG, "Unable to bootstrap installed package", e);
11603        }
11604    }
11605
11606    @Override
11607    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11608            int userId) {
11609        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11610        PackageSetting pkgSetting;
11611        final int uid = Binder.getCallingUid();
11612        enforceCrossUserPermission(uid, userId,
11613                true /* requireFullPermission */, true /* checkShell */,
11614                "setApplicationHiddenSetting for user " + userId);
11615
11616        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11617            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11618            return false;
11619        }
11620
11621        long callingId = Binder.clearCallingIdentity();
11622        try {
11623            boolean sendAdded = false;
11624            boolean sendRemoved = false;
11625            // writer
11626            synchronized (mPackages) {
11627                pkgSetting = mSettings.mPackages.get(packageName);
11628                if (pkgSetting == null) {
11629                    return false;
11630                }
11631                // Do not allow "android" is being disabled
11632                if ("android".equals(packageName)) {
11633                    Slog.w(TAG, "Cannot hide package: android");
11634                    return false;
11635                }
11636                // Only allow protected packages to hide themselves.
11637                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11638                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11639                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11640                    return false;
11641                }
11642
11643                if (pkgSetting.getHidden(userId) != hidden) {
11644                    pkgSetting.setHidden(hidden, userId);
11645                    mSettings.writePackageRestrictionsLPr(userId);
11646                    if (hidden) {
11647                        sendRemoved = true;
11648                    } else {
11649                        sendAdded = true;
11650                    }
11651                }
11652            }
11653            if (sendAdded) {
11654                sendPackageAddedForUser(packageName, pkgSetting, userId);
11655                return true;
11656            }
11657            if (sendRemoved) {
11658                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11659                        "hiding pkg");
11660                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11661                return true;
11662            }
11663        } finally {
11664            Binder.restoreCallingIdentity(callingId);
11665        }
11666        return false;
11667    }
11668
11669    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11670            int userId) {
11671        final PackageRemovedInfo info = new PackageRemovedInfo();
11672        info.removedPackage = packageName;
11673        info.removedUsers = new int[] {userId};
11674        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11675        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11676    }
11677
11678    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11679        if (pkgList.length > 0) {
11680            Bundle extras = new Bundle(1);
11681            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11682
11683            sendPackageBroadcast(
11684                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11685                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11686                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11687                    new int[] {userId});
11688        }
11689    }
11690
11691    /**
11692     * Returns true if application is not found or there was an error. Otherwise it returns
11693     * the hidden state of the package for the given user.
11694     */
11695    @Override
11696    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11697        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11698        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11699                true /* requireFullPermission */, false /* checkShell */,
11700                "getApplicationHidden for user " + userId);
11701        PackageSetting pkgSetting;
11702        long callingId = Binder.clearCallingIdentity();
11703        try {
11704            // writer
11705            synchronized (mPackages) {
11706                pkgSetting = mSettings.mPackages.get(packageName);
11707                if (pkgSetting == null) {
11708                    return true;
11709                }
11710                return pkgSetting.getHidden(userId);
11711            }
11712        } finally {
11713            Binder.restoreCallingIdentity(callingId);
11714        }
11715    }
11716
11717    /**
11718     * @hide
11719     */
11720    @Override
11721    public int installExistingPackageAsUser(String packageName, int userId) {
11722        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11723                null);
11724        PackageSetting pkgSetting;
11725        final int uid = Binder.getCallingUid();
11726        enforceCrossUserPermission(uid, userId,
11727                true /* requireFullPermission */, true /* checkShell */,
11728                "installExistingPackage for user " + userId);
11729        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11730            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11731        }
11732
11733        long callingId = Binder.clearCallingIdentity();
11734        try {
11735            boolean installed = false;
11736
11737            // writer
11738            synchronized (mPackages) {
11739                pkgSetting = mSettings.mPackages.get(packageName);
11740                if (pkgSetting == null) {
11741                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11742                }
11743                if (!pkgSetting.getInstalled(userId)) {
11744                    pkgSetting.setInstalled(true, userId);
11745                    pkgSetting.setHidden(false, userId);
11746                    mSettings.writePackageRestrictionsLPr(userId);
11747                    installed = true;
11748                }
11749            }
11750
11751            if (installed) {
11752                if (pkgSetting.pkg != null) {
11753                    synchronized (mInstallLock) {
11754                        // We don't need to freeze for a brand new install
11755                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11756                    }
11757                }
11758                sendPackageAddedForUser(packageName, pkgSetting, userId);
11759            }
11760        } finally {
11761            Binder.restoreCallingIdentity(callingId);
11762        }
11763
11764        return PackageManager.INSTALL_SUCCEEDED;
11765    }
11766
11767    boolean isUserRestricted(int userId, String restrictionKey) {
11768        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11769        if (restrictions.getBoolean(restrictionKey, false)) {
11770            Log.w(TAG, "User is restricted: " + restrictionKey);
11771            return true;
11772        }
11773        return false;
11774    }
11775
11776    @Override
11777    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11778            int userId) {
11779        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11780        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11781                true /* requireFullPermission */, true /* checkShell */,
11782                "setPackagesSuspended for user " + userId);
11783
11784        if (ArrayUtils.isEmpty(packageNames)) {
11785            return packageNames;
11786        }
11787
11788        // List of package names for whom the suspended state has changed.
11789        List<String> changedPackages = new ArrayList<>(packageNames.length);
11790        // List of package names for whom the suspended state is not set as requested in this
11791        // method.
11792        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11793        long callingId = Binder.clearCallingIdentity();
11794        try {
11795            for (int i = 0; i < packageNames.length; i++) {
11796                String packageName = packageNames[i];
11797                boolean changed = false;
11798                final int appId;
11799                synchronized (mPackages) {
11800                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11801                    if (pkgSetting == null) {
11802                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11803                                + "\". Skipping suspending/un-suspending.");
11804                        unactionedPackages.add(packageName);
11805                        continue;
11806                    }
11807                    appId = pkgSetting.appId;
11808                    if (pkgSetting.getSuspended(userId) != suspended) {
11809                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11810                            unactionedPackages.add(packageName);
11811                            continue;
11812                        }
11813                        pkgSetting.setSuspended(suspended, userId);
11814                        mSettings.writePackageRestrictionsLPr(userId);
11815                        changed = true;
11816                        changedPackages.add(packageName);
11817                    }
11818                }
11819
11820                if (changed && suspended) {
11821                    killApplication(packageName, UserHandle.getUid(userId, appId),
11822                            "suspending package");
11823                }
11824            }
11825        } finally {
11826            Binder.restoreCallingIdentity(callingId);
11827        }
11828
11829        if (!changedPackages.isEmpty()) {
11830            sendPackagesSuspendedForUser(changedPackages.toArray(
11831                    new String[changedPackages.size()]), userId, suspended);
11832        }
11833
11834        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11835    }
11836
11837    @Override
11838    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11839        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11840                true /* requireFullPermission */, false /* checkShell */,
11841                "isPackageSuspendedForUser for user " + userId);
11842        synchronized (mPackages) {
11843            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11844            if (pkgSetting == null) {
11845                throw new IllegalArgumentException("Unknown target package: " + packageName);
11846            }
11847            return pkgSetting.getSuspended(userId);
11848        }
11849    }
11850
11851    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11852        if (isPackageDeviceAdmin(packageName, userId)) {
11853            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11854                    + "\": has an active device admin");
11855            return false;
11856        }
11857
11858        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11859        if (packageName.equals(activeLauncherPackageName)) {
11860            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11861                    + "\": contains the active launcher");
11862            return false;
11863        }
11864
11865        if (packageName.equals(mRequiredInstallerPackage)) {
11866            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11867                    + "\": required for package installation");
11868            return false;
11869        }
11870
11871        if (packageName.equals(mRequiredVerifierPackage)) {
11872            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11873                    + "\": required for package verification");
11874            return false;
11875        }
11876
11877        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11878            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11879                    + "\": is the default dialer");
11880            return false;
11881        }
11882
11883        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11884            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11885                    + "\": protected package");
11886            return false;
11887        }
11888
11889        return true;
11890    }
11891
11892    private String getActiveLauncherPackageName(int userId) {
11893        Intent intent = new Intent(Intent.ACTION_MAIN);
11894        intent.addCategory(Intent.CATEGORY_HOME);
11895        ResolveInfo resolveInfo = resolveIntent(
11896                intent,
11897                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11898                PackageManager.MATCH_DEFAULT_ONLY,
11899                userId);
11900
11901        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11902    }
11903
11904    private String getDefaultDialerPackageName(int userId) {
11905        synchronized (mPackages) {
11906            return mSettings.getDefaultDialerPackageNameLPw(userId);
11907        }
11908    }
11909
11910    @Override
11911    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11912        mContext.enforceCallingOrSelfPermission(
11913                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11914                "Only package verification agents can verify applications");
11915
11916        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11917        final PackageVerificationResponse response = new PackageVerificationResponse(
11918                verificationCode, Binder.getCallingUid());
11919        msg.arg1 = id;
11920        msg.obj = response;
11921        mHandler.sendMessage(msg);
11922    }
11923
11924    @Override
11925    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11926            long millisecondsToDelay) {
11927        mContext.enforceCallingOrSelfPermission(
11928                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11929                "Only package verification agents can extend verification timeouts");
11930
11931        final PackageVerificationState state = mPendingVerification.get(id);
11932        final PackageVerificationResponse response = new PackageVerificationResponse(
11933                verificationCodeAtTimeout, Binder.getCallingUid());
11934
11935        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11936            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11937        }
11938        if (millisecondsToDelay < 0) {
11939            millisecondsToDelay = 0;
11940        }
11941        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11942                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11943            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11944        }
11945
11946        if ((state != null) && !state.timeoutExtended()) {
11947            state.extendTimeout();
11948
11949            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11950            msg.arg1 = id;
11951            msg.obj = response;
11952            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11953        }
11954    }
11955
11956    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11957            int verificationCode, UserHandle user) {
11958        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11959        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11960        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11961        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11962        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11963
11964        mContext.sendBroadcastAsUser(intent, user,
11965                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11966    }
11967
11968    private ComponentName matchComponentForVerifier(String packageName,
11969            List<ResolveInfo> receivers) {
11970        ActivityInfo targetReceiver = null;
11971
11972        final int NR = receivers.size();
11973        for (int i = 0; i < NR; i++) {
11974            final ResolveInfo info = receivers.get(i);
11975            if (info.activityInfo == null) {
11976                continue;
11977            }
11978
11979            if (packageName.equals(info.activityInfo.packageName)) {
11980                targetReceiver = info.activityInfo;
11981                break;
11982            }
11983        }
11984
11985        if (targetReceiver == null) {
11986            return null;
11987        }
11988
11989        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11990    }
11991
11992    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11993            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11994        if (pkgInfo.verifiers.length == 0) {
11995            return null;
11996        }
11997
11998        final int N = pkgInfo.verifiers.length;
11999        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12000        for (int i = 0; i < N; i++) {
12001            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12002
12003            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12004                    receivers);
12005            if (comp == null) {
12006                continue;
12007            }
12008
12009            final int verifierUid = getUidForVerifier(verifierInfo);
12010            if (verifierUid == -1) {
12011                continue;
12012            }
12013
12014            if (DEBUG_VERIFY) {
12015                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12016                        + " with the correct signature");
12017            }
12018            sufficientVerifiers.add(comp);
12019            verificationState.addSufficientVerifier(verifierUid);
12020        }
12021
12022        return sufficientVerifiers;
12023    }
12024
12025    private int getUidForVerifier(VerifierInfo verifierInfo) {
12026        synchronized (mPackages) {
12027            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12028            if (pkg == null) {
12029                return -1;
12030            } else if (pkg.mSignatures.length != 1) {
12031                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12032                        + " has more than one signature; ignoring");
12033                return -1;
12034            }
12035
12036            /*
12037             * If the public key of the package's signature does not match
12038             * our expected public key, then this is a different package and
12039             * we should skip.
12040             */
12041
12042            final byte[] expectedPublicKey;
12043            try {
12044                final Signature verifierSig = pkg.mSignatures[0];
12045                final PublicKey publicKey = verifierSig.getPublicKey();
12046                expectedPublicKey = publicKey.getEncoded();
12047            } catch (CertificateException e) {
12048                return -1;
12049            }
12050
12051            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12052
12053            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12054                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12055                        + " does not have the expected public key; ignoring");
12056                return -1;
12057            }
12058
12059            return pkg.applicationInfo.uid;
12060        }
12061    }
12062
12063    @Override
12064    public void finishPackageInstall(int token, boolean didLaunch) {
12065        enforceSystemOrRoot("Only the system is allowed to finish installs");
12066
12067        if (DEBUG_INSTALL) {
12068            Slog.v(TAG, "BM finishing package install for " + token);
12069        }
12070        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12071
12072        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12073        mHandler.sendMessage(msg);
12074    }
12075
12076    /**
12077     * Get the verification agent timeout.
12078     *
12079     * @return verification timeout in milliseconds
12080     */
12081    private long getVerificationTimeout() {
12082        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12083                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12084                DEFAULT_VERIFICATION_TIMEOUT);
12085    }
12086
12087    /**
12088     * Get the default verification agent response code.
12089     *
12090     * @return default verification response code
12091     */
12092    private int getDefaultVerificationResponse() {
12093        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12094                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12095                DEFAULT_VERIFICATION_RESPONSE);
12096    }
12097
12098    /**
12099     * Check whether or not package verification has been enabled.
12100     *
12101     * @return true if verification should be performed
12102     */
12103    private boolean isVerificationEnabled(int userId, int installFlags) {
12104        if (!DEFAULT_VERIFY_ENABLE) {
12105            return false;
12106        }
12107        // Ephemeral apps don't get the full verification treatment
12108        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12109            if (DEBUG_EPHEMERAL) {
12110                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12111            }
12112            return false;
12113        }
12114
12115        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12116
12117        // Check if installing from ADB
12118        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12119            // Do not run verification in a test harness environment
12120            if (ActivityManager.isRunningInTestHarness()) {
12121                return false;
12122            }
12123            if (ensureVerifyAppsEnabled) {
12124                return true;
12125            }
12126            // Check if the developer does not want package verification for ADB installs
12127            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12128                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12129                return false;
12130            }
12131        }
12132
12133        if (ensureVerifyAppsEnabled) {
12134            return true;
12135        }
12136
12137        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12138                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12139    }
12140
12141    @Override
12142    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12143            throws RemoteException {
12144        mContext.enforceCallingOrSelfPermission(
12145                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12146                "Only intentfilter verification agents can verify applications");
12147
12148        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12149        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12150                Binder.getCallingUid(), verificationCode, failedDomains);
12151        msg.arg1 = id;
12152        msg.obj = response;
12153        mHandler.sendMessage(msg);
12154    }
12155
12156    @Override
12157    public int getIntentVerificationStatus(String packageName, int userId) {
12158        synchronized (mPackages) {
12159            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12160        }
12161    }
12162
12163    @Override
12164    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12165        mContext.enforceCallingOrSelfPermission(
12166                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12167
12168        boolean result = false;
12169        synchronized (mPackages) {
12170            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12171        }
12172        if (result) {
12173            scheduleWritePackageRestrictionsLocked(userId);
12174        }
12175        return result;
12176    }
12177
12178    @Override
12179    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12180            String packageName) {
12181        synchronized (mPackages) {
12182            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12183        }
12184    }
12185
12186    @Override
12187    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12188        if (TextUtils.isEmpty(packageName)) {
12189            return ParceledListSlice.emptyList();
12190        }
12191        synchronized (mPackages) {
12192            PackageParser.Package pkg = mPackages.get(packageName);
12193            if (pkg == null || pkg.activities == null) {
12194                return ParceledListSlice.emptyList();
12195            }
12196            final int count = pkg.activities.size();
12197            ArrayList<IntentFilter> result = new ArrayList<>();
12198            for (int n=0; n<count; n++) {
12199                PackageParser.Activity activity = pkg.activities.get(n);
12200                if (activity.intents != null && activity.intents.size() > 0) {
12201                    result.addAll(activity.intents);
12202                }
12203            }
12204            return new ParceledListSlice<>(result);
12205        }
12206    }
12207
12208    @Override
12209    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12210        mContext.enforceCallingOrSelfPermission(
12211                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12212
12213        synchronized (mPackages) {
12214            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12215            if (packageName != null) {
12216                result |= updateIntentVerificationStatus(packageName,
12217                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12218                        userId);
12219                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12220                        packageName, userId);
12221            }
12222            return result;
12223        }
12224    }
12225
12226    @Override
12227    public String getDefaultBrowserPackageName(int userId) {
12228        synchronized (mPackages) {
12229            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12230        }
12231    }
12232
12233    /**
12234     * Get the "allow unknown sources" setting.
12235     *
12236     * @return the current "allow unknown sources" setting
12237     */
12238    private int getUnknownSourcesSettings() {
12239        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12240                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12241                -1);
12242    }
12243
12244    @Override
12245    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12246        final int uid = Binder.getCallingUid();
12247        // writer
12248        synchronized (mPackages) {
12249            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12250            if (targetPackageSetting == null) {
12251                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12252            }
12253
12254            PackageSetting installerPackageSetting;
12255            if (installerPackageName != null) {
12256                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12257                if (installerPackageSetting == null) {
12258                    throw new IllegalArgumentException("Unknown installer package: "
12259                            + installerPackageName);
12260                }
12261            } else {
12262                installerPackageSetting = null;
12263            }
12264
12265            Signature[] callerSignature;
12266            Object obj = mSettings.getUserIdLPr(uid);
12267            if (obj != null) {
12268                if (obj instanceof SharedUserSetting) {
12269                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12270                } else if (obj instanceof PackageSetting) {
12271                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12272                } else {
12273                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12274                }
12275            } else {
12276                throw new SecurityException("Unknown calling UID: " + uid);
12277            }
12278
12279            // Verify: can't set installerPackageName to a package that is
12280            // not signed with the same cert as the caller.
12281            if (installerPackageSetting != null) {
12282                if (compareSignatures(callerSignature,
12283                        installerPackageSetting.signatures.mSignatures)
12284                        != PackageManager.SIGNATURE_MATCH) {
12285                    throw new SecurityException(
12286                            "Caller does not have same cert as new installer package "
12287                            + installerPackageName);
12288                }
12289            }
12290
12291            // Verify: if target already has an installer package, it must
12292            // be signed with the same cert as the caller.
12293            if (targetPackageSetting.installerPackageName != null) {
12294                PackageSetting setting = mSettings.mPackages.get(
12295                        targetPackageSetting.installerPackageName);
12296                // If the currently set package isn't valid, then it's always
12297                // okay to change it.
12298                if (setting != null) {
12299                    if (compareSignatures(callerSignature,
12300                            setting.signatures.mSignatures)
12301                            != PackageManager.SIGNATURE_MATCH) {
12302                        throw new SecurityException(
12303                                "Caller does not have same cert as old installer package "
12304                                + targetPackageSetting.installerPackageName);
12305                    }
12306                }
12307            }
12308
12309            // Okay!
12310            targetPackageSetting.installerPackageName = installerPackageName;
12311            if (installerPackageName != null) {
12312                mSettings.mInstallerPackages.add(installerPackageName);
12313            }
12314            scheduleWriteSettingsLocked();
12315        }
12316    }
12317
12318    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12319        // Queue up an async operation since the package installation may take a little while.
12320        mHandler.post(new Runnable() {
12321            public void run() {
12322                mHandler.removeCallbacks(this);
12323                 // Result object to be returned
12324                PackageInstalledInfo res = new PackageInstalledInfo();
12325                res.setReturnCode(currentStatus);
12326                res.uid = -1;
12327                res.pkg = null;
12328                res.removedInfo = null;
12329                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12330                    args.doPreInstall(res.returnCode);
12331                    synchronized (mInstallLock) {
12332                        installPackageTracedLI(args, res);
12333                    }
12334                    args.doPostInstall(res.returnCode, res.uid);
12335                }
12336
12337                // A restore should be performed at this point if (a) the install
12338                // succeeded, (b) the operation is not an update, and (c) the new
12339                // package has not opted out of backup participation.
12340                final boolean update = res.removedInfo != null
12341                        && res.removedInfo.removedPackage != null;
12342                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12343                boolean doRestore = !update
12344                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12345
12346                // Set up the post-install work request bookkeeping.  This will be used
12347                // and cleaned up by the post-install event handling regardless of whether
12348                // there's a restore pass performed.  Token values are >= 1.
12349                int token;
12350                if (mNextInstallToken < 0) mNextInstallToken = 1;
12351                token = mNextInstallToken++;
12352
12353                PostInstallData data = new PostInstallData(args, res);
12354                mRunningInstalls.put(token, data);
12355                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12356
12357                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12358                    // Pass responsibility to the Backup Manager.  It will perform a
12359                    // restore if appropriate, then pass responsibility back to the
12360                    // Package Manager to run the post-install observer callbacks
12361                    // and broadcasts.
12362                    IBackupManager bm = IBackupManager.Stub.asInterface(
12363                            ServiceManager.getService(Context.BACKUP_SERVICE));
12364                    if (bm != null) {
12365                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12366                                + " to BM for possible restore");
12367                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12368                        try {
12369                            // TODO: http://b/22388012
12370                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12371                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12372                            } else {
12373                                doRestore = false;
12374                            }
12375                        } catch (RemoteException e) {
12376                            // can't happen; the backup manager is local
12377                        } catch (Exception e) {
12378                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12379                            doRestore = false;
12380                        }
12381                    } else {
12382                        Slog.e(TAG, "Backup Manager not found!");
12383                        doRestore = false;
12384                    }
12385                }
12386
12387                if (!doRestore) {
12388                    // No restore possible, or the Backup Manager was mysteriously not
12389                    // available -- just fire the post-install work request directly.
12390                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12391
12392                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12393
12394                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12395                    mHandler.sendMessage(msg);
12396                }
12397            }
12398        });
12399    }
12400
12401    /**
12402     * Callback from PackageSettings whenever an app is first transitioned out of the
12403     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12404     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12405     * here whether the app is the target of an ongoing install, and only send the
12406     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12407     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12408     * handling.
12409     */
12410    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12411        // Serialize this with the rest of the install-process message chain.  In the
12412        // restore-at-install case, this Runnable will necessarily run before the
12413        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12414        // are coherent.  In the non-restore case, the app has already completed install
12415        // and been launched through some other means, so it is not in a problematic
12416        // state for observers to see the FIRST_LAUNCH signal.
12417        mHandler.post(new Runnable() {
12418            @Override
12419            public void run() {
12420                for (int i = 0; i < mRunningInstalls.size(); i++) {
12421                    final PostInstallData data = mRunningInstalls.valueAt(i);
12422                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12423                        continue;
12424                    }
12425                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12426                        // right package; but is it for the right user?
12427                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12428                            if (userId == data.res.newUsers[uIndex]) {
12429                                if (DEBUG_BACKUP) {
12430                                    Slog.i(TAG, "Package " + pkgName
12431                                            + " being restored so deferring FIRST_LAUNCH");
12432                                }
12433                                return;
12434                            }
12435                        }
12436                    }
12437                }
12438                // didn't find it, so not being restored
12439                if (DEBUG_BACKUP) {
12440                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12441                }
12442                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12443            }
12444        });
12445    }
12446
12447    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12448        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12449                installerPkg, null, userIds);
12450    }
12451
12452    private abstract class HandlerParams {
12453        private static final int MAX_RETRIES = 4;
12454
12455        /**
12456         * Number of times startCopy() has been attempted and had a non-fatal
12457         * error.
12458         */
12459        private int mRetries = 0;
12460
12461        /** User handle for the user requesting the information or installation. */
12462        private final UserHandle mUser;
12463        String traceMethod;
12464        int traceCookie;
12465
12466        HandlerParams(UserHandle user) {
12467            mUser = user;
12468        }
12469
12470        UserHandle getUser() {
12471            return mUser;
12472        }
12473
12474        HandlerParams setTraceMethod(String traceMethod) {
12475            this.traceMethod = traceMethod;
12476            return this;
12477        }
12478
12479        HandlerParams setTraceCookie(int traceCookie) {
12480            this.traceCookie = traceCookie;
12481            return this;
12482        }
12483
12484        final boolean startCopy() {
12485            boolean res;
12486            try {
12487                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12488
12489                if (++mRetries > MAX_RETRIES) {
12490                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12491                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12492                    handleServiceError();
12493                    return false;
12494                } else {
12495                    handleStartCopy();
12496                    res = true;
12497                }
12498            } catch (RemoteException e) {
12499                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12500                mHandler.sendEmptyMessage(MCS_RECONNECT);
12501                res = false;
12502            }
12503            handleReturnCode();
12504            return res;
12505        }
12506
12507        final void serviceError() {
12508            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12509            handleServiceError();
12510            handleReturnCode();
12511        }
12512
12513        abstract void handleStartCopy() throws RemoteException;
12514        abstract void handleServiceError();
12515        abstract void handleReturnCode();
12516    }
12517
12518    class MeasureParams extends HandlerParams {
12519        private final PackageStats mStats;
12520        private boolean mSuccess;
12521
12522        private final IPackageStatsObserver mObserver;
12523
12524        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12525            super(new UserHandle(stats.userHandle));
12526            mObserver = observer;
12527            mStats = stats;
12528        }
12529
12530        @Override
12531        public String toString() {
12532            return "MeasureParams{"
12533                + Integer.toHexString(System.identityHashCode(this))
12534                + " " + mStats.packageName + "}";
12535        }
12536
12537        @Override
12538        void handleStartCopy() throws RemoteException {
12539            synchronized (mInstallLock) {
12540                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12541            }
12542
12543            if (mSuccess) {
12544                boolean mounted = false;
12545                try {
12546                    final String status = Environment.getExternalStorageState();
12547                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12548                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12549                } catch (Exception e) {
12550                }
12551
12552                if (mounted) {
12553                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12554
12555                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12556                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12557
12558                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12559                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12560
12561                    // Always subtract cache size, since it's a subdirectory
12562                    mStats.externalDataSize -= mStats.externalCacheSize;
12563
12564                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12565                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12566
12567                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12568                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12569                }
12570            }
12571        }
12572
12573        @Override
12574        void handleReturnCode() {
12575            if (mObserver != null) {
12576                try {
12577                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12578                } catch (RemoteException e) {
12579                    Slog.i(TAG, "Observer no longer exists.");
12580                }
12581            }
12582        }
12583
12584        @Override
12585        void handleServiceError() {
12586            Slog.e(TAG, "Could not measure application " + mStats.packageName
12587                            + " external storage");
12588        }
12589    }
12590
12591    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12592            throws RemoteException {
12593        long result = 0;
12594        for (File path : paths) {
12595            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12596        }
12597        return result;
12598    }
12599
12600    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12601        for (File path : paths) {
12602            try {
12603                mcs.clearDirectory(path.getAbsolutePath());
12604            } catch (RemoteException e) {
12605            }
12606        }
12607    }
12608
12609    static class OriginInfo {
12610        /**
12611         * Location where install is coming from, before it has been
12612         * copied/renamed into place. This could be a single monolithic APK
12613         * file, or a cluster directory. This location may be untrusted.
12614         */
12615        final File file;
12616        final String cid;
12617
12618        /**
12619         * Flag indicating that {@link #file} or {@link #cid} has already been
12620         * staged, meaning downstream users don't need to defensively copy the
12621         * contents.
12622         */
12623        final boolean staged;
12624
12625        /**
12626         * Flag indicating that {@link #file} or {@link #cid} is an already
12627         * installed app that is being moved.
12628         */
12629        final boolean existing;
12630
12631        final String resolvedPath;
12632        final File resolvedFile;
12633
12634        static OriginInfo fromNothing() {
12635            return new OriginInfo(null, null, false, false);
12636        }
12637
12638        static OriginInfo fromUntrustedFile(File file) {
12639            return new OriginInfo(file, null, false, false);
12640        }
12641
12642        static OriginInfo fromExistingFile(File file) {
12643            return new OriginInfo(file, null, false, true);
12644        }
12645
12646        static OriginInfo fromStagedFile(File file) {
12647            return new OriginInfo(file, null, true, false);
12648        }
12649
12650        static OriginInfo fromStagedContainer(String cid) {
12651            return new OriginInfo(null, cid, true, false);
12652        }
12653
12654        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12655            this.file = file;
12656            this.cid = cid;
12657            this.staged = staged;
12658            this.existing = existing;
12659
12660            if (cid != null) {
12661                resolvedPath = PackageHelper.getSdDir(cid);
12662                resolvedFile = new File(resolvedPath);
12663            } else if (file != null) {
12664                resolvedPath = file.getAbsolutePath();
12665                resolvedFile = file;
12666            } else {
12667                resolvedPath = null;
12668                resolvedFile = null;
12669            }
12670        }
12671    }
12672
12673    static class MoveInfo {
12674        final int moveId;
12675        final String fromUuid;
12676        final String toUuid;
12677        final String packageName;
12678        final String dataAppName;
12679        final int appId;
12680        final String seinfo;
12681        final int targetSdkVersion;
12682
12683        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12684                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12685            this.moveId = moveId;
12686            this.fromUuid = fromUuid;
12687            this.toUuid = toUuid;
12688            this.packageName = packageName;
12689            this.dataAppName = dataAppName;
12690            this.appId = appId;
12691            this.seinfo = seinfo;
12692            this.targetSdkVersion = targetSdkVersion;
12693        }
12694    }
12695
12696    static class VerificationInfo {
12697        /** A constant used to indicate that a uid value is not present. */
12698        public static final int NO_UID = -1;
12699
12700        /** URI referencing where the package was downloaded from. */
12701        final Uri originatingUri;
12702
12703        /** HTTP referrer URI associated with the originatingURI. */
12704        final Uri referrer;
12705
12706        /** UID of the application that the install request originated from. */
12707        final int originatingUid;
12708
12709        /** UID of application requesting the install */
12710        final int installerUid;
12711
12712        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12713            this.originatingUri = originatingUri;
12714            this.referrer = referrer;
12715            this.originatingUid = originatingUid;
12716            this.installerUid = installerUid;
12717        }
12718    }
12719
12720    class InstallParams extends HandlerParams {
12721        final OriginInfo origin;
12722        final MoveInfo move;
12723        final IPackageInstallObserver2 observer;
12724        int installFlags;
12725        final String installerPackageName;
12726        final String volumeUuid;
12727        private InstallArgs mArgs;
12728        private int mRet;
12729        final String packageAbiOverride;
12730        final String[] grantedRuntimePermissions;
12731        final VerificationInfo verificationInfo;
12732        final Certificate[][] certificates;
12733
12734        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12735                int installFlags, String installerPackageName, String volumeUuid,
12736                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12737                String[] grantedPermissions, Certificate[][] certificates) {
12738            super(user);
12739            this.origin = origin;
12740            this.move = move;
12741            this.observer = observer;
12742            this.installFlags = installFlags;
12743            this.installerPackageName = installerPackageName;
12744            this.volumeUuid = volumeUuid;
12745            this.verificationInfo = verificationInfo;
12746            this.packageAbiOverride = packageAbiOverride;
12747            this.grantedRuntimePermissions = grantedPermissions;
12748            this.certificates = certificates;
12749        }
12750
12751        @Override
12752        public String toString() {
12753            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12754                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12755        }
12756
12757        private int installLocationPolicy(PackageInfoLite pkgLite) {
12758            String packageName = pkgLite.packageName;
12759            int installLocation = pkgLite.installLocation;
12760            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12761            // reader
12762            synchronized (mPackages) {
12763                // Currently installed package which the new package is attempting to replace or
12764                // null if no such package is installed.
12765                PackageParser.Package installedPkg = mPackages.get(packageName);
12766                // Package which currently owns the data which the new package will own if installed.
12767                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12768                // will be null whereas dataOwnerPkg will contain information about the package
12769                // which was uninstalled while keeping its data.
12770                PackageParser.Package dataOwnerPkg = installedPkg;
12771                if (dataOwnerPkg  == null) {
12772                    PackageSetting ps = mSettings.mPackages.get(packageName);
12773                    if (ps != null) {
12774                        dataOwnerPkg = ps.pkg;
12775                    }
12776                }
12777
12778                if (dataOwnerPkg != null) {
12779                    // If installed, the package will get access to data left on the device by its
12780                    // predecessor. As a security measure, this is permited only if this is not a
12781                    // version downgrade or if the predecessor package is marked as debuggable and
12782                    // a downgrade is explicitly requested.
12783                    //
12784                    // On debuggable platform builds, downgrades are permitted even for
12785                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12786                    // not offer security guarantees and thus it's OK to disable some security
12787                    // mechanisms to make debugging/testing easier on those builds. However, even on
12788                    // debuggable builds downgrades of packages are permitted only if requested via
12789                    // installFlags. This is because we aim to keep the behavior of debuggable
12790                    // platform builds as close as possible to the behavior of non-debuggable
12791                    // platform builds.
12792                    final boolean downgradeRequested =
12793                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12794                    final boolean packageDebuggable =
12795                                (dataOwnerPkg.applicationInfo.flags
12796                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12797                    final boolean downgradePermitted =
12798                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12799                    if (!downgradePermitted) {
12800                        try {
12801                            checkDowngrade(dataOwnerPkg, pkgLite);
12802                        } catch (PackageManagerException e) {
12803                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12804                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12805                        }
12806                    }
12807                }
12808
12809                if (installedPkg != null) {
12810                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12811                        // Check for updated system application.
12812                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12813                            if (onSd) {
12814                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12815                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12816                            }
12817                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12818                        } else {
12819                            if (onSd) {
12820                                // Install flag overrides everything.
12821                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12822                            }
12823                            // If current upgrade specifies particular preference
12824                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12825                                // Application explicitly specified internal.
12826                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12827                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12828                                // App explictly prefers external. Let policy decide
12829                            } else {
12830                                // Prefer previous location
12831                                if (isExternal(installedPkg)) {
12832                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12833                                }
12834                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12835                            }
12836                        }
12837                    } else {
12838                        // Invalid install. Return error code
12839                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12840                    }
12841                }
12842            }
12843            // All the special cases have been taken care of.
12844            // Return result based on recommended install location.
12845            if (onSd) {
12846                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12847            }
12848            return pkgLite.recommendedInstallLocation;
12849        }
12850
12851        /*
12852         * Invoke remote method to get package information and install
12853         * location values. Override install location based on default
12854         * policy if needed and then create install arguments based
12855         * on the install location.
12856         */
12857        public void handleStartCopy() throws RemoteException {
12858            int ret = PackageManager.INSTALL_SUCCEEDED;
12859
12860            // If we're already staged, we've firmly committed to an install location
12861            if (origin.staged) {
12862                if (origin.file != null) {
12863                    installFlags |= PackageManager.INSTALL_INTERNAL;
12864                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12865                } else if (origin.cid != null) {
12866                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12867                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12868                } else {
12869                    throw new IllegalStateException("Invalid stage location");
12870                }
12871            }
12872
12873            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12874            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12875            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12876            PackageInfoLite pkgLite = null;
12877
12878            if (onInt && onSd) {
12879                // Check if both bits are set.
12880                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12881                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12882            } else if (onSd && ephemeral) {
12883                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12884                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12885            } else {
12886                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12887                        packageAbiOverride);
12888
12889                if (DEBUG_EPHEMERAL && ephemeral) {
12890                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12891                }
12892
12893                /*
12894                 * If we have too little free space, try to free cache
12895                 * before giving up.
12896                 */
12897                if (!origin.staged && pkgLite.recommendedInstallLocation
12898                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12899                    // TODO: focus freeing disk space on the target device
12900                    final StorageManager storage = StorageManager.from(mContext);
12901                    final long lowThreshold = storage.getStorageLowBytes(
12902                            Environment.getDataDirectory());
12903
12904                    final long sizeBytes = mContainerService.calculateInstalledSize(
12905                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12906
12907                    try {
12908                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12909                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12910                                installFlags, packageAbiOverride);
12911                    } catch (InstallerException e) {
12912                        Slog.w(TAG, "Failed to free cache", e);
12913                    }
12914
12915                    /*
12916                     * The cache free must have deleted the file we
12917                     * downloaded to install.
12918                     *
12919                     * TODO: fix the "freeCache" call to not delete
12920                     *       the file we care about.
12921                     */
12922                    if (pkgLite.recommendedInstallLocation
12923                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12924                        pkgLite.recommendedInstallLocation
12925                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12926                    }
12927                }
12928            }
12929
12930            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12931                int loc = pkgLite.recommendedInstallLocation;
12932                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12933                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12934                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12935                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12936                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12937                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12938                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12939                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12940                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12941                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12942                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12943                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12944                } else {
12945                    // Override with defaults if needed.
12946                    loc = installLocationPolicy(pkgLite);
12947                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12948                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12949                    } else if (!onSd && !onInt) {
12950                        // Override install location with flags
12951                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12952                            // Set the flag to install on external media.
12953                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12954                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12955                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12956                            if (DEBUG_EPHEMERAL) {
12957                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12958                            }
12959                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12960                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12961                                    |PackageManager.INSTALL_INTERNAL);
12962                        } else {
12963                            // Make sure the flag for installing on external
12964                            // media is unset
12965                            installFlags |= PackageManager.INSTALL_INTERNAL;
12966                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12967                        }
12968                    }
12969                }
12970            }
12971
12972            final InstallArgs args = createInstallArgs(this);
12973            mArgs = args;
12974
12975            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12976                // TODO: http://b/22976637
12977                // Apps installed for "all" users use the device owner to verify the app
12978                UserHandle verifierUser = getUser();
12979                if (verifierUser == UserHandle.ALL) {
12980                    verifierUser = UserHandle.SYSTEM;
12981                }
12982
12983                /*
12984                 * Determine if we have any installed package verifiers. If we
12985                 * do, then we'll defer to them to verify the packages.
12986                 */
12987                final int requiredUid = mRequiredVerifierPackage == null ? -1
12988                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12989                                verifierUser.getIdentifier());
12990                if (!origin.existing && requiredUid != -1
12991                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12992                    final Intent verification = new Intent(
12993                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12994                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12995                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12996                            PACKAGE_MIME_TYPE);
12997                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12998
12999                    // Query all live verifiers based on current user state
13000                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13001                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13002
13003                    if (DEBUG_VERIFY) {
13004                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13005                                + verification.toString() + " with " + pkgLite.verifiers.length
13006                                + " optional verifiers");
13007                    }
13008
13009                    final int verificationId = mPendingVerificationToken++;
13010
13011                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13012
13013                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13014                            installerPackageName);
13015
13016                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13017                            installFlags);
13018
13019                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13020                            pkgLite.packageName);
13021
13022                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13023                            pkgLite.versionCode);
13024
13025                    if (verificationInfo != null) {
13026                        if (verificationInfo.originatingUri != null) {
13027                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13028                                    verificationInfo.originatingUri);
13029                        }
13030                        if (verificationInfo.referrer != null) {
13031                            verification.putExtra(Intent.EXTRA_REFERRER,
13032                                    verificationInfo.referrer);
13033                        }
13034                        if (verificationInfo.originatingUid >= 0) {
13035                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13036                                    verificationInfo.originatingUid);
13037                        }
13038                        if (verificationInfo.installerUid >= 0) {
13039                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13040                                    verificationInfo.installerUid);
13041                        }
13042                    }
13043
13044                    final PackageVerificationState verificationState = new PackageVerificationState(
13045                            requiredUid, args);
13046
13047                    mPendingVerification.append(verificationId, verificationState);
13048
13049                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13050                            receivers, verificationState);
13051
13052                    /*
13053                     * If any sufficient verifiers were listed in the package
13054                     * manifest, attempt to ask them.
13055                     */
13056                    if (sufficientVerifiers != null) {
13057                        final int N = sufficientVerifiers.size();
13058                        if (N == 0) {
13059                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13060                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13061                        } else {
13062                            for (int i = 0; i < N; i++) {
13063                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13064
13065                                final Intent sufficientIntent = new Intent(verification);
13066                                sufficientIntent.setComponent(verifierComponent);
13067                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13068                            }
13069                        }
13070                    }
13071
13072                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13073                            mRequiredVerifierPackage, receivers);
13074                    if (ret == PackageManager.INSTALL_SUCCEEDED
13075                            && mRequiredVerifierPackage != null) {
13076                        Trace.asyncTraceBegin(
13077                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13078                        /*
13079                         * Send the intent to the required verification agent,
13080                         * but only start the verification timeout after the
13081                         * target BroadcastReceivers have run.
13082                         */
13083                        verification.setComponent(requiredVerifierComponent);
13084                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13085                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13086                                new BroadcastReceiver() {
13087                                    @Override
13088                                    public void onReceive(Context context, Intent intent) {
13089                                        final Message msg = mHandler
13090                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13091                                        msg.arg1 = verificationId;
13092                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13093                                    }
13094                                }, null, 0, null, null);
13095
13096                        /*
13097                         * We don't want the copy to proceed until verification
13098                         * succeeds, so null out this field.
13099                         */
13100                        mArgs = null;
13101                    }
13102                } else {
13103                    /*
13104                     * No package verification is enabled, so immediately start
13105                     * the remote call to initiate copy using temporary file.
13106                     */
13107                    ret = args.copyApk(mContainerService, true);
13108                }
13109            }
13110
13111            mRet = ret;
13112        }
13113
13114        @Override
13115        void handleReturnCode() {
13116            // If mArgs is null, then MCS couldn't be reached. When it
13117            // reconnects, it will try again to install. At that point, this
13118            // will succeed.
13119            if (mArgs != null) {
13120                processPendingInstall(mArgs, mRet);
13121            }
13122        }
13123
13124        @Override
13125        void handleServiceError() {
13126            mArgs = createInstallArgs(this);
13127            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13128        }
13129
13130        public boolean isForwardLocked() {
13131            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13132        }
13133    }
13134
13135    /**
13136     * Used during creation of InstallArgs
13137     *
13138     * @param installFlags package installation flags
13139     * @return true if should be installed on external storage
13140     */
13141    private static boolean installOnExternalAsec(int installFlags) {
13142        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13143            return false;
13144        }
13145        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13146            return true;
13147        }
13148        return false;
13149    }
13150
13151    /**
13152     * Used during creation of InstallArgs
13153     *
13154     * @param installFlags package installation flags
13155     * @return true if should be installed as forward locked
13156     */
13157    private static boolean installForwardLocked(int installFlags) {
13158        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13159    }
13160
13161    private InstallArgs createInstallArgs(InstallParams params) {
13162        if (params.move != null) {
13163            return new MoveInstallArgs(params);
13164        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13165            return new AsecInstallArgs(params);
13166        } else {
13167            return new FileInstallArgs(params);
13168        }
13169    }
13170
13171    /**
13172     * Create args that describe an existing installed package. Typically used
13173     * when cleaning up old installs, or used as a move source.
13174     */
13175    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13176            String resourcePath, String[] instructionSets) {
13177        final boolean isInAsec;
13178        if (installOnExternalAsec(installFlags)) {
13179            /* Apps on SD card are always in ASEC containers. */
13180            isInAsec = true;
13181        } else if (installForwardLocked(installFlags)
13182                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13183            /*
13184             * Forward-locked apps are only in ASEC containers if they're the
13185             * new style
13186             */
13187            isInAsec = true;
13188        } else {
13189            isInAsec = false;
13190        }
13191
13192        if (isInAsec) {
13193            return new AsecInstallArgs(codePath, instructionSets,
13194                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13195        } else {
13196            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13197        }
13198    }
13199
13200    static abstract class InstallArgs {
13201        /** @see InstallParams#origin */
13202        final OriginInfo origin;
13203        /** @see InstallParams#move */
13204        final MoveInfo move;
13205
13206        final IPackageInstallObserver2 observer;
13207        // Always refers to PackageManager flags only
13208        final int installFlags;
13209        final String installerPackageName;
13210        final String volumeUuid;
13211        final UserHandle user;
13212        final String abiOverride;
13213        final String[] installGrantPermissions;
13214        /** If non-null, drop an async trace when the install completes */
13215        final String traceMethod;
13216        final int traceCookie;
13217        final Certificate[][] certificates;
13218
13219        // The list of instruction sets supported by this app. This is currently
13220        // only used during the rmdex() phase to clean up resources. We can get rid of this
13221        // if we move dex files under the common app path.
13222        /* nullable */ String[] instructionSets;
13223
13224        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13225                int installFlags, String installerPackageName, String volumeUuid,
13226                UserHandle user, String[] instructionSets,
13227                String abiOverride, String[] installGrantPermissions,
13228                String traceMethod, int traceCookie, Certificate[][] certificates) {
13229            this.origin = origin;
13230            this.move = move;
13231            this.installFlags = installFlags;
13232            this.observer = observer;
13233            this.installerPackageName = installerPackageName;
13234            this.volumeUuid = volumeUuid;
13235            this.user = user;
13236            this.instructionSets = instructionSets;
13237            this.abiOverride = abiOverride;
13238            this.installGrantPermissions = installGrantPermissions;
13239            this.traceMethod = traceMethod;
13240            this.traceCookie = traceCookie;
13241            this.certificates = certificates;
13242        }
13243
13244        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13245        abstract int doPreInstall(int status);
13246
13247        /**
13248         * Rename package into final resting place. All paths on the given
13249         * scanned package should be updated to reflect the rename.
13250         */
13251        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13252        abstract int doPostInstall(int status, int uid);
13253
13254        /** @see PackageSettingBase#codePathString */
13255        abstract String getCodePath();
13256        /** @see PackageSettingBase#resourcePathString */
13257        abstract String getResourcePath();
13258
13259        // Need installer lock especially for dex file removal.
13260        abstract void cleanUpResourcesLI();
13261        abstract boolean doPostDeleteLI(boolean delete);
13262
13263        /**
13264         * Called before the source arguments are copied. This is used mostly
13265         * for MoveParams when it needs to read the source file to put it in the
13266         * destination.
13267         */
13268        int doPreCopy() {
13269            return PackageManager.INSTALL_SUCCEEDED;
13270        }
13271
13272        /**
13273         * Called after the source arguments are copied. This is used mostly for
13274         * MoveParams when it needs to read the source file to put it in the
13275         * destination.
13276         */
13277        int doPostCopy(int uid) {
13278            return PackageManager.INSTALL_SUCCEEDED;
13279        }
13280
13281        protected boolean isFwdLocked() {
13282            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13283        }
13284
13285        protected boolean isExternalAsec() {
13286            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13287        }
13288
13289        protected boolean isEphemeral() {
13290            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13291        }
13292
13293        UserHandle getUser() {
13294            return user;
13295        }
13296    }
13297
13298    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13299        if (!allCodePaths.isEmpty()) {
13300            if (instructionSets == null) {
13301                throw new IllegalStateException("instructionSet == null");
13302            }
13303            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13304            for (String codePath : allCodePaths) {
13305                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13306                    try {
13307                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13308                    } catch (InstallerException ignored) {
13309                    }
13310                }
13311            }
13312        }
13313    }
13314
13315    /**
13316     * Logic to handle installation of non-ASEC applications, including copying
13317     * and renaming logic.
13318     */
13319    class FileInstallArgs extends InstallArgs {
13320        private File codeFile;
13321        private File resourceFile;
13322
13323        // Example topology:
13324        // /data/app/com.example/base.apk
13325        // /data/app/com.example/split_foo.apk
13326        // /data/app/com.example/lib/arm/libfoo.so
13327        // /data/app/com.example/lib/arm64/libfoo.so
13328        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13329
13330        /** New install */
13331        FileInstallArgs(InstallParams params) {
13332            super(params.origin, params.move, params.observer, params.installFlags,
13333                    params.installerPackageName, params.volumeUuid,
13334                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13335                    params.grantedRuntimePermissions,
13336                    params.traceMethod, params.traceCookie, params.certificates);
13337            if (isFwdLocked()) {
13338                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13339            }
13340        }
13341
13342        /** Existing install */
13343        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13344            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13345                    null, null, null, 0, null /*certificates*/);
13346            this.codeFile = (codePath != null) ? new File(codePath) : null;
13347            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13348        }
13349
13350        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13351            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13352            try {
13353                return doCopyApk(imcs, temp);
13354            } finally {
13355                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13356            }
13357        }
13358
13359        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13360            if (origin.staged) {
13361                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13362                codeFile = origin.file;
13363                resourceFile = origin.file;
13364                return PackageManager.INSTALL_SUCCEEDED;
13365            }
13366
13367            try {
13368                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13369                final File tempDir =
13370                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13371                codeFile = tempDir;
13372                resourceFile = tempDir;
13373            } catch (IOException e) {
13374                Slog.w(TAG, "Failed to create copy file: " + e);
13375                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13376            }
13377
13378            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13379                @Override
13380                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13381                    if (!FileUtils.isValidExtFilename(name)) {
13382                        throw new IllegalArgumentException("Invalid filename: " + name);
13383                    }
13384                    try {
13385                        final File file = new File(codeFile, name);
13386                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13387                                O_RDWR | O_CREAT, 0644);
13388                        Os.chmod(file.getAbsolutePath(), 0644);
13389                        return new ParcelFileDescriptor(fd);
13390                    } catch (ErrnoException e) {
13391                        throw new RemoteException("Failed to open: " + e.getMessage());
13392                    }
13393                }
13394            };
13395
13396            int ret = PackageManager.INSTALL_SUCCEEDED;
13397            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13398            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13399                Slog.e(TAG, "Failed to copy package");
13400                return ret;
13401            }
13402
13403            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13404            NativeLibraryHelper.Handle handle = null;
13405            try {
13406                handle = NativeLibraryHelper.Handle.create(codeFile);
13407                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13408                        abiOverride);
13409            } catch (IOException e) {
13410                Slog.e(TAG, "Copying native libraries failed", e);
13411                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13412            } finally {
13413                IoUtils.closeQuietly(handle);
13414            }
13415
13416            return ret;
13417        }
13418
13419        int doPreInstall(int status) {
13420            if (status != PackageManager.INSTALL_SUCCEEDED) {
13421                cleanUp();
13422            }
13423            return status;
13424        }
13425
13426        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13427            if (status != PackageManager.INSTALL_SUCCEEDED) {
13428                cleanUp();
13429                return false;
13430            }
13431
13432            final File targetDir = codeFile.getParentFile();
13433            final File beforeCodeFile = codeFile;
13434            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13435
13436            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13437            try {
13438                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13439            } catch (ErrnoException e) {
13440                Slog.w(TAG, "Failed to rename", e);
13441                return false;
13442            }
13443
13444            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13445                Slog.w(TAG, "Failed to restorecon");
13446                return false;
13447            }
13448
13449            // Reflect the rename internally
13450            codeFile = afterCodeFile;
13451            resourceFile = afterCodeFile;
13452
13453            // Reflect the rename in scanned details
13454            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13455            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13456                    afterCodeFile, pkg.baseCodePath));
13457            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13458                    afterCodeFile, pkg.splitCodePaths));
13459
13460            // Reflect the rename in app info
13461            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13462            pkg.setApplicationInfoCodePath(pkg.codePath);
13463            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13464            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13465            pkg.setApplicationInfoResourcePath(pkg.codePath);
13466            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13467            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13468
13469            return true;
13470        }
13471
13472        int doPostInstall(int status, int uid) {
13473            if (status != PackageManager.INSTALL_SUCCEEDED) {
13474                cleanUp();
13475            }
13476            return status;
13477        }
13478
13479        @Override
13480        String getCodePath() {
13481            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13482        }
13483
13484        @Override
13485        String getResourcePath() {
13486            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13487        }
13488
13489        private boolean cleanUp() {
13490            if (codeFile == null || !codeFile.exists()) {
13491                return false;
13492            }
13493
13494            removeCodePathLI(codeFile);
13495
13496            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13497                resourceFile.delete();
13498            }
13499
13500            return true;
13501        }
13502
13503        void cleanUpResourcesLI() {
13504            // Try enumerating all code paths before deleting
13505            List<String> allCodePaths = Collections.EMPTY_LIST;
13506            if (codeFile != null && codeFile.exists()) {
13507                try {
13508                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13509                    allCodePaths = pkg.getAllCodePaths();
13510                } catch (PackageParserException e) {
13511                    // Ignored; we tried our best
13512                }
13513            }
13514
13515            cleanUp();
13516            removeDexFiles(allCodePaths, instructionSets);
13517        }
13518
13519        boolean doPostDeleteLI(boolean delete) {
13520            // XXX err, shouldn't we respect the delete flag?
13521            cleanUpResourcesLI();
13522            return true;
13523        }
13524    }
13525
13526    private boolean isAsecExternal(String cid) {
13527        final String asecPath = PackageHelper.getSdFilesystem(cid);
13528        return !asecPath.startsWith(mAsecInternalPath);
13529    }
13530
13531    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13532            PackageManagerException {
13533        if (copyRet < 0) {
13534            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13535                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13536                throw new PackageManagerException(copyRet, message);
13537            }
13538        }
13539    }
13540
13541    /**
13542     * Extract the MountService "container ID" from the full code path of an
13543     * .apk.
13544     */
13545    static String cidFromCodePath(String fullCodePath) {
13546        int eidx = fullCodePath.lastIndexOf("/");
13547        String subStr1 = fullCodePath.substring(0, eidx);
13548        int sidx = subStr1.lastIndexOf("/");
13549        return subStr1.substring(sidx+1, eidx);
13550    }
13551
13552    /**
13553     * Logic to handle installation of ASEC applications, including copying and
13554     * renaming logic.
13555     */
13556    class AsecInstallArgs extends InstallArgs {
13557        static final String RES_FILE_NAME = "pkg.apk";
13558        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13559
13560        String cid;
13561        String packagePath;
13562        String resourcePath;
13563
13564        /** New install */
13565        AsecInstallArgs(InstallParams params) {
13566            super(params.origin, params.move, params.observer, params.installFlags,
13567                    params.installerPackageName, params.volumeUuid,
13568                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13569                    params.grantedRuntimePermissions,
13570                    params.traceMethod, params.traceCookie, params.certificates);
13571        }
13572
13573        /** Existing install */
13574        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13575                        boolean isExternal, boolean isForwardLocked) {
13576            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13577              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13578                    instructionSets, null, null, null, 0, null /*certificates*/);
13579            // Hackily pretend we're still looking at a full code path
13580            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13581                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13582            }
13583
13584            // Extract cid from fullCodePath
13585            int eidx = fullCodePath.lastIndexOf("/");
13586            String subStr1 = fullCodePath.substring(0, eidx);
13587            int sidx = subStr1.lastIndexOf("/");
13588            cid = subStr1.substring(sidx+1, eidx);
13589            setMountPath(subStr1);
13590        }
13591
13592        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13593            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13594              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13595                    instructionSets, null, null, null, 0, null /*certificates*/);
13596            this.cid = cid;
13597            setMountPath(PackageHelper.getSdDir(cid));
13598        }
13599
13600        void createCopyFile() {
13601            cid = mInstallerService.allocateExternalStageCidLegacy();
13602        }
13603
13604        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13605            if (origin.staged && origin.cid != null) {
13606                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13607                cid = origin.cid;
13608                setMountPath(PackageHelper.getSdDir(cid));
13609                return PackageManager.INSTALL_SUCCEEDED;
13610            }
13611
13612            if (temp) {
13613                createCopyFile();
13614            } else {
13615                /*
13616                 * Pre-emptively destroy the container since it's destroyed if
13617                 * copying fails due to it existing anyway.
13618                 */
13619                PackageHelper.destroySdDir(cid);
13620            }
13621
13622            final String newMountPath = imcs.copyPackageToContainer(
13623                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13624                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13625
13626            if (newMountPath != null) {
13627                setMountPath(newMountPath);
13628                return PackageManager.INSTALL_SUCCEEDED;
13629            } else {
13630                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13631            }
13632        }
13633
13634        @Override
13635        String getCodePath() {
13636            return packagePath;
13637        }
13638
13639        @Override
13640        String getResourcePath() {
13641            return resourcePath;
13642        }
13643
13644        int doPreInstall(int status) {
13645            if (status != PackageManager.INSTALL_SUCCEEDED) {
13646                // Destroy container
13647                PackageHelper.destroySdDir(cid);
13648            } else {
13649                boolean mounted = PackageHelper.isContainerMounted(cid);
13650                if (!mounted) {
13651                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13652                            Process.SYSTEM_UID);
13653                    if (newMountPath != null) {
13654                        setMountPath(newMountPath);
13655                    } else {
13656                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13657                    }
13658                }
13659            }
13660            return status;
13661        }
13662
13663        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13664            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13665            String newMountPath = null;
13666            if (PackageHelper.isContainerMounted(cid)) {
13667                // Unmount the container
13668                if (!PackageHelper.unMountSdDir(cid)) {
13669                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13670                    return false;
13671                }
13672            }
13673            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13674                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13675                        " which might be stale. Will try to clean up.");
13676                // Clean up the stale container and proceed to recreate.
13677                if (!PackageHelper.destroySdDir(newCacheId)) {
13678                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13679                    return false;
13680                }
13681                // Successfully cleaned up stale container. Try to rename again.
13682                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13683                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13684                            + " inspite of cleaning it up.");
13685                    return false;
13686                }
13687            }
13688            if (!PackageHelper.isContainerMounted(newCacheId)) {
13689                Slog.w(TAG, "Mounting container " + newCacheId);
13690                newMountPath = PackageHelper.mountSdDir(newCacheId,
13691                        getEncryptKey(), Process.SYSTEM_UID);
13692            } else {
13693                newMountPath = PackageHelper.getSdDir(newCacheId);
13694            }
13695            if (newMountPath == null) {
13696                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13697                return false;
13698            }
13699            Log.i(TAG, "Succesfully renamed " + cid +
13700                    " to " + newCacheId +
13701                    " at new path: " + newMountPath);
13702            cid = newCacheId;
13703
13704            final File beforeCodeFile = new File(packagePath);
13705            setMountPath(newMountPath);
13706            final File afterCodeFile = new File(packagePath);
13707
13708            // Reflect the rename in scanned details
13709            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13710            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13711                    afterCodeFile, pkg.baseCodePath));
13712            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13713                    afterCodeFile, pkg.splitCodePaths));
13714
13715            // Reflect the rename in app info
13716            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13717            pkg.setApplicationInfoCodePath(pkg.codePath);
13718            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13719            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13720            pkg.setApplicationInfoResourcePath(pkg.codePath);
13721            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13722            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13723
13724            return true;
13725        }
13726
13727        private void setMountPath(String mountPath) {
13728            final File mountFile = new File(mountPath);
13729
13730            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13731            if (monolithicFile.exists()) {
13732                packagePath = monolithicFile.getAbsolutePath();
13733                if (isFwdLocked()) {
13734                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13735                } else {
13736                    resourcePath = packagePath;
13737                }
13738            } else {
13739                packagePath = mountFile.getAbsolutePath();
13740                resourcePath = packagePath;
13741            }
13742        }
13743
13744        int doPostInstall(int status, int uid) {
13745            if (status != PackageManager.INSTALL_SUCCEEDED) {
13746                cleanUp();
13747            } else {
13748                final int groupOwner;
13749                final String protectedFile;
13750                if (isFwdLocked()) {
13751                    groupOwner = UserHandle.getSharedAppGid(uid);
13752                    protectedFile = RES_FILE_NAME;
13753                } else {
13754                    groupOwner = -1;
13755                    protectedFile = null;
13756                }
13757
13758                if (uid < Process.FIRST_APPLICATION_UID
13759                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13760                    Slog.e(TAG, "Failed to finalize " + cid);
13761                    PackageHelper.destroySdDir(cid);
13762                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13763                }
13764
13765                boolean mounted = PackageHelper.isContainerMounted(cid);
13766                if (!mounted) {
13767                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13768                }
13769            }
13770            return status;
13771        }
13772
13773        private void cleanUp() {
13774            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13775
13776            // Destroy secure container
13777            PackageHelper.destroySdDir(cid);
13778        }
13779
13780        private List<String> getAllCodePaths() {
13781            final File codeFile = new File(getCodePath());
13782            if (codeFile != null && codeFile.exists()) {
13783                try {
13784                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13785                    return pkg.getAllCodePaths();
13786                } catch (PackageParserException e) {
13787                    // Ignored; we tried our best
13788                }
13789            }
13790            return Collections.EMPTY_LIST;
13791        }
13792
13793        void cleanUpResourcesLI() {
13794            // Enumerate all code paths before deleting
13795            cleanUpResourcesLI(getAllCodePaths());
13796        }
13797
13798        private void cleanUpResourcesLI(List<String> allCodePaths) {
13799            cleanUp();
13800            removeDexFiles(allCodePaths, instructionSets);
13801        }
13802
13803        String getPackageName() {
13804            return getAsecPackageName(cid);
13805        }
13806
13807        boolean doPostDeleteLI(boolean delete) {
13808            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13809            final List<String> allCodePaths = getAllCodePaths();
13810            boolean mounted = PackageHelper.isContainerMounted(cid);
13811            if (mounted) {
13812                // Unmount first
13813                if (PackageHelper.unMountSdDir(cid)) {
13814                    mounted = false;
13815                }
13816            }
13817            if (!mounted && delete) {
13818                cleanUpResourcesLI(allCodePaths);
13819            }
13820            return !mounted;
13821        }
13822
13823        @Override
13824        int doPreCopy() {
13825            if (isFwdLocked()) {
13826                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13827                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13828                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13829                }
13830            }
13831
13832            return PackageManager.INSTALL_SUCCEEDED;
13833        }
13834
13835        @Override
13836        int doPostCopy(int uid) {
13837            if (isFwdLocked()) {
13838                if (uid < Process.FIRST_APPLICATION_UID
13839                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13840                                RES_FILE_NAME)) {
13841                    Slog.e(TAG, "Failed to finalize " + cid);
13842                    PackageHelper.destroySdDir(cid);
13843                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13844                }
13845            }
13846
13847            return PackageManager.INSTALL_SUCCEEDED;
13848        }
13849    }
13850
13851    /**
13852     * Logic to handle movement of existing installed applications.
13853     */
13854    class MoveInstallArgs extends InstallArgs {
13855        private File codeFile;
13856        private File resourceFile;
13857
13858        /** New install */
13859        MoveInstallArgs(InstallParams params) {
13860            super(params.origin, params.move, params.observer, params.installFlags,
13861                    params.installerPackageName, params.volumeUuid,
13862                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13863                    params.grantedRuntimePermissions,
13864                    params.traceMethod, params.traceCookie, params.certificates);
13865        }
13866
13867        int copyApk(IMediaContainerService imcs, boolean temp) {
13868            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13869                    + move.fromUuid + " to " + move.toUuid);
13870            synchronized (mInstaller) {
13871                try {
13872                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13873                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13874                } catch (InstallerException e) {
13875                    Slog.w(TAG, "Failed to move app", e);
13876                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13877                }
13878            }
13879
13880            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13881            resourceFile = codeFile;
13882            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13883
13884            return PackageManager.INSTALL_SUCCEEDED;
13885        }
13886
13887        int doPreInstall(int status) {
13888            if (status != PackageManager.INSTALL_SUCCEEDED) {
13889                cleanUp(move.toUuid);
13890            }
13891            return status;
13892        }
13893
13894        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13895            if (status != PackageManager.INSTALL_SUCCEEDED) {
13896                cleanUp(move.toUuid);
13897                return false;
13898            }
13899
13900            // Reflect the move in app info
13901            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13902            pkg.setApplicationInfoCodePath(pkg.codePath);
13903            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13904            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13905            pkg.setApplicationInfoResourcePath(pkg.codePath);
13906            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13907            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13908
13909            return true;
13910        }
13911
13912        int doPostInstall(int status, int uid) {
13913            if (status == PackageManager.INSTALL_SUCCEEDED) {
13914                cleanUp(move.fromUuid);
13915            } else {
13916                cleanUp(move.toUuid);
13917            }
13918            return status;
13919        }
13920
13921        @Override
13922        String getCodePath() {
13923            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13924        }
13925
13926        @Override
13927        String getResourcePath() {
13928            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13929        }
13930
13931        private boolean cleanUp(String volumeUuid) {
13932            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13933                    move.dataAppName);
13934            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13935            final int[] userIds = sUserManager.getUserIds();
13936            synchronized (mInstallLock) {
13937                // Clean up both app data and code
13938                // All package moves are frozen until finished
13939                for (int userId : userIds) {
13940                    try {
13941                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13942                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13943                    } catch (InstallerException e) {
13944                        Slog.w(TAG, String.valueOf(e));
13945                    }
13946                }
13947                removeCodePathLI(codeFile);
13948            }
13949            return true;
13950        }
13951
13952        void cleanUpResourcesLI() {
13953            throw new UnsupportedOperationException();
13954        }
13955
13956        boolean doPostDeleteLI(boolean delete) {
13957            throw new UnsupportedOperationException();
13958        }
13959    }
13960
13961    static String getAsecPackageName(String packageCid) {
13962        int idx = packageCid.lastIndexOf("-");
13963        if (idx == -1) {
13964            return packageCid;
13965        }
13966        return packageCid.substring(0, idx);
13967    }
13968
13969    // Utility method used to create code paths based on package name and available index.
13970    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13971        String idxStr = "";
13972        int idx = 1;
13973        // Fall back to default value of idx=1 if prefix is not
13974        // part of oldCodePath
13975        if (oldCodePath != null) {
13976            String subStr = oldCodePath;
13977            // Drop the suffix right away
13978            if (suffix != null && subStr.endsWith(suffix)) {
13979                subStr = subStr.substring(0, subStr.length() - suffix.length());
13980            }
13981            // If oldCodePath already contains prefix find out the
13982            // ending index to either increment or decrement.
13983            int sidx = subStr.lastIndexOf(prefix);
13984            if (sidx != -1) {
13985                subStr = subStr.substring(sidx + prefix.length());
13986                if (subStr != null) {
13987                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13988                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13989                    }
13990                    try {
13991                        idx = Integer.parseInt(subStr);
13992                        if (idx <= 1) {
13993                            idx++;
13994                        } else {
13995                            idx--;
13996                        }
13997                    } catch(NumberFormatException e) {
13998                    }
13999                }
14000            }
14001        }
14002        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14003        return prefix + idxStr;
14004    }
14005
14006    private File getNextCodePath(File targetDir, String packageName) {
14007        int suffix = 1;
14008        File result;
14009        do {
14010            result = new File(targetDir, packageName + "-" + suffix);
14011            suffix++;
14012        } while (result.exists());
14013        return result;
14014    }
14015
14016    // Utility method that returns the relative package path with respect
14017    // to the installation directory. Like say for /data/data/com.test-1.apk
14018    // string com.test-1 is returned.
14019    static String deriveCodePathName(String codePath) {
14020        if (codePath == null) {
14021            return null;
14022        }
14023        final File codeFile = new File(codePath);
14024        final String name = codeFile.getName();
14025        if (codeFile.isDirectory()) {
14026            return name;
14027        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14028            final int lastDot = name.lastIndexOf('.');
14029            return name.substring(0, lastDot);
14030        } else {
14031            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14032            return null;
14033        }
14034    }
14035
14036    static class PackageInstalledInfo {
14037        String name;
14038        int uid;
14039        // The set of users that originally had this package installed.
14040        int[] origUsers;
14041        // The set of users that now have this package installed.
14042        int[] newUsers;
14043        PackageParser.Package pkg;
14044        int returnCode;
14045        String returnMsg;
14046        PackageRemovedInfo removedInfo;
14047        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14048
14049        public void setError(int code, String msg) {
14050            setReturnCode(code);
14051            setReturnMessage(msg);
14052            Slog.w(TAG, msg);
14053        }
14054
14055        public void setError(String msg, PackageParserException e) {
14056            setReturnCode(e.error);
14057            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14058            Slog.w(TAG, msg, e);
14059        }
14060
14061        public void setError(String msg, PackageManagerException e) {
14062            returnCode = e.error;
14063            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14064            Slog.w(TAG, msg, e);
14065        }
14066
14067        public void setReturnCode(int returnCode) {
14068            this.returnCode = returnCode;
14069            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14070            for (int i = 0; i < childCount; i++) {
14071                addedChildPackages.valueAt(i).returnCode = returnCode;
14072            }
14073        }
14074
14075        private void setReturnMessage(String returnMsg) {
14076            this.returnMsg = returnMsg;
14077            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14078            for (int i = 0; i < childCount; i++) {
14079                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14080            }
14081        }
14082
14083        // In some error cases we want to convey more info back to the observer
14084        String origPackage;
14085        String origPermission;
14086    }
14087
14088    /*
14089     * Install a non-existing package.
14090     */
14091    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14092            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14093            PackageInstalledInfo res) {
14094        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14095
14096        // Remember this for later, in case we need to rollback this install
14097        String pkgName = pkg.packageName;
14098
14099        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14100
14101        synchronized(mPackages) {
14102            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14103                // A package with the same name is already installed, though
14104                // it has been renamed to an older name.  The package we
14105                // are trying to install should be installed as an update to
14106                // the existing one, but that has not been requested, so bail.
14107                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14108                        + " without first uninstalling package running as "
14109                        + mSettings.mRenamedPackages.get(pkgName));
14110                return;
14111            }
14112            if (mPackages.containsKey(pkgName)) {
14113                // Don't allow installation over an existing package with the same name.
14114                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14115                        + " without first uninstalling.");
14116                return;
14117            }
14118        }
14119
14120        try {
14121            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14122                    System.currentTimeMillis(), user);
14123
14124            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14125
14126            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14127                prepareAppDataAfterInstallLIF(newPackage);
14128
14129            } else {
14130                // Remove package from internal structures, but keep around any
14131                // data that might have already existed
14132                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14133                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14134            }
14135        } catch (PackageManagerException e) {
14136            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14137        }
14138
14139        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14140    }
14141
14142    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14143        // Can't rotate keys during boot or if sharedUser.
14144        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14145                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14146            return false;
14147        }
14148        // app is using upgradeKeySets; make sure all are valid
14149        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14150        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14151        for (int i = 0; i < upgradeKeySets.length; i++) {
14152            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14153                Slog.wtf(TAG, "Package "
14154                         + (oldPs.name != null ? oldPs.name : "<null>")
14155                         + " contains upgrade-key-set reference to unknown key-set: "
14156                         + upgradeKeySets[i]
14157                         + " reverting to signatures check.");
14158                return false;
14159            }
14160        }
14161        return true;
14162    }
14163
14164    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14165        // Upgrade keysets are being used.  Determine if new package has a superset of the
14166        // required keys.
14167        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14168        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14169        for (int i = 0; i < upgradeKeySets.length; i++) {
14170            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14171            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14172                return true;
14173            }
14174        }
14175        return false;
14176    }
14177
14178    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14179        try (DigestInputStream digestStream =
14180                new DigestInputStream(new FileInputStream(file), digest)) {
14181            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14182        }
14183    }
14184
14185    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14186            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14187        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14188
14189        final PackageParser.Package oldPackage;
14190        final String pkgName = pkg.packageName;
14191        final int[] allUsers;
14192        final int[] installedUsers;
14193
14194        synchronized(mPackages) {
14195            oldPackage = mPackages.get(pkgName);
14196            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14197
14198            // don't allow upgrade to target a release SDK from a pre-release SDK
14199            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14200                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14201            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14202                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14203            if (oldTargetsPreRelease
14204                    && !newTargetsPreRelease
14205                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14206                Slog.w(TAG, "Can't install package targeting released sdk");
14207                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14208                return;
14209            }
14210
14211            // don't allow an upgrade from full to ephemeral
14212            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14213            if (isEphemeral && !oldIsEphemeral) {
14214                // can't downgrade from full to ephemeral
14215                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14216                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14217                return;
14218            }
14219
14220            // verify signatures are valid
14221            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14222            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14223                if (!checkUpgradeKeySetLP(ps, pkg)) {
14224                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14225                            "New package not signed by keys specified by upgrade-keysets: "
14226                                    + pkgName);
14227                    return;
14228                }
14229            } else {
14230                // default to original signature matching
14231                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14232                        != PackageManager.SIGNATURE_MATCH) {
14233                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14234                            "New package has a different signature: " + pkgName);
14235                    return;
14236                }
14237            }
14238
14239            // don't allow a system upgrade unless the upgrade hash matches
14240            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14241                byte[] digestBytes = null;
14242                try {
14243                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14244                    updateDigest(digest, new File(pkg.baseCodePath));
14245                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14246                        for (String path : pkg.splitCodePaths) {
14247                            updateDigest(digest, new File(path));
14248                        }
14249                    }
14250                    digestBytes = digest.digest();
14251                } catch (NoSuchAlgorithmException | IOException e) {
14252                    res.setError(INSTALL_FAILED_INVALID_APK,
14253                            "Could not compute hash: " + pkgName);
14254                    return;
14255                }
14256                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14257                    res.setError(INSTALL_FAILED_INVALID_APK,
14258                            "New package fails restrict-update check: " + pkgName);
14259                    return;
14260                }
14261                // retain upgrade restriction
14262                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14263            }
14264
14265            // Check for shared user id changes
14266            String invalidPackageName =
14267                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14268            if (invalidPackageName != null) {
14269                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14270                        "Package " + invalidPackageName + " tried to change user "
14271                                + oldPackage.mSharedUserId);
14272                return;
14273            }
14274
14275            // In case of rollback, remember per-user/profile install state
14276            allUsers = sUserManager.getUserIds();
14277            installedUsers = ps.queryInstalledUsers(allUsers, true);
14278        }
14279
14280        // Update what is removed
14281        res.removedInfo = new PackageRemovedInfo();
14282        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14283        res.removedInfo.removedPackage = oldPackage.packageName;
14284        res.removedInfo.isUpdate = true;
14285        res.removedInfo.origUsers = installedUsers;
14286        final int childCount = (oldPackage.childPackages != null)
14287                ? oldPackage.childPackages.size() : 0;
14288        for (int i = 0; i < childCount; i++) {
14289            boolean childPackageUpdated = false;
14290            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14291            if (res.addedChildPackages != null) {
14292                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14293                if (childRes != null) {
14294                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14295                    childRes.removedInfo.removedPackage = childPkg.packageName;
14296                    childRes.removedInfo.isUpdate = true;
14297                    childPackageUpdated = true;
14298                }
14299            }
14300            if (!childPackageUpdated) {
14301                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14302                childRemovedRes.removedPackage = childPkg.packageName;
14303                childRemovedRes.isUpdate = false;
14304                childRemovedRes.dataRemoved = true;
14305                synchronized (mPackages) {
14306                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14307                    if (childPs != null) {
14308                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14309                    }
14310                }
14311                if (res.removedInfo.removedChildPackages == null) {
14312                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14313                }
14314                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14315            }
14316        }
14317
14318        boolean sysPkg = (isSystemApp(oldPackage));
14319        if (sysPkg) {
14320            // Set the system/privileged flags as needed
14321            final boolean privileged =
14322                    (oldPackage.applicationInfo.privateFlags
14323                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14324            final int systemPolicyFlags = policyFlags
14325                    | PackageParser.PARSE_IS_SYSTEM
14326                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14327
14328            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14329                    user, allUsers, installerPackageName, res);
14330        } else {
14331            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14332                    user, allUsers, installerPackageName, res);
14333        }
14334    }
14335
14336    public List<String> getPreviousCodePaths(String packageName) {
14337        final PackageSetting ps = mSettings.mPackages.get(packageName);
14338        final List<String> result = new ArrayList<String>();
14339        if (ps != null && ps.oldCodePaths != null) {
14340            result.addAll(ps.oldCodePaths);
14341        }
14342        return result;
14343    }
14344
14345    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14346            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14347            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14348        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14349                + deletedPackage);
14350
14351        String pkgName = deletedPackage.packageName;
14352        boolean deletedPkg = true;
14353        boolean addedPkg = false;
14354        boolean updatedSettings = false;
14355        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14356        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14357                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14358
14359        final long origUpdateTime = (pkg.mExtras != null)
14360                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14361
14362        // First delete the existing package while retaining the data directory
14363        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14364                res.removedInfo, true, pkg)) {
14365            // If the existing package wasn't successfully deleted
14366            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14367            deletedPkg = false;
14368        } else {
14369            // Successfully deleted the old package; proceed with replace.
14370
14371            // If deleted package lived in a container, give users a chance to
14372            // relinquish resources before killing.
14373            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14374                if (DEBUG_INSTALL) {
14375                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14376                }
14377                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14378                final ArrayList<String> pkgList = new ArrayList<String>(1);
14379                pkgList.add(deletedPackage.applicationInfo.packageName);
14380                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14381            }
14382
14383            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14384                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14385            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14386
14387            try {
14388                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14389                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14390                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14391
14392                // Update the in-memory copy of the previous code paths.
14393                PackageSetting ps = mSettings.mPackages.get(pkgName);
14394                if (!killApp) {
14395                    if (ps.oldCodePaths == null) {
14396                        ps.oldCodePaths = new ArraySet<>();
14397                    }
14398                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14399                    if (deletedPackage.splitCodePaths != null) {
14400                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14401                    }
14402                } else {
14403                    ps.oldCodePaths = null;
14404                }
14405                if (ps.childPackageNames != null) {
14406                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14407                        final String childPkgName = ps.childPackageNames.get(i);
14408                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14409                        childPs.oldCodePaths = ps.oldCodePaths;
14410                    }
14411                }
14412                prepareAppDataAfterInstallLIF(newPackage);
14413                addedPkg = true;
14414            } catch (PackageManagerException e) {
14415                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14416            }
14417        }
14418
14419        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14420            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14421
14422            // Revert all internal state mutations and added folders for the failed install
14423            if (addedPkg) {
14424                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14425                        res.removedInfo, true, null);
14426            }
14427
14428            // Restore the old package
14429            if (deletedPkg) {
14430                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14431                File restoreFile = new File(deletedPackage.codePath);
14432                // Parse old package
14433                boolean oldExternal = isExternal(deletedPackage);
14434                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14435                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14436                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14437                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14438                try {
14439                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14440                            null);
14441                } catch (PackageManagerException e) {
14442                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14443                            + e.getMessage());
14444                    return;
14445                }
14446
14447                synchronized (mPackages) {
14448                    // Ensure the installer package name up to date
14449                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14450
14451                    // Update permissions for restored package
14452                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14453
14454                    mSettings.writeLPr();
14455                }
14456
14457                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14458            }
14459        } else {
14460            synchronized (mPackages) {
14461                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14462                if (ps != null) {
14463                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14464                    if (res.removedInfo.removedChildPackages != null) {
14465                        final int childCount = res.removedInfo.removedChildPackages.size();
14466                        // Iterate in reverse as we may modify the collection
14467                        for (int i = childCount - 1; i >= 0; i--) {
14468                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14469                            if (res.addedChildPackages.containsKey(childPackageName)) {
14470                                res.removedInfo.removedChildPackages.removeAt(i);
14471                            } else {
14472                                PackageRemovedInfo childInfo = res.removedInfo
14473                                        .removedChildPackages.valueAt(i);
14474                                childInfo.removedForAllUsers = mPackages.get(
14475                                        childInfo.removedPackage) == null;
14476                            }
14477                        }
14478                    }
14479                }
14480            }
14481        }
14482    }
14483
14484    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14485            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14486            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14487        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14488                + ", old=" + deletedPackage);
14489
14490        final boolean disabledSystem;
14491
14492        // Remove existing system package
14493        removePackageLI(deletedPackage, true);
14494
14495        synchronized (mPackages) {
14496            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14497        }
14498        if (!disabledSystem) {
14499            // We didn't need to disable the .apk as a current system package,
14500            // which means we are replacing another update that is already
14501            // installed.  We need to make sure to delete the older one's .apk.
14502            res.removedInfo.args = createInstallArgsForExisting(0,
14503                    deletedPackage.applicationInfo.getCodePath(),
14504                    deletedPackage.applicationInfo.getResourcePath(),
14505                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14506        } else {
14507            res.removedInfo.args = null;
14508        }
14509
14510        // Successfully disabled the old package. Now proceed with re-installation
14511        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14512                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14513        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14514
14515        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14516        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14517                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14518
14519        PackageParser.Package newPackage = null;
14520        try {
14521            // Add the package to the internal data structures
14522            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14523
14524            // Set the update and install times
14525            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14526            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14527                    System.currentTimeMillis());
14528
14529            // Update the package dynamic state if succeeded
14530            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14531                // Now that the install succeeded make sure we remove data
14532                // directories for any child package the update removed.
14533                final int deletedChildCount = (deletedPackage.childPackages != null)
14534                        ? deletedPackage.childPackages.size() : 0;
14535                final int newChildCount = (newPackage.childPackages != null)
14536                        ? newPackage.childPackages.size() : 0;
14537                for (int i = 0; i < deletedChildCount; i++) {
14538                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14539                    boolean childPackageDeleted = true;
14540                    for (int j = 0; j < newChildCount; j++) {
14541                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14542                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14543                            childPackageDeleted = false;
14544                            break;
14545                        }
14546                    }
14547                    if (childPackageDeleted) {
14548                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14549                                deletedChildPkg.packageName);
14550                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14551                            PackageRemovedInfo removedChildRes = res.removedInfo
14552                                    .removedChildPackages.get(deletedChildPkg.packageName);
14553                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14554                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14555                        }
14556                    }
14557                }
14558
14559                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14560                prepareAppDataAfterInstallLIF(newPackage);
14561            }
14562        } catch (PackageManagerException e) {
14563            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14564            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14565        }
14566
14567        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14568            // Re installation failed. Restore old information
14569            // Remove new pkg information
14570            if (newPackage != null) {
14571                removeInstalledPackageLI(newPackage, true);
14572            }
14573            // Add back the old system package
14574            try {
14575                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14576            } catch (PackageManagerException e) {
14577                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14578            }
14579
14580            synchronized (mPackages) {
14581                if (disabledSystem) {
14582                    enableSystemPackageLPw(deletedPackage);
14583                }
14584
14585                // Ensure the installer package name up to date
14586                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14587
14588                // Update permissions for restored package
14589                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14590
14591                mSettings.writeLPr();
14592            }
14593
14594            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14595                    + " after failed upgrade");
14596        }
14597    }
14598
14599    /**
14600     * Checks whether the parent or any of the child packages have a change shared
14601     * user. For a package to be a valid update the shred users of the parent and
14602     * the children should match. We may later support changing child shared users.
14603     * @param oldPkg The updated package.
14604     * @param newPkg The update package.
14605     * @return The shared user that change between the versions.
14606     */
14607    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14608            PackageParser.Package newPkg) {
14609        // Check parent shared user
14610        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14611            return newPkg.packageName;
14612        }
14613        // Check child shared users
14614        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14615        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14616        for (int i = 0; i < newChildCount; i++) {
14617            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14618            // If this child was present, did it have the same shared user?
14619            for (int j = 0; j < oldChildCount; j++) {
14620                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14621                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14622                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14623                    return newChildPkg.packageName;
14624                }
14625            }
14626        }
14627        return null;
14628    }
14629
14630    private void removeNativeBinariesLI(PackageSetting ps) {
14631        // Remove the lib path for the parent package
14632        if (ps != null) {
14633            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14634            // Remove the lib path for the child packages
14635            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14636            for (int i = 0; i < childCount; i++) {
14637                PackageSetting childPs = null;
14638                synchronized (mPackages) {
14639                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14640                }
14641                if (childPs != null) {
14642                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14643                            .legacyNativeLibraryPathString);
14644                }
14645            }
14646        }
14647    }
14648
14649    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14650        // Enable the parent package
14651        mSettings.enableSystemPackageLPw(pkg.packageName);
14652        // Enable the child packages
14653        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14654        for (int i = 0; i < childCount; i++) {
14655            PackageParser.Package childPkg = pkg.childPackages.get(i);
14656            mSettings.enableSystemPackageLPw(childPkg.packageName);
14657        }
14658    }
14659
14660    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14661            PackageParser.Package newPkg) {
14662        // Disable the parent package (parent always replaced)
14663        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14664        // Disable the child packages
14665        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14666        for (int i = 0; i < childCount; i++) {
14667            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14668            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14669            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14670        }
14671        return disabled;
14672    }
14673
14674    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14675            String installerPackageName) {
14676        // Enable the parent package
14677        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14678        // Enable the child packages
14679        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14680        for (int i = 0; i < childCount; i++) {
14681            PackageParser.Package childPkg = pkg.childPackages.get(i);
14682            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14683        }
14684    }
14685
14686    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14687        // Collect all used permissions in the UID
14688        ArraySet<String> usedPermissions = new ArraySet<>();
14689        final int packageCount = su.packages.size();
14690        for (int i = 0; i < packageCount; i++) {
14691            PackageSetting ps = su.packages.valueAt(i);
14692            if (ps.pkg == null) {
14693                continue;
14694            }
14695            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14696            for (int j = 0; j < requestedPermCount; j++) {
14697                String permission = ps.pkg.requestedPermissions.get(j);
14698                BasePermission bp = mSettings.mPermissions.get(permission);
14699                if (bp != null) {
14700                    usedPermissions.add(permission);
14701                }
14702            }
14703        }
14704
14705        PermissionsState permissionsState = su.getPermissionsState();
14706        // Prune install permissions
14707        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14708        final int installPermCount = installPermStates.size();
14709        for (int i = installPermCount - 1; i >= 0;  i--) {
14710            PermissionState permissionState = installPermStates.get(i);
14711            if (!usedPermissions.contains(permissionState.getName())) {
14712                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14713                if (bp != null) {
14714                    permissionsState.revokeInstallPermission(bp);
14715                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14716                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14717                }
14718            }
14719        }
14720
14721        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14722
14723        // Prune runtime permissions
14724        for (int userId : allUserIds) {
14725            List<PermissionState> runtimePermStates = permissionsState
14726                    .getRuntimePermissionStates(userId);
14727            final int runtimePermCount = runtimePermStates.size();
14728            for (int i = runtimePermCount - 1; i >= 0; i--) {
14729                PermissionState permissionState = runtimePermStates.get(i);
14730                if (!usedPermissions.contains(permissionState.getName())) {
14731                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14732                    if (bp != null) {
14733                        permissionsState.revokeRuntimePermission(bp, userId);
14734                        permissionsState.updatePermissionFlags(bp, userId,
14735                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14736                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14737                                runtimePermissionChangedUserIds, userId);
14738                    }
14739                }
14740            }
14741        }
14742
14743        return runtimePermissionChangedUserIds;
14744    }
14745
14746    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14747            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14748        // Update the parent package setting
14749        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14750                res, user);
14751        // Update the child packages setting
14752        final int childCount = (newPackage.childPackages != null)
14753                ? newPackage.childPackages.size() : 0;
14754        for (int i = 0; i < childCount; i++) {
14755            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14756            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14757            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14758                    childRes.origUsers, childRes, user);
14759        }
14760    }
14761
14762    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14763            String installerPackageName, int[] allUsers, int[] installedForUsers,
14764            PackageInstalledInfo res, UserHandle user) {
14765        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14766
14767        String pkgName = newPackage.packageName;
14768        synchronized (mPackages) {
14769            //write settings. the installStatus will be incomplete at this stage.
14770            //note that the new package setting would have already been
14771            //added to mPackages. It hasn't been persisted yet.
14772            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14773            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14774            mSettings.writeLPr();
14775            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14776        }
14777
14778        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14779        synchronized (mPackages) {
14780            updatePermissionsLPw(newPackage.packageName, newPackage,
14781                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14782                            ? UPDATE_PERMISSIONS_ALL : 0));
14783            // For system-bundled packages, we assume that installing an upgraded version
14784            // of the package implies that the user actually wants to run that new code,
14785            // so we enable the package.
14786            PackageSetting ps = mSettings.mPackages.get(pkgName);
14787            final int userId = user.getIdentifier();
14788            if (ps != null) {
14789                if (isSystemApp(newPackage)) {
14790                    if (DEBUG_INSTALL) {
14791                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14792                    }
14793                    // Enable system package for requested users
14794                    if (res.origUsers != null) {
14795                        for (int origUserId : res.origUsers) {
14796                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14797                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14798                                        origUserId, installerPackageName);
14799                            }
14800                        }
14801                    }
14802                    // Also convey the prior install/uninstall state
14803                    if (allUsers != null && installedForUsers != null) {
14804                        for (int currentUserId : allUsers) {
14805                            final boolean installed = ArrayUtils.contains(
14806                                    installedForUsers, currentUserId);
14807                            if (DEBUG_INSTALL) {
14808                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14809                            }
14810                            ps.setInstalled(installed, currentUserId);
14811                        }
14812                        // these install state changes will be persisted in the
14813                        // upcoming call to mSettings.writeLPr().
14814                    }
14815                }
14816                // It's implied that when a user requests installation, they want the app to be
14817                // installed and enabled.
14818                if (userId != UserHandle.USER_ALL) {
14819                    ps.setInstalled(true, userId);
14820                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14821                }
14822            }
14823            res.name = pkgName;
14824            res.uid = newPackage.applicationInfo.uid;
14825            res.pkg = newPackage;
14826            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14827            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14828            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14829            //to update install status
14830            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14831            mSettings.writeLPr();
14832            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14833        }
14834
14835        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14836    }
14837
14838    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14839        try {
14840            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14841            installPackageLI(args, res);
14842        } finally {
14843            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14844        }
14845    }
14846
14847    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14848        final int installFlags = args.installFlags;
14849        final String installerPackageName = args.installerPackageName;
14850        final String volumeUuid = args.volumeUuid;
14851        final File tmpPackageFile = new File(args.getCodePath());
14852        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14853        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14854                || (args.volumeUuid != null));
14855        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14856        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14857        boolean replace = false;
14858        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14859        if (args.move != null) {
14860            // moving a complete application; perform an initial scan on the new install location
14861            scanFlags |= SCAN_INITIAL;
14862        }
14863        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14864            scanFlags |= SCAN_DONT_KILL_APP;
14865        }
14866
14867        // Result object to be returned
14868        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14869
14870        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14871
14872        // Sanity check
14873        if (ephemeral && (forwardLocked || onExternal)) {
14874            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14875                    + " external=" + onExternal);
14876            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14877            return;
14878        }
14879
14880        // Retrieve PackageSettings and parse package
14881        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14882                | PackageParser.PARSE_ENFORCE_CODE
14883                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14884                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14885                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14886                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14887        PackageParser pp = new PackageParser();
14888        pp.setSeparateProcesses(mSeparateProcesses);
14889        pp.setDisplayMetrics(mMetrics);
14890
14891        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14892        final PackageParser.Package pkg;
14893        try {
14894            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14895        } catch (PackageParserException e) {
14896            res.setError("Failed parse during installPackageLI", e);
14897            return;
14898        } finally {
14899            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14900        }
14901
14902        // If we are installing a clustered package add results for the children
14903        if (pkg.childPackages != null) {
14904            synchronized (mPackages) {
14905                final int childCount = pkg.childPackages.size();
14906                for (int i = 0; i < childCount; i++) {
14907                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14908                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14909                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14910                    childRes.pkg = childPkg;
14911                    childRes.name = childPkg.packageName;
14912                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14913                    if (childPs != null) {
14914                        childRes.origUsers = childPs.queryInstalledUsers(
14915                                sUserManager.getUserIds(), true);
14916                    }
14917                    if ((mPackages.containsKey(childPkg.packageName))) {
14918                        childRes.removedInfo = new PackageRemovedInfo();
14919                        childRes.removedInfo.removedPackage = childPkg.packageName;
14920                    }
14921                    if (res.addedChildPackages == null) {
14922                        res.addedChildPackages = new ArrayMap<>();
14923                    }
14924                    res.addedChildPackages.put(childPkg.packageName, childRes);
14925                }
14926            }
14927        }
14928
14929        // If package doesn't declare API override, mark that we have an install
14930        // time CPU ABI override.
14931        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14932            pkg.cpuAbiOverride = args.abiOverride;
14933        }
14934
14935        String pkgName = res.name = pkg.packageName;
14936        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14937            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14938                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14939                return;
14940            }
14941        }
14942
14943        try {
14944            // either use what we've been given or parse directly from the APK
14945            if (args.certificates != null) {
14946                try {
14947                    PackageParser.populateCertificates(pkg, args.certificates);
14948                } catch (PackageParserException e) {
14949                    // there was something wrong with the certificates we were given;
14950                    // try to pull them from the APK
14951                    PackageParser.collectCertificates(pkg, parseFlags);
14952                }
14953            } else {
14954                PackageParser.collectCertificates(pkg, parseFlags);
14955            }
14956        } catch (PackageParserException e) {
14957            res.setError("Failed collect during installPackageLI", e);
14958            return;
14959        }
14960
14961        // Get rid of all references to package scan path via parser.
14962        pp = null;
14963        String oldCodePath = null;
14964        boolean systemApp = false;
14965        synchronized (mPackages) {
14966            // Check if installing already existing package
14967            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14968                String oldName = mSettings.mRenamedPackages.get(pkgName);
14969                if (pkg.mOriginalPackages != null
14970                        && pkg.mOriginalPackages.contains(oldName)
14971                        && mPackages.containsKey(oldName)) {
14972                    // This package is derived from an original package,
14973                    // and this device has been updating from that original
14974                    // name.  We must continue using the original name, so
14975                    // rename the new package here.
14976                    pkg.setPackageName(oldName);
14977                    pkgName = pkg.packageName;
14978                    replace = true;
14979                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14980                            + oldName + " pkgName=" + pkgName);
14981                } else if (mPackages.containsKey(pkgName)) {
14982                    // This package, under its official name, already exists
14983                    // on the device; we should replace it.
14984                    replace = true;
14985                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14986                }
14987
14988                // Child packages are installed through the parent package
14989                if (pkg.parentPackage != null) {
14990                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14991                            "Package " + pkg.packageName + " is child of package "
14992                                    + pkg.parentPackage.parentPackage + ". Child packages "
14993                                    + "can be updated only through the parent package.");
14994                    return;
14995                }
14996
14997                if (replace) {
14998                    // Prevent apps opting out from runtime permissions
14999                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15000                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15001                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15002                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15003                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15004                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15005                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15006                                        + " doesn't support runtime permissions but the old"
15007                                        + " target SDK " + oldTargetSdk + " does.");
15008                        return;
15009                    }
15010
15011                    // Prevent installing of child packages
15012                    if (oldPackage.parentPackage != null) {
15013                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15014                                "Package " + pkg.packageName + " is child of package "
15015                                        + oldPackage.parentPackage + ". Child packages "
15016                                        + "can be updated only through the parent package.");
15017                        return;
15018                    }
15019                }
15020            }
15021
15022            PackageSetting ps = mSettings.mPackages.get(pkgName);
15023            if (ps != null) {
15024                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15025
15026                // Quick sanity check that we're signed correctly if updating;
15027                // we'll check this again later when scanning, but we want to
15028                // bail early here before tripping over redefined permissions.
15029                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15030                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15031                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15032                                + pkg.packageName + " upgrade keys do not match the "
15033                                + "previously installed version");
15034                        return;
15035                    }
15036                } else {
15037                    try {
15038                        verifySignaturesLP(ps, pkg);
15039                    } catch (PackageManagerException e) {
15040                        res.setError(e.error, e.getMessage());
15041                        return;
15042                    }
15043                }
15044
15045                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15046                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15047                    systemApp = (ps.pkg.applicationInfo.flags &
15048                            ApplicationInfo.FLAG_SYSTEM) != 0;
15049                }
15050                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15051            }
15052
15053            // Check whether the newly-scanned package wants to define an already-defined perm
15054            int N = pkg.permissions.size();
15055            for (int i = N-1; i >= 0; i--) {
15056                PackageParser.Permission perm = pkg.permissions.get(i);
15057                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15058                if (bp != null) {
15059                    // If the defining package is signed with our cert, it's okay.  This
15060                    // also includes the "updating the same package" case, of course.
15061                    // "updating same package" could also involve key-rotation.
15062                    final boolean sigsOk;
15063                    if (bp.sourcePackage.equals(pkg.packageName)
15064                            && (bp.packageSetting instanceof PackageSetting)
15065                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15066                                    scanFlags))) {
15067                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15068                    } else {
15069                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15070                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15071                    }
15072                    if (!sigsOk) {
15073                        // If the owning package is the system itself, we log but allow
15074                        // install to proceed; we fail the install on all other permission
15075                        // redefinitions.
15076                        if (!bp.sourcePackage.equals("android")) {
15077                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15078                                    + pkg.packageName + " attempting to redeclare permission "
15079                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15080                            res.origPermission = perm.info.name;
15081                            res.origPackage = bp.sourcePackage;
15082                            return;
15083                        } else {
15084                            Slog.w(TAG, "Package " + pkg.packageName
15085                                    + " attempting to redeclare system permission "
15086                                    + perm.info.name + "; ignoring new declaration");
15087                            pkg.permissions.remove(i);
15088                        }
15089                    }
15090                }
15091            }
15092        }
15093
15094        if (systemApp) {
15095            if (onExternal) {
15096                // Abort update; system app can't be replaced with app on sdcard
15097                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15098                        "Cannot install updates to system apps on sdcard");
15099                return;
15100            } else if (ephemeral) {
15101                // Abort update; system app can't be replaced with an ephemeral app
15102                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15103                        "Cannot update a system app with an ephemeral app");
15104                return;
15105            }
15106        }
15107
15108        if (args.move != null) {
15109            // We did an in-place move, so dex is ready to roll
15110            scanFlags |= SCAN_NO_DEX;
15111            scanFlags |= SCAN_MOVE;
15112
15113            synchronized (mPackages) {
15114                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15115                if (ps == null) {
15116                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15117                            "Missing settings for moved package " + pkgName);
15118                }
15119
15120                // We moved the entire application as-is, so bring over the
15121                // previously derived ABI information.
15122                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15123                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15124            }
15125
15126        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15127            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15128            scanFlags |= SCAN_NO_DEX;
15129
15130            try {
15131                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15132                    args.abiOverride : pkg.cpuAbiOverride);
15133                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15134                        true /* extract libs */);
15135            } catch (PackageManagerException pme) {
15136                Slog.e(TAG, "Error deriving application ABI", pme);
15137                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15138                return;
15139            }
15140
15141            // Shared libraries for the package need to be updated.
15142            synchronized (mPackages) {
15143                try {
15144                    updateSharedLibrariesLPw(pkg, null);
15145                } catch (PackageManagerException e) {
15146                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15147                }
15148            }
15149            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15150            // Do not run PackageDexOptimizer through the local performDexOpt
15151            // method because `pkg` may not be in `mPackages` yet.
15152            //
15153            // Also, don't fail application installs if the dexopt step fails.
15154            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15155                    null /* instructionSets */, false /* checkProfiles */,
15156                    getCompilerFilterForReason(REASON_INSTALL),
15157                    getOrCreateCompilerPackageStats(pkg));
15158            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15159
15160            // Notify BackgroundDexOptService that the package has been changed.
15161            // If this is an update of a package which used to fail to compile,
15162            // BDOS will remove it from its blacklist.
15163            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15164        }
15165
15166        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15167            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15168            return;
15169        }
15170
15171        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15172
15173        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15174                "installPackageLI")) {
15175            if (replace) {
15176                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15177                        installerPackageName, res);
15178            } else {
15179                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15180                        args.user, installerPackageName, volumeUuid, res);
15181            }
15182        }
15183        synchronized (mPackages) {
15184            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15185            if (ps != null) {
15186                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15187            }
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                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15193                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15194                if (childPs != null) {
15195                    childRes.newUsers = childPs.queryInstalledUsers(
15196                            sUserManager.getUserIds(), true);
15197                }
15198            }
15199        }
15200    }
15201
15202    private void startIntentFilterVerifications(int userId, boolean replacing,
15203            PackageParser.Package pkg) {
15204        if (mIntentFilterVerifierComponent == null) {
15205            Slog.w(TAG, "No IntentFilter verification will not be done as "
15206                    + "there is no IntentFilterVerifier available!");
15207            return;
15208        }
15209
15210        final int verifierUid = getPackageUid(
15211                mIntentFilterVerifierComponent.getPackageName(),
15212                MATCH_DEBUG_TRIAGED_MISSING,
15213                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15214
15215        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15216        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15217        mHandler.sendMessage(msg);
15218
15219        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15220        for (int i = 0; i < childCount; i++) {
15221            PackageParser.Package childPkg = pkg.childPackages.get(i);
15222            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15223            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15224            mHandler.sendMessage(msg);
15225        }
15226    }
15227
15228    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15229            PackageParser.Package pkg) {
15230        int size = pkg.activities.size();
15231        if (size == 0) {
15232            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15233                    "No activity, so no need to verify any IntentFilter!");
15234            return;
15235        }
15236
15237        final boolean hasDomainURLs = hasDomainURLs(pkg);
15238        if (!hasDomainURLs) {
15239            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15240                    "No domain URLs, so no need to verify any IntentFilter!");
15241            return;
15242        }
15243
15244        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15245                + " if any IntentFilter from the " + size
15246                + " Activities needs verification ...");
15247
15248        int count = 0;
15249        final String packageName = pkg.packageName;
15250
15251        synchronized (mPackages) {
15252            // If this is a new install and we see that we've already run verification for this
15253            // package, we have nothing to do: it means the state was restored from backup.
15254            if (!replacing) {
15255                IntentFilterVerificationInfo ivi =
15256                        mSettings.getIntentFilterVerificationLPr(packageName);
15257                if (ivi != null) {
15258                    if (DEBUG_DOMAIN_VERIFICATION) {
15259                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15260                                + ivi.getStatusString());
15261                    }
15262                    return;
15263                }
15264            }
15265
15266            // If any filters need to be verified, then all need to be.
15267            boolean needToVerify = false;
15268            for (PackageParser.Activity a : pkg.activities) {
15269                for (ActivityIntentInfo filter : a.intents) {
15270                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15271                        if (DEBUG_DOMAIN_VERIFICATION) {
15272                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15273                        }
15274                        needToVerify = true;
15275                        break;
15276                    }
15277                }
15278            }
15279
15280            if (needToVerify) {
15281                final int verificationId = mIntentFilterVerificationToken++;
15282                for (PackageParser.Activity a : pkg.activities) {
15283                    for (ActivityIntentInfo filter : a.intents) {
15284                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15285                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15286                                    "Verification needed for IntentFilter:" + filter.toString());
15287                            mIntentFilterVerifier.addOneIntentFilterVerification(
15288                                    verifierUid, userId, verificationId, filter, packageName);
15289                            count++;
15290                        }
15291                    }
15292                }
15293            }
15294        }
15295
15296        if (count > 0) {
15297            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15298                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15299                    +  " for userId:" + userId);
15300            mIntentFilterVerifier.startVerifications(userId);
15301        } else {
15302            if (DEBUG_DOMAIN_VERIFICATION) {
15303                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15304            }
15305        }
15306    }
15307
15308    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15309        final ComponentName cn  = filter.activity.getComponentName();
15310        final String packageName = cn.getPackageName();
15311
15312        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15313                packageName);
15314        if (ivi == null) {
15315            return true;
15316        }
15317        int status = ivi.getStatus();
15318        switch (status) {
15319            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15320            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15321                return true;
15322
15323            default:
15324                // Nothing to do
15325                return false;
15326        }
15327    }
15328
15329    private static boolean isMultiArch(ApplicationInfo info) {
15330        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15331    }
15332
15333    private static boolean isExternal(PackageParser.Package pkg) {
15334        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15335    }
15336
15337    private static boolean isExternal(PackageSetting ps) {
15338        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15339    }
15340
15341    private static boolean isEphemeral(PackageParser.Package pkg) {
15342        return pkg.applicationInfo.isEphemeralApp();
15343    }
15344
15345    private static boolean isEphemeral(PackageSetting ps) {
15346        return ps.pkg != null && isEphemeral(ps.pkg);
15347    }
15348
15349    private static boolean isSystemApp(PackageParser.Package pkg) {
15350        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15351    }
15352
15353    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15354        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15355    }
15356
15357    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15358        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15359    }
15360
15361    private static boolean isSystemApp(PackageSetting ps) {
15362        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15363    }
15364
15365    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15366        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15367    }
15368
15369    private int packageFlagsToInstallFlags(PackageSetting ps) {
15370        int installFlags = 0;
15371        if (isEphemeral(ps)) {
15372            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15373        }
15374        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15375            // This existing package was an external ASEC install when we have
15376            // the external flag without a UUID
15377            installFlags |= PackageManager.INSTALL_EXTERNAL;
15378        }
15379        if (ps.isForwardLocked()) {
15380            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15381        }
15382        return installFlags;
15383    }
15384
15385    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15386        if (isExternal(pkg)) {
15387            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15388                return StorageManager.UUID_PRIMARY_PHYSICAL;
15389            } else {
15390                return pkg.volumeUuid;
15391            }
15392        } else {
15393            return StorageManager.UUID_PRIVATE_INTERNAL;
15394        }
15395    }
15396
15397    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15398        if (isExternal(pkg)) {
15399            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15400                return mSettings.getExternalVersion();
15401            } else {
15402                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15403            }
15404        } else {
15405            return mSettings.getInternalVersion();
15406        }
15407    }
15408
15409    private void deleteTempPackageFiles() {
15410        final FilenameFilter filter = new FilenameFilter() {
15411            public boolean accept(File dir, String name) {
15412                return name.startsWith("vmdl") && name.endsWith(".tmp");
15413            }
15414        };
15415        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15416            file.delete();
15417        }
15418    }
15419
15420    @Override
15421    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15422            int flags) {
15423        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15424                flags);
15425    }
15426
15427    @Override
15428    public void deletePackage(final String packageName,
15429            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15430        mContext.enforceCallingOrSelfPermission(
15431                android.Manifest.permission.DELETE_PACKAGES, null);
15432        Preconditions.checkNotNull(packageName);
15433        Preconditions.checkNotNull(observer);
15434        final int uid = Binder.getCallingUid();
15435        if (uid != Process.SHELL_UID && uid != Process.ROOT_UID && uid != Process.SYSTEM_UID
15436                && uid != getPackageUid(mRequiredInstallerPackage, 0, UserHandle.getUserId(uid))
15437                && !isOrphaned(packageName)
15438                && !isCallerSameAsInstaller(uid, packageName)) {
15439            try {
15440                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15441                intent.setData(Uri.fromParts("package", packageName, null));
15442                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15443                observer.onUserActionRequired(intent);
15444            } catch (RemoteException re) {
15445            }
15446            return;
15447        }
15448        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15449        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15450        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15451            mContext.enforceCallingOrSelfPermission(
15452                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15453                    "deletePackage for user " + userId);
15454        }
15455
15456        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15457            try {
15458                observer.onPackageDeleted(packageName,
15459                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15460            } catch (RemoteException re) {
15461            }
15462            return;
15463        }
15464
15465        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15466            try {
15467                observer.onPackageDeleted(packageName,
15468                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15469            } catch (RemoteException re) {
15470            }
15471            return;
15472        }
15473
15474        if (DEBUG_REMOVE) {
15475            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15476                    + " deleteAllUsers: " + deleteAllUsers );
15477        }
15478        // Queue up an async operation since the package deletion may take a little while.
15479        mHandler.post(new Runnable() {
15480            public void run() {
15481                mHandler.removeCallbacks(this);
15482                int returnCode;
15483                if (!deleteAllUsers) {
15484                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15485                } else {
15486                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15487                    // If nobody is blocking uninstall, proceed with delete for all users
15488                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15489                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15490                    } else {
15491                        // Otherwise uninstall individually for users with blockUninstalls=false
15492                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15493                        for (int userId : users) {
15494                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15495                                returnCode = deletePackageX(packageName, userId, userFlags);
15496                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15497                                    Slog.w(TAG, "Package delete failed for user " + userId
15498                                            + ", returnCode " + returnCode);
15499                                }
15500                            }
15501                        }
15502                        // The app has only been marked uninstalled for certain users.
15503                        // We still need to report that delete was blocked
15504                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15505                    }
15506                }
15507                try {
15508                    observer.onPackageDeleted(packageName, returnCode, null);
15509                } catch (RemoteException e) {
15510                    Log.i(TAG, "Observer no longer exists.");
15511                } //end catch
15512            } //end run
15513        });
15514    }
15515
15516    private boolean isCallerSameAsInstaller(int callingUid, String pkgName) {
15517        final int installerPkgUid = getPackageUid(getInstallerPackageName(pkgName),
15518                0 /* flags */, UserHandle.getUserId(callingUid));
15519        return installerPkgUid == callingUid;
15520    }
15521
15522    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15523        int[] result = EMPTY_INT_ARRAY;
15524        for (int userId : userIds) {
15525            if (getBlockUninstallForUser(packageName, userId)) {
15526                result = ArrayUtils.appendInt(result, userId);
15527            }
15528        }
15529        return result;
15530    }
15531
15532    @Override
15533    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15534        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15535    }
15536
15537    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15538        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15539                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15540        try {
15541            if (dpm != null) {
15542                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15543                        /* callingUserOnly =*/ false);
15544                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15545                        : deviceOwnerComponentName.getPackageName();
15546                // Does the package contains the device owner?
15547                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15548                // this check is probably not needed, since DO should be registered as a device
15549                // admin on some user too. (Original bug for this: b/17657954)
15550                if (packageName.equals(deviceOwnerPackageName)) {
15551                    return true;
15552                }
15553                // Does it contain a device admin for any user?
15554                int[] users;
15555                if (userId == UserHandle.USER_ALL) {
15556                    users = sUserManager.getUserIds();
15557                } else {
15558                    users = new int[]{userId};
15559                }
15560                for (int i = 0; i < users.length; ++i) {
15561                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15562                        return true;
15563                    }
15564                }
15565            }
15566        } catch (RemoteException e) {
15567        }
15568        return false;
15569    }
15570
15571    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15572        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15573    }
15574
15575    /**
15576     *  This method is an internal method that could be get invoked either
15577     *  to delete an installed package or to clean up a failed installation.
15578     *  After deleting an installed package, a broadcast is sent to notify any
15579     *  listeners that the package has been removed. For cleaning up a failed
15580     *  installation, the broadcast is not necessary since the package's
15581     *  installation wouldn't have sent the initial broadcast either
15582     *  The key steps in deleting a package are
15583     *  deleting the package information in internal structures like mPackages,
15584     *  deleting the packages base directories through installd
15585     *  updating mSettings to reflect current status
15586     *  persisting settings for later use
15587     *  sending a broadcast if necessary
15588     */
15589    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15590        final PackageRemovedInfo info = new PackageRemovedInfo();
15591        final boolean res;
15592
15593        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15594                ? UserHandle.USER_ALL : userId;
15595
15596        if (isPackageDeviceAdmin(packageName, removeUser)) {
15597            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15598            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15599        }
15600
15601        PackageSetting uninstalledPs = null;
15602
15603        // for the uninstall-updates case and restricted profiles, remember the per-
15604        // user handle installed state
15605        int[] allUsers;
15606        synchronized (mPackages) {
15607            uninstalledPs = mSettings.mPackages.get(packageName);
15608            if (uninstalledPs == null) {
15609                Slog.w(TAG, "Not removing non-existent package " + packageName);
15610                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15611            }
15612            allUsers = sUserManager.getUserIds();
15613            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15614        }
15615
15616        final int freezeUser;
15617        if (isUpdatedSystemApp(uninstalledPs)
15618                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15619            // We're downgrading a system app, which will apply to all users, so
15620            // freeze them all during the downgrade
15621            freezeUser = UserHandle.USER_ALL;
15622        } else {
15623            freezeUser = removeUser;
15624        }
15625
15626        synchronized (mInstallLock) {
15627            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15628            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15629                    deleteFlags, "deletePackageX")) {
15630                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15631                        deleteFlags | REMOVE_CHATTY, info, true, null);
15632            }
15633            synchronized (mPackages) {
15634                if (res) {
15635                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15636                }
15637            }
15638        }
15639
15640        if (res) {
15641            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15642            info.sendPackageRemovedBroadcasts(killApp);
15643            info.sendSystemPackageUpdatedBroadcasts();
15644            info.sendSystemPackageAppearedBroadcasts();
15645        }
15646        // Force a gc here.
15647        Runtime.getRuntime().gc();
15648        // Delete the resources here after sending the broadcast to let
15649        // other processes clean up before deleting resources.
15650        if (info.args != null) {
15651            synchronized (mInstallLock) {
15652                info.args.doPostDeleteLI(true);
15653            }
15654        }
15655
15656        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15657    }
15658
15659    class PackageRemovedInfo {
15660        String removedPackage;
15661        int uid = -1;
15662        int removedAppId = -1;
15663        int[] origUsers;
15664        int[] removedUsers = null;
15665        boolean isRemovedPackageSystemUpdate = false;
15666        boolean isUpdate;
15667        boolean dataRemoved;
15668        boolean removedForAllUsers;
15669        // Clean up resources deleted packages.
15670        InstallArgs args = null;
15671        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15672        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15673
15674        void sendPackageRemovedBroadcasts(boolean killApp) {
15675            sendPackageRemovedBroadcastInternal(killApp);
15676            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15677            for (int i = 0; i < childCount; i++) {
15678                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15679                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15680            }
15681        }
15682
15683        void sendSystemPackageUpdatedBroadcasts() {
15684            if (isRemovedPackageSystemUpdate) {
15685                sendSystemPackageUpdatedBroadcastsInternal();
15686                final int childCount = (removedChildPackages != null)
15687                        ? removedChildPackages.size() : 0;
15688                for (int i = 0; i < childCount; i++) {
15689                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15690                    if (childInfo.isRemovedPackageSystemUpdate) {
15691                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15692                    }
15693                }
15694            }
15695        }
15696
15697        void sendSystemPackageAppearedBroadcasts() {
15698            final int packageCount = (appearedChildPackages != null)
15699                    ? appearedChildPackages.size() : 0;
15700            for (int i = 0; i < packageCount; i++) {
15701                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15702                for (int userId : installedInfo.newUsers) {
15703                    sendPackageAddedForUser(installedInfo.name, true,
15704                            UserHandle.getAppId(installedInfo.uid), userId);
15705                }
15706            }
15707        }
15708
15709        private void sendSystemPackageUpdatedBroadcastsInternal() {
15710            Bundle extras = new Bundle(2);
15711            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15712            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15713            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15714                    extras, 0, null, null, null);
15715            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15716                    extras, 0, null, null, null);
15717            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15718                    null, 0, removedPackage, null, null);
15719        }
15720
15721        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15722            Bundle extras = new Bundle(2);
15723            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15724            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15725            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15726            if (isUpdate || isRemovedPackageSystemUpdate) {
15727                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15728            }
15729            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15730            if (removedPackage != null) {
15731                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15732                        extras, 0, null, null, removedUsers);
15733                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15734                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15735                            removedPackage, extras, 0, null, null, removedUsers);
15736                }
15737            }
15738            if (removedAppId >= 0) {
15739                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15740                        removedUsers);
15741            }
15742        }
15743    }
15744
15745    /*
15746     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15747     * flag is not set, the data directory is removed as well.
15748     * make sure this flag is set for partially installed apps. If not its meaningless to
15749     * delete a partially installed application.
15750     */
15751    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15752            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15753        String packageName = ps.name;
15754        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15755        // Retrieve object to delete permissions for shared user later on
15756        final PackageParser.Package deletedPkg;
15757        final PackageSetting deletedPs;
15758        // reader
15759        synchronized (mPackages) {
15760            deletedPkg = mPackages.get(packageName);
15761            deletedPs = mSettings.mPackages.get(packageName);
15762            if (outInfo != null) {
15763                outInfo.removedPackage = packageName;
15764                outInfo.removedUsers = deletedPs != null
15765                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15766                        : null;
15767            }
15768        }
15769
15770        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15771
15772        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15773            final PackageParser.Package resolvedPkg;
15774            if (deletedPkg != null) {
15775                resolvedPkg = deletedPkg;
15776            } else {
15777                // We don't have a parsed package when it lives on an ejected
15778                // adopted storage device, so fake something together
15779                resolvedPkg = new PackageParser.Package(ps.name);
15780                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15781            }
15782            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15783                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15784            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15785            if (outInfo != null) {
15786                outInfo.dataRemoved = true;
15787            }
15788            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15789        }
15790
15791        // writer
15792        synchronized (mPackages) {
15793            if (deletedPs != null) {
15794                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15795                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15796                    clearDefaultBrowserIfNeeded(packageName);
15797                    if (outInfo != null) {
15798                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15799                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15800                    }
15801                    updatePermissionsLPw(deletedPs.name, null, 0);
15802                    if (deletedPs.sharedUser != null) {
15803                        // Remove permissions associated with package. Since runtime
15804                        // permissions are per user we have to kill the removed package
15805                        // or packages running under the shared user of the removed
15806                        // package if revoking the permissions requested only by the removed
15807                        // package is successful and this causes a change in gids.
15808                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15809                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15810                                    userId);
15811                            if (userIdToKill == UserHandle.USER_ALL
15812                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15813                                // If gids changed for this user, kill all affected packages.
15814                                mHandler.post(new Runnable() {
15815                                    @Override
15816                                    public void run() {
15817                                        // This has to happen with no lock held.
15818                                        killApplication(deletedPs.name, deletedPs.appId,
15819                                                KILL_APP_REASON_GIDS_CHANGED);
15820                                    }
15821                                });
15822                                break;
15823                            }
15824                        }
15825                    }
15826                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15827                }
15828                // make sure to preserve per-user disabled state if this removal was just
15829                // a downgrade of a system app to the factory package
15830                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15831                    if (DEBUG_REMOVE) {
15832                        Slog.d(TAG, "Propagating install state across downgrade");
15833                    }
15834                    for (int userId : allUserHandles) {
15835                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15836                        if (DEBUG_REMOVE) {
15837                            Slog.d(TAG, "    user " + userId + " => " + installed);
15838                        }
15839                        ps.setInstalled(installed, userId);
15840                    }
15841                }
15842            }
15843            // can downgrade to reader
15844            if (writeSettings) {
15845                // Save settings now
15846                mSettings.writeLPr();
15847            }
15848        }
15849        if (outInfo != null) {
15850            // A user ID was deleted here. Go through all users and remove it
15851            // from KeyStore.
15852            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15853        }
15854    }
15855
15856    static boolean locationIsPrivileged(File path) {
15857        try {
15858            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15859                    .getCanonicalPath();
15860            return path.getCanonicalPath().startsWith(privilegedAppDir);
15861        } catch (IOException e) {
15862            Slog.e(TAG, "Unable to access code path " + path);
15863        }
15864        return false;
15865    }
15866
15867    /*
15868     * Tries to delete system package.
15869     */
15870    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15871            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15872            boolean writeSettings) {
15873        if (deletedPs.parentPackageName != null) {
15874            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15875            return false;
15876        }
15877
15878        final boolean applyUserRestrictions
15879                = (allUserHandles != null) && (outInfo.origUsers != null);
15880        final PackageSetting disabledPs;
15881        // Confirm if the system package has been updated
15882        // An updated system app can be deleted. This will also have to restore
15883        // the system pkg from system partition
15884        // reader
15885        synchronized (mPackages) {
15886            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15887        }
15888
15889        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15890                + " disabledPs=" + disabledPs);
15891
15892        if (disabledPs == null) {
15893            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15894            return false;
15895        } else if (DEBUG_REMOVE) {
15896            Slog.d(TAG, "Deleting system pkg from data partition");
15897        }
15898
15899        if (DEBUG_REMOVE) {
15900            if (applyUserRestrictions) {
15901                Slog.d(TAG, "Remembering install states:");
15902                for (int userId : allUserHandles) {
15903                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15904                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15905                }
15906            }
15907        }
15908
15909        // Delete the updated package
15910        outInfo.isRemovedPackageSystemUpdate = true;
15911        if (outInfo.removedChildPackages != null) {
15912            final int childCount = (deletedPs.childPackageNames != null)
15913                    ? deletedPs.childPackageNames.size() : 0;
15914            for (int i = 0; i < childCount; i++) {
15915                String childPackageName = deletedPs.childPackageNames.get(i);
15916                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15917                        .contains(childPackageName)) {
15918                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15919                            childPackageName);
15920                    if (childInfo != null) {
15921                        childInfo.isRemovedPackageSystemUpdate = true;
15922                    }
15923                }
15924            }
15925        }
15926
15927        if (disabledPs.versionCode < deletedPs.versionCode) {
15928            // Delete data for downgrades
15929            flags &= ~PackageManager.DELETE_KEEP_DATA;
15930        } else {
15931            // Preserve data by setting flag
15932            flags |= PackageManager.DELETE_KEEP_DATA;
15933        }
15934
15935        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15936                outInfo, writeSettings, disabledPs.pkg);
15937        if (!ret) {
15938            return false;
15939        }
15940
15941        // writer
15942        synchronized (mPackages) {
15943            // Reinstate the old system package
15944            enableSystemPackageLPw(disabledPs.pkg);
15945            // Remove any native libraries from the upgraded package.
15946            removeNativeBinariesLI(deletedPs);
15947        }
15948
15949        // Install the system package
15950        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15951        int parseFlags = mDefParseFlags
15952                | PackageParser.PARSE_MUST_BE_APK
15953                | PackageParser.PARSE_IS_SYSTEM
15954                | PackageParser.PARSE_IS_SYSTEM_DIR;
15955        if (locationIsPrivileged(disabledPs.codePath)) {
15956            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15957        }
15958
15959        final PackageParser.Package newPkg;
15960        try {
15961            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15962        } catch (PackageManagerException e) {
15963            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15964                    + e.getMessage());
15965            return false;
15966        }
15967        try {
15968            // update shared libraries for the newly re-installed system package
15969            updateSharedLibrariesLPw(newPkg, null);
15970        } catch (PackageManagerException e) {
15971            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
15972        }
15973
15974        prepareAppDataAfterInstallLIF(newPkg);
15975
15976        // writer
15977        synchronized (mPackages) {
15978            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15979
15980            // Propagate the permissions state as we do not want to drop on the floor
15981            // runtime permissions. The update permissions method below will take
15982            // care of removing obsolete permissions and grant install permissions.
15983            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15984            updatePermissionsLPw(newPkg.packageName, newPkg,
15985                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15986
15987            if (applyUserRestrictions) {
15988                if (DEBUG_REMOVE) {
15989                    Slog.d(TAG, "Propagating install state across reinstall");
15990                }
15991                for (int userId : allUserHandles) {
15992                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15993                    if (DEBUG_REMOVE) {
15994                        Slog.d(TAG, "    user " + userId + " => " + installed);
15995                    }
15996                    ps.setInstalled(installed, userId);
15997
15998                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15999                }
16000                // Regardless of writeSettings we need to ensure that this restriction
16001                // state propagation is persisted
16002                mSettings.writeAllUsersPackageRestrictionsLPr();
16003            }
16004            // can downgrade to reader here
16005            if (writeSettings) {
16006                mSettings.writeLPr();
16007            }
16008        }
16009        return true;
16010    }
16011
16012    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16013            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16014            PackageRemovedInfo outInfo, boolean writeSettings,
16015            PackageParser.Package replacingPackage) {
16016        synchronized (mPackages) {
16017            if (outInfo != null) {
16018                outInfo.uid = ps.appId;
16019            }
16020
16021            if (outInfo != null && outInfo.removedChildPackages != null) {
16022                final int childCount = (ps.childPackageNames != null)
16023                        ? ps.childPackageNames.size() : 0;
16024                for (int i = 0; i < childCount; i++) {
16025                    String childPackageName = ps.childPackageNames.get(i);
16026                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16027                    if (childPs == null) {
16028                        return false;
16029                    }
16030                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16031                            childPackageName);
16032                    if (childInfo != null) {
16033                        childInfo.uid = childPs.appId;
16034                    }
16035                }
16036            }
16037        }
16038
16039        // Delete package data from internal structures and also remove data if flag is set
16040        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16041
16042        // Delete the child packages data
16043        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16044        for (int i = 0; i < childCount; i++) {
16045            PackageSetting childPs;
16046            synchronized (mPackages) {
16047                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16048            }
16049            if (childPs != null) {
16050                PackageRemovedInfo childOutInfo = (outInfo != null
16051                        && outInfo.removedChildPackages != null)
16052                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16053                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16054                        && (replacingPackage != null
16055                        && !replacingPackage.hasChildPackage(childPs.name))
16056                        ? flags & ~DELETE_KEEP_DATA : flags;
16057                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16058                        deleteFlags, writeSettings);
16059            }
16060        }
16061
16062        // Delete application code and resources only for parent packages
16063        if (ps.parentPackageName == null) {
16064            if (deleteCodeAndResources && (outInfo != null)) {
16065                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16066                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16067                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16068            }
16069        }
16070
16071        return true;
16072    }
16073
16074    @Override
16075    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16076            int userId) {
16077        mContext.enforceCallingOrSelfPermission(
16078                android.Manifest.permission.DELETE_PACKAGES, null);
16079        synchronized (mPackages) {
16080            PackageSetting ps = mSettings.mPackages.get(packageName);
16081            if (ps == null) {
16082                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16083                return false;
16084            }
16085            if (!ps.getInstalled(userId)) {
16086                // Can't block uninstall for an app that is not installed or enabled.
16087                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16088                return false;
16089            }
16090            ps.setBlockUninstall(blockUninstall, userId);
16091            mSettings.writePackageRestrictionsLPr(userId);
16092        }
16093        return true;
16094    }
16095
16096    @Override
16097    public boolean getBlockUninstallForUser(String packageName, int userId) {
16098        synchronized (mPackages) {
16099            PackageSetting ps = mSettings.mPackages.get(packageName);
16100            if (ps == null) {
16101                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16102                return false;
16103            }
16104            return ps.getBlockUninstall(userId);
16105        }
16106    }
16107
16108    @Override
16109    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16110        int callingUid = Binder.getCallingUid();
16111        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16112            throw new SecurityException(
16113                    "setRequiredForSystemUser can only be run by the system or root");
16114        }
16115        synchronized (mPackages) {
16116            PackageSetting ps = mSettings.mPackages.get(packageName);
16117            if (ps == null) {
16118                Log.w(TAG, "Package doesn't exist: " + packageName);
16119                return false;
16120            }
16121            if (systemUserApp) {
16122                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16123            } else {
16124                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16125            }
16126            mSettings.writeLPr();
16127        }
16128        return true;
16129    }
16130
16131    /*
16132     * This method handles package deletion in general
16133     */
16134    private boolean deletePackageLIF(String packageName, UserHandle user,
16135            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16136            PackageRemovedInfo outInfo, boolean writeSettings,
16137            PackageParser.Package replacingPackage) {
16138        if (packageName == null) {
16139            Slog.w(TAG, "Attempt to delete null packageName.");
16140            return false;
16141        }
16142
16143        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16144
16145        PackageSetting ps;
16146
16147        synchronized (mPackages) {
16148            ps = mSettings.mPackages.get(packageName);
16149            if (ps == null) {
16150                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16151                return false;
16152            }
16153
16154            if (ps.parentPackageName != null && (!isSystemApp(ps)
16155                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16156                if (DEBUG_REMOVE) {
16157                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16158                            + ((user == null) ? UserHandle.USER_ALL : user));
16159                }
16160                final int removedUserId = (user != null) ? user.getIdentifier()
16161                        : UserHandle.USER_ALL;
16162                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16163                    return false;
16164                }
16165                markPackageUninstalledForUserLPw(ps, user);
16166                scheduleWritePackageRestrictionsLocked(user);
16167                return true;
16168            }
16169        }
16170
16171        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16172                && user.getIdentifier() != UserHandle.USER_ALL)) {
16173            // The caller is asking that the package only be deleted for a single
16174            // user.  To do this, we just mark its uninstalled state and delete
16175            // its data. If this is a system app, we only allow this to happen if
16176            // they have set the special DELETE_SYSTEM_APP which requests different
16177            // semantics than normal for uninstalling system apps.
16178            markPackageUninstalledForUserLPw(ps, user);
16179
16180            if (!isSystemApp(ps)) {
16181                // Do not uninstall the APK if an app should be cached
16182                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16183                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16184                    // Other user still have this package installed, so all
16185                    // we need to do is clear this user's data and save that
16186                    // it is uninstalled.
16187                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16188                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16189                        return false;
16190                    }
16191                    scheduleWritePackageRestrictionsLocked(user);
16192                    return true;
16193                } else {
16194                    // We need to set it back to 'installed' so the uninstall
16195                    // broadcasts will be sent correctly.
16196                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16197                    ps.setInstalled(true, user.getIdentifier());
16198                }
16199            } else {
16200                // This is a system app, so we assume that the
16201                // other users still have this package installed, so all
16202                // we need to do is clear this user's data and save that
16203                // it is uninstalled.
16204                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16205                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16206                    return false;
16207                }
16208                scheduleWritePackageRestrictionsLocked(user);
16209                return true;
16210            }
16211        }
16212
16213        // If we are deleting a composite package for all users, keep track
16214        // of result for each child.
16215        if (ps.childPackageNames != null && outInfo != null) {
16216            synchronized (mPackages) {
16217                final int childCount = ps.childPackageNames.size();
16218                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16219                for (int i = 0; i < childCount; i++) {
16220                    String childPackageName = ps.childPackageNames.get(i);
16221                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16222                    childInfo.removedPackage = childPackageName;
16223                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16224                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16225                    if (childPs != null) {
16226                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16227                    }
16228                }
16229            }
16230        }
16231
16232        boolean ret = false;
16233        if (isSystemApp(ps)) {
16234            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16235            // When an updated system application is deleted we delete the existing resources
16236            // as well and fall back to existing code in system partition
16237            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16238        } else {
16239            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16240            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16241                    outInfo, writeSettings, replacingPackage);
16242        }
16243
16244        // Take a note whether we deleted the package for all users
16245        if (outInfo != null) {
16246            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16247            if (outInfo.removedChildPackages != null) {
16248                synchronized (mPackages) {
16249                    final int childCount = outInfo.removedChildPackages.size();
16250                    for (int i = 0; i < childCount; i++) {
16251                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16252                        if (childInfo != null) {
16253                            childInfo.removedForAllUsers = mPackages.get(
16254                                    childInfo.removedPackage) == null;
16255                        }
16256                    }
16257                }
16258            }
16259            // If we uninstalled an update to a system app there may be some
16260            // child packages that appeared as they are declared in the system
16261            // app but were not declared in the update.
16262            if (isSystemApp(ps)) {
16263                synchronized (mPackages) {
16264                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16265                    final int childCount = (updatedPs.childPackageNames != null)
16266                            ? updatedPs.childPackageNames.size() : 0;
16267                    for (int i = 0; i < childCount; i++) {
16268                        String childPackageName = updatedPs.childPackageNames.get(i);
16269                        if (outInfo.removedChildPackages == null
16270                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16271                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16272                            if (childPs == null) {
16273                                continue;
16274                            }
16275                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16276                            installRes.name = childPackageName;
16277                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16278                            installRes.pkg = mPackages.get(childPackageName);
16279                            installRes.uid = childPs.pkg.applicationInfo.uid;
16280                            if (outInfo.appearedChildPackages == null) {
16281                                outInfo.appearedChildPackages = new ArrayMap<>();
16282                            }
16283                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16284                        }
16285                    }
16286                }
16287            }
16288        }
16289
16290        return ret;
16291    }
16292
16293    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16294        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16295                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16296        for (int nextUserId : userIds) {
16297            if (DEBUG_REMOVE) {
16298                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16299            }
16300            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16301                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16302                    false /*hidden*/, false /*suspended*/, null, null, null,
16303                    false /*blockUninstall*/,
16304                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16305        }
16306    }
16307
16308    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16309            PackageRemovedInfo outInfo) {
16310        final PackageParser.Package pkg;
16311        synchronized (mPackages) {
16312            pkg = mPackages.get(ps.name);
16313        }
16314
16315        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16316                : new int[] {userId};
16317        for (int nextUserId : userIds) {
16318            if (DEBUG_REMOVE) {
16319                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16320                        + nextUserId);
16321            }
16322
16323            destroyAppDataLIF(pkg, userId,
16324                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16325            destroyAppProfilesLIF(pkg, userId);
16326            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16327            schedulePackageCleaning(ps.name, nextUserId, false);
16328            synchronized (mPackages) {
16329                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16330                    scheduleWritePackageRestrictionsLocked(nextUserId);
16331                }
16332                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16333            }
16334        }
16335
16336        if (outInfo != null) {
16337            outInfo.removedPackage = ps.name;
16338            outInfo.removedAppId = ps.appId;
16339            outInfo.removedUsers = userIds;
16340        }
16341
16342        return true;
16343    }
16344
16345    private final class ClearStorageConnection implements ServiceConnection {
16346        IMediaContainerService mContainerService;
16347
16348        @Override
16349        public void onServiceConnected(ComponentName name, IBinder service) {
16350            synchronized (this) {
16351                mContainerService = IMediaContainerService.Stub.asInterface(service);
16352                notifyAll();
16353            }
16354        }
16355
16356        @Override
16357        public void onServiceDisconnected(ComponentName name) {
16358        }
16359    }
16360
16361    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16362        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16363
16364        final boolean mounted;
16365        if (Environment.isExternalStorageEmulated()) {
16366            mounted = true;
16367        } else {
16368            final String status = Environment.getExternalStorageState();
16369
16370            mounted = status.equals(Environment.MEDIA_MOUNTED)
16371                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16372        }
16373
16374        if (!mounted) {
16375            return;
16376        }
16377
16378        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16379        int[] users;
16380        if (userId == UserHandle.USER_ALL) {
16381            users = sUserManager.getUserIds();
16382        } else {
16383            users = new int[] { userId };
16384        }
16385        final ClearStorageConnection conn = new ClearStorageConnection();
16386        if (mContext.bindServiceAsUser(
16387                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16388            try {
16389                for (int curUser : users) {
16390                    long timeout = SystemClock.uptimeMillis() + 5000;
16391                    synchronized (conn) {
16392                        long now;
16393                        while (conn.mContainerService == null &&
16394                                (now = SystemClock.uptimeMillis()) < timeout) {
16395                            try {
16396                                conn.wait(timeout - now);
16397                            } catch (InterruptedException e) {
16398                            }
16399                        }
16400                    }
16401                    if (conn.mContainerService == null) {
16402                        return;
16403                    }
16404
16405                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16406                    clearDirectory(conn.mContainerService,
16407                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16408                    if (allData) {
16409                        clearDirectory(conn.mContainerService,
16410                                userEnv.buildExternalStorageAppDataDirs(packageName));
16411                        clearDirectory(conn.mContainerService,
16412                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16413                    }
16414                }
16415            } finally {
16416                mContext.unbindService(conn);
16417            }
16418        }
16419    }
16420
16421    @Override
16422    public void clearApplicationProfileData(String packageName) {
16423        enforceSystemOrRoot("Only the system can clear all profile data");
16424
16425        final PackageParser.Package pkg;
16426        synchronized (mPackages) {
16427            pkg = mPackages.get(packageName);
16428        }
16429
16430        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16431            synchronized (mInstallLock) {
16432                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16433                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16434                        true /* removeBaseMarker */);
16435            }
16436        }
16437    }
16438
16439    @Override
16440    public void clearApplicationUserData(final String packageName,
16441            final IPackageDataObserver observer, final int userId) {
16442        mContext.enforceCallingOrSelfPermission(
16443                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16444
16445        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16446                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16447
16448        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16449            throw new SecurityException("Cannot clear data for a protected package: "
16450                    + packageName);
16451        }
16452        // Queue up an async operation since the package deletion may take a little while.
16453        mHandler.post(new Runnable() {
16454            public void run() {
16455                mHandler.removeCallbacks(this);
16456                final boolean succeeded;
16457                try (PackageFreezer freezer = freezePackage(packageName,
16458                        "clearApplicationUserData")) {
16459                    synchronized (mInstallLock) {
16460                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16461                    }
16462                    clearExternalStorageDataSync(packageName, userId, true);
16463                }
16464                if (succeeded) {
16465                    // invoke DeviceStorageMonitor's update method to clear any notifications
16466                    DeviceStorageMonitorInternal dsm = LocalServices
16467                            .getService(DeviceStorageMonitorInternal.class);
16468                    if (dsm != null) {
16469                        dsm.checkMemory();
16470                    }
16471                }
16472                if(observer != null) {
16473                    try {
16474                        observer.onRemoveCompleted(packageName, succeeded);
16475                    } catch (RemoteException e) {
16476                        Log.i(TAG, "Observer no longer exists.");
16477                    }
16478                } //end if observer
16479            } //end run
16480        });
16481    }
16482
16483    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16484        if (packageName == null) {
16485            Slog.w(TAG, "Attempt to delete null packageName.");
16486            return false;
16487        }
16488
16489        // Try finding details about the requested package
16490        PackageParser.Package pkg;
16491        synchronized (mPackages) {
16492            pkg = mPackages.get(packageName);
16493            if (pkg == null) {
16494                final PackageSetting ps = mSettings.mPackages.get(packageName);
16495                if (ps != null) {
16496                    pkg = ps.pkg;
16497                }
16498            }
16499
16500            if (pkg == null) {
16501                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16502                return false;
16503            }
16504
16505            PackageSetting ps = (PackageSetting) pkg.mExtras;
16506            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16507        }
16508
16509        clearAppDataLIF(pkg, userId,
16510                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16511
16512        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16513        removeKeystoreDataIfNeeded(userId, appId);
16514
16515        UserManagerInternal umInternal = getUserManagerInternal();
16516        final int flags;
16517        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16518            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16519        } else if (umInternal.isUserRunning(userId)) {
16520            flags = StorageManager.FLAG_STORAGE_DE;
16521        } else {
16522            flags = 0;
16523        }
16524        prepareAppDataContentsLIF(pkg, userId, flags);
16525
16526        return true;
16527    }
16528
16529    /**
16530     * Reverts user permission state changes (permissions and flags) in
16531     * all packages for a given user.
16532     *
16533     * @param userId The device user for which to do a reset.
16534     */
16535    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16536        final int packageCount = mPackages.size();
16537        for (int i = 0; i < packageCount; i++) {
16538            PackageParser.Package pkg = mPackages.valueAt(i);
16539            PackageSetting ps = (PackageSetting) pkg.mExtras;
16540            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16541        }
16542    }
16543
16544    private void resetNetworkPolicies(int userId) {
16545        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16546    }
16547
16548    /**
16549     * Reverts user permission state changes (permissions and flags).
16550     *
16551     * @param ps The package for which to reset.
16552     * @param userId The device user for which to do a reset.
16553     */
16554    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16555            final PackageSetting ps, final int userId) {
16556        if (ps.pkg == null) {
16557            return;
16558        }
16559
16560        // These are flags that can change base on user actions.
16561        final int userSettableMask = FLAG_PERMISSION_USER_SET
16562                | FLAG_PERMISSION_USER_FIXED
16563                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16564                | FLAG_PERMISSION_REVIEW_REQUIRED;
16565
16566        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16567                | FLAG_PERMISSION_POLICY_FIXED;
16568
16569        boolean writeInstallPermissions = false;
16570        boolean writeRuntimePermissions = false;
16571
16572        final int permissionCount = ps.pkg.requestedPermissions.size();
16573        for (int i = 0; i < permissionCount; i++) {
16574            String permission = ps.pkg.requestedPermissions.get(i);
16575
16576            BasePermission bp = mSettings.mPermissions.get(permission);
16577            if (bp == null) {
16578                continue;
16579            }
16580
16581            // If shared user we just reset the state to which only this app contributed.
16582            if (ps.sharedUser != null) {
16583                boolean used = false;
16584                final int packageCount = ps.sharedUser.packages.size();
16585                for (int j = 0; j < packageCount; j++) {
16586                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16587                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16588                            && pkg.pkg.requestedPermissions.contains(permission)) {
16589                        used = true;
16590                        break;
16591                    }
16592                }
16593                if (used) {
16594                    continue;
16595                }
16596            }
16597
16598            PermissionsState permissionsState = ps.getPermissionsState();
16599
16600            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16601
16602            // Always clear the user settable flags.
16603            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16604                    bp.name) != null;
16605            // If permission review is enabled and this is a legacy app, mark the
16606            // permission as requiring a review as this is the initial state.
16607            int flags = 0;
16608            if (Build.PERMISSIONS_REVIEW_REQUIRED
16609                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16610                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16611            }
16612            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16613                if (hasInstallState) {
16614                    writeInstallPermissions = true;
16615                } else {
16616                    writeRuntimePermissions = true;
16617                }
16618            }
16619
16620            // Below is only runtime permission handling.
16621            if (!bp.isRuntime()) {
16622                continue;
16623            }
16624
16625            // Never clobber system or policy.
16626            if ((oldFlags & policyOrSystemFlags) != 0) {
16627                continue;
16628            }
16629
16630            // If this permission was granted by default, make sure it is.
16631            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16632                if (permissionsState.grantRuntimePermission(bp, userId)
16633                        != PERMISSION_OPERATION_FAILURE) {
16634                    writeRuntimePermissions = true;
16635                }
16636            // If permission review is enabled the permissions for a legacy apps
16637            // are represented as constantly granted runtime ones, so don't revoke.
16638            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16639                // Otherwise, reset the permission.
16640                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16641                switch (revokeResult) {
16642                    case PERMISSION_OPERATION_SUCCESS:
16643                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16644                        writeRuntimePermissions = true;
16645                        final int appId = ps.appId;
16646                        mHandler.post(new Runnable() {
16647                            @Override
16648                            public void run() {
16649                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16650                            }
16651                        });
16652                    } break;
16653                }
16654            }
16655        }
16656
16657        // Synchronously write as we are taking permissions away.
16658        if (writeRuntimePermissions) {
16659            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16660        }
16661
16662        // Synchronously write as we are taking permissions away.
16663        if (writeInstallPermissions) {
16664            mSettings.writeLPr();
16665        }
16666    }
16667
16668    /**
16669     * Remove entries from the keystore daemon. Will only remove it if the
16670     * {@code appId} is valid.
16671     */
16672    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16673        if (appId < 0) {
16674            return;
16675        }
16676
16677        final KeyStore keyStore = KeyStore.getInstance();
16678        if (keyStore != null) {
16679            if (userId == UserHandle.USER_ALL) {
16680                for (final int individual : sUserManager.getUserIds()) {
16681                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16682                }
16683            } else {
16684                keyStore.clearUid(UserHandle.getUid(userId, appId));
16685            }
16686        } else {
16687            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16688        }
16689    }
16690
16691    @Override
16692    public void deleteApplicationCacheFiles(final String packageName,
16693            final IPackageDataObserver observer) {
16694        final int userId = UserHandle.getCallingUserId();
16695        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16696    }
16697
16698    @Override
16699    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16700            final IPackageDataObserver observer) {
16701        mContext.enforceCallingOrSelfPermission(
16702                android.Manifest.permission.DELETE_CACHE_FILES, null);
16703        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16704                /* requireFullPermission= */ true, /* checkShell= */ false,
16705                "delete application cache files");
16706
16707        final PackageParser.Package pkg;
16708        synchronized (mPackages) {
16709            pkg = mPackages.get(packageName);
16710        }
16711
16712        // Queue up an async operation since the package deletion may take a little while.
16713        mHandler.post(new Runnable() {
16714            public void run() {
16715                synchronized (mInstallLock) {
16716                    final int flags = StorageManager.FLAG_STORAGE_DE
16717                            | StorageManager.FLAG_STORAGE_CE;
16718                    // We're only clearing cache files, so we don't care if the
16719                    // app is unfrozen and still able to run
16720                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16721                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16722                }
16723                clearExternalStorageDataSync(packageName, userId, false);
16724                if (observer != null) {
16725                    try {
16726                        observer.onRemoveCompleted(packageName, true);
16727                    } catch (RemoteException e) {
16728                        Log.i(TAG, "Observer no longer exists.");
16729                    }
16730                }
16731            }
16732        });
16733    }
16734
16735    @Override
16736    public void getPackageSizeInfo(final String packageName, int userHandle,
16737            final IPackageStatsObserver observer) {
16738        mContext.enforceCallingOrSelfPermission(
16739                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16740        if (packageName == null) {
16741            throw new IllegalArgumentException("Attempt to get size of null packageName");
16742        }
16743
16744        PackageStats stats = new PackageStats(packageName, userHandle);
16745
16746        /*
16747         * Queue up an async operation since the package measurement may take a
16748         * little while.
16749         */
16750        Message msg = mHandler.obtainMessage(INIT_COPY);
16751        msg.obj = new MeasureParams(stats, observer);
16752        mHandler.sendMessage(msg);
16753    }
16754
16755    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16756        final PackageSetting ps;
16757        synchronized (mPackages) {
16758            ps = mSettings.mPackages.get(packageName);
16759            if (ps == null) {
16760                Slog.w(TAG, "Failed to find settings for " + packageName);
16761                return false;
16762            }
16763        }
16764        try {
16765            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16766                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16767                    ps.getCeDataInode(userId), ps.codePathString, stats);
16768        } catch (InstallerException e) {
16769            Slog.w(TAG, String.valueOf(e));
16770            return false;
16771        }
16772
16773        // For now, ignore code size of packages on system partition
16774        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16775            stats.codeSize = 0;
16776        }
16777
16778        return true;
16779    }
16780
16781    private int getUidTargetSdkVersionLockedLPr(int uid) {
16782        Object obj = mSettings.getUserIdLPr(uid);
16783        if (obj instanceof SharedUserSetting) {
16784            final SharedUserSetting sus = (SharedUserSetting) obj;
16785            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16786            final Iterator<PackageSetting> it = sus.packages.iterator();
16787            while (it.hasNext()) {
16788                final PackageSetting ps = it.next();
16789                if (ps.pkg != null) {
16790                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16791                    if (v < vers) vers = v;
16792                }
16793            }
16794            return vers;
16795        } else if (obj instanceof PackageSetting) {
16796            final PackageSetting ps = (PackageSetting) obj;
16797            if (ps.pkg != null) {
16798                return ps.pkg.applicationInfo.targetSdkVersion;
16799            }
16800        }
16801        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16802    }
16803
16804    @Override
16805    public void addPreferredActivity(IntentFilter filter, int match,
16806            ComponentName[] set, ComponentName activity, int userId) {
16807        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16808                "Adding preferred");
16809    }
16810
16811    private void addPreferredActivityInternal(IntentFilter filter, int match,
16812            ComponentName[] set, ComponentName activity, boolean always, int userId,
16813            String opname) {
16814        // writer
16815        int callingUid = Binder.getCallingUid();
16816        enforceCrossUserPermission(callingUid, userId,
16817                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16818        if (filter.countActions() == 0) {
16819            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16820            return;
16821        }
16822        synchronized (mPackages) {
16823            if (mContext.checkCallingOrSelfPermission(
16824                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16825                    != PackageManager.PERMISSION_GRANTED) {
16826                if (getUidTargetSdkVersionLockedLPr(callingUid)
16827                        < Build.VERSION_CODES.FROYO) {
16828                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16829                            + callingUid);
16830                    return;
16831                }
16832                mContext.enforceCallingOrSelfPermission(
16833                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16834            }
16835
16836            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16837            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16838                    + userId + ":");
16839            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16840            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16841            scheduleWritePackageRestrictionsLocked(userId);
16842            postPreferredActivityChangedBroadcast(userId);
16843        }
16844    }
16845
16846    private void postPreferredActivityChangedBroadcast(int userId) {
16847        mHandler.post(() -> {
16848            final IActivityManager am = ActivityManagerNative.getDefault();
16849            if (am == null) {
16850                return;
16851            }
16852
16853            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16854            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16855            try {
16856                am.broadcastIntent(null, intent, null, null,
16857                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
16858                        null, false, false, userId);
16859            } catch (RemoteException e) {
16860            }
16861        });
16862    }
16863
16864    @Override
16865    public void replacePreferredActivity(IntentFilter filter, int match,
16866            ComponentName[] set, ComponentName activity, int userId) {
16867        if (filter.countActions() != 1) {
16868            throw new IllegalArgumentException(
16869                    "replacePreferredActivity expects filter to have only 1 action.");
16870        }
16871        if (filter.countDataAuthorities() != 0
16872                || filter.countDataPaths() != 0
16873                || filter.countDataSchemes() > 1
16874                || filter.countDataTypes() != 0) {
16875            throw new IllegalArgumentException(
16876                    "replacePreferredActivity expects filter to have no data authorities, " +
16877                    "paths, or types; and at most one scheme.");
16878        }
16879
16880        final int callingUid = Binder.getCallingUid();
16881        enforceCrossUserPermission(callingUid, userId,
16882                true /* requireFullPermission */, false /* checkShell */,
16883                "replace preferred activity");
16884        synchronized (mPackages) {
16885            if (mContext.checkCallingOrSelfPermission(
16886                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16887                    != PackageManager.PERMISSION_GRANTED) {
16888                if (getUidTargetSdkVersionLockedLPr(callingUid)
16889                        < Build.VERSION_CODES.FROYO) {
16890                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16891                            + Binder.getCallingUid());
16892                    return;
16893                }
16894                mContext.enforceCallingOrSelfPermission(
16895                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16896            }
16897
16898            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16899            if (pir != null) {
16900                // Get all of the existing entries that exactly match this filter.
16901                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16902                if (existing != null && existing.size() == 1) {
16903                    PreferredActivity cur = existing.get(0);
16904                    if (DEBUG_PREFERRED) {
16905                        Slog.i(TAG, "Checking replace of preferred:");
16906                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16907                        if (!cur.mPref.mAlways) {
16908                            Slog.i(TAG, "  -- CUR; not mAlways!");
16909                        } else {
16910                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16911                            Slog.i(TAG, "  -- CUR: mSet="
16912                                    + Arrays.toString(cur.mPref.mSetComponents));
16913                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16914                            Slog.i(TAG, "  -- NEW: mMatch="
16915                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16916                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16917                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16918                        }
16919                    }
16920                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16921                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16922                            && cur.mPref.sameSet(set)) {
16923                        // Setting the preferred activity to what it happens to be already
16924                        if (DEBUG_PREFERRED) {
16925                            Slog.i(TAG, "Replacing with same preferred activity "
16926                                    + cur.mPref.mShortComponent + " for user "
16927                                    + userId + ":");
16928                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16929                        }
16930                        return;
16931                    }
16932                }
16933
16934                if (existing != null) {
16935                    if (DEBUG_PREFERRED) {
16936                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16937                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16938                    }
16939                    for (int i = 0; i < existing.size(); i++) {
16940                        PreferredActivity pa = existing.get(i);
16941                        if (DEBUG_PREFERRED) {
16942                            Slog.i(TAG, "Removing existing preferred activity "
16943                                    + pa.mPref.mComponent + ":");
16944                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16945                        }
16946                        pir.removeFilter(pa);
16947                    }
16948                }
16949            }
16950            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16951                    "Replacing preferred");
16952        }
16953    }
16954
16955    @Override
16956    public void clearPackagePreferredActivities(String packageName) {
16957        final int uid = Binder.getCallingUid();
16958        // writer
16959        synchronized (mPackages) {
16960            PackageParser.Package pkg = mPackages.get(packageName);
16961            if (pkg == null || pkg.applicationInfo.uid != uid) {
16962                if (mContext.checkCallingOrSelfPermission(
16963                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16964                        != PackageManager.PERMISSION_GRANTED) {
16965                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16966                            < Build.VERSION_CODES.FROYO) {
16967                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16968                                + Binder.getCallingUid());
16969                        return;
16970                    }
16971                    mContext.enforceCallingOrSelfPermission(
16972                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16973                }
16974            }
16975
16976            int user = UserHandle.getCallingUserId();
16977            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16978                scheduleWritePackageRestrictionsLocked(user);
16979            }
16980        }
16981    }
16982
16983    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16984    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16985        ArrayList<PreferredActivity> removed = null;
16986        boolean changed = false;
16987        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16988            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16989            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16990            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16991                continue;
16992            }
16993            Iterator<PreferredActivity> it = pir.filterIterator();
16994            while (it.hasNext()) {
16995                PreferredActivity pa = it.next();
16996                // Mark entry for removal only if it matches the package name
16997                // and the entry is of type "always".
16998                if (packageName == null ||
16999                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17000                                && pa.mPref.mAlways)) {
17001                    if (removed == null) {
17002                        removed = new ArrayList<PreferredActivity>();
17003                    }
17004                    removed.add(pa);
17005                }
17006            }
17007            if (removed != null) {
17008                for (int j=0; j<removed.size(); j++) {
17009                    PreferredActivity pa = removed.get(j);
17010                    pir.removeFilter(pa);
17011                }
17012                changed = true;
17013            }
17014        }
17015        if (changed) {
17016            postPreferredActivityChangedBroadcast(userId);
17017        }
17018        return changed;
17019    }
17020
17021    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17022    private void clearIntentFilterVerificationsLPw(int userId) {
17023        final int packageCount = mPackages.size();
17024        for (int i = 0; i < packageCount; i++) {
17025            PackageParser.Package pkg = mPackages.valueAt(i);
17026            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17027        }
17028    }
17029
17030    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17031    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17032        if (userId == UserHandle.USER_ALL) {
17033            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17034                    sUserManager.getUserIds())) {
17035                for (int oneUserId : sUserManager.getUserIds()) {
17036                    scheduleWritePackageRestrictionsLocked(oneUserId);
17037                }
17038            }
17039        } else {
17040            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17041                scheduleWritePackageRestrictionsLocked(userId);
17042            }
17043        }
17044    }
17045
17046    void clearDefaultBrowserIfNeeded(String packageName) {
17047        for (int oneUserId : sUserManager.getUserIds()) {
17048            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17049            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17050            if (packageName.equals(defaultBrowserPackageName)) {
17051                setDefaultBrowserPackageName(null, oneUserId);
17052            }
17053        }
17054    }
17055
17056    @Override
17057    public void resetApplicationPreferences(int userId) {
17058        mContext.enforceCallingOrSelfPermission(
17059                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17060        final long identity = Binder.clearCallingIdentity();
17061        // writer
17062        try {
17063            synchronized (mPackages) {
17064                clearPackagePreferredActivitiesLPw(null, userId);
17065                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17066                // TODO: We have to reset the default SMS and Phone. This requires
17067                // significant refactoring to keep all default apps in the package
17068                // manager (cleaner but more work) or have the services provide
17069                // callbacks to the package manager to request a default app reset.
17070                applyFactoryDefaultBrowserLPw(userId);
17071                clearIntentFilterVerificationsLPw(userId);
17072                primeDomainVerificationsLPw(userId);
17073                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17074                scheduleWritePackageRestrictionsLocked(userId);
17075            }
17076            resetNetworkPolicies(userId);
17077        } finally {
17078            Binder.restoreCallingIdentity(identity);
17079        }
17080    }
17081
17082    @Override
17083    public int getPreferredActivities(List<IntentFilter> outFilters,
17084            List<ComponentName> outActivities, String packageName) {
17085
17086        int num = 0;
17087        final int userId = UserHandle.getCallingUserId();
17088        // reader
17089        synchronized (mPackages) {
17090            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17091            if (pir != null) {
17092                final Iterator<PreferredActivity> it = pir.filterIterator();
17093                while (it.hasNext()) {
17094                    final PreferredActivity pa = it.next();
17095                    if (packageName == null
17096                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17097                                    && pa.mPref.mAlways)) {
17098                        if (outFilters != null) {
17099                            outFilters.add(new IntentFilter(pa));
17100                        }
17101                        if (outActivities != null) {
17102                            outActivities.add(pa.mPref.mComponent);
17103                        }
17104                    }
17105                }
17106            }
17107        }
17108
17109        return num;
17110    }
17111
17112    @Override
17113    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17114            int userId) {
17115        int callingUid = Binder.getCallingUid();
17116        if (callingUid != Process.SYSTEM_UID) {
17117            throw new SecurityException(
17118                    "addPersistentPreferredActivity can only be run by the system");
17119        }
17120        if (filter.countActions() == 0) {
17121            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17122            return;
17123        }
17124        synchronized (mPackages) {
17125            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17126                    ":");
17127            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17128            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17129                    new PersistentPreferredActivity(filter, activity));
17130            scheduleWritePackageRestrictionsLocked(userId);
17131            postPreferredActivityChangedBroadcast(userId);
17132        }
17133    }
17134
17135    @Override
17136    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17137        int callingUid = Binder.getCallingUid();
17138        if (callingUid != Process.SYSTEM_UID) {
17139            throw new SecurityException(
17140                    "clearPackagePersistentPreferredActivities can only be run by the system");
17141        }
17142        ArrayList<PersistentPreferredActivity> removed = null;
17143        boolean changed = false;
17144        synchronized (mPackages) {
17145            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17146                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17147                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17148                        .valueAt(i);
17149                if (userId != thisUserId) {
17150                    continue;
17151                }
17152                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17153                while (it.hasNext()) {
17154                    PersistentPreferredActivity ppa = it.next();
17155                    // Mark entry for removal only if it matches the package name.
17156                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17157                        if (removed == null) {
17158                            removed = new ArrayList<PersistentPreferredActivity>();
17159                        }
17160                        removed.add(ppa);
17161                    }
17162                }
17163                if (removed != null) {
17164                    for (int j=0; j<removed.size(); j++) {
17165                        PersistentPreferredActivity ppa = removed.get(j);
17166                        ppir.removeFilter(ppa);
17167                    }
17168                    changed = true;
17169                }
17170            }
17171
17172            if (changed) {
17173                scheduleWritePackageRestrictionsLocked(userId);
17174                postPreferredActivityChangedBroadcast(userId);
17175            }
17176        }
17177    }
17178
17179    /**
17180     * Common machinery for picking apart a restored XML blob and passing
17181     * it to a caller-supplied functor to be applied to the running system.
17182     */
17183    private void restoreFromXml(XmlPullParser parser, int userId,
17184            String expectedStartTag, BlobXmlRestorer functor)
17185            throws IOException, XmlPullParserException {
17186        int type;
17187        while ((type = parser.next()) != XmlPullParser.START_TAG
17188                && type != XmlPullParser.END_DOCUMENT) {
17189        }
17190        if (type != XmlPullParser.START_TAG) {
17191            // oops didn't find a start tag?!
17192            if (DEBUG_BACKUP) {
17193                Slog.e(TAG, "Didn't find start tag during restore");
17194            }
17195            return;
17196        }
17197Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17198        // this is supposed to be TAG_PREFERRED_BACKUP
17199        if (!expectedStartTag.equals(parser.getName())) {
17200            if (DEBUG_BACKUP) {
17201                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17202            }
17203            return;
17204        }
17205
17206        // skip interfering stuff, then we're aligned with the backing implementation
17207        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17208Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17209        functor.apply(parser, userId);
17210    }
17211
17212    private interface BlobXmlRestorer {
17213        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17214    }
17215
17216    /**
17217     * Non-Binder method, support for the backup/restore mechanism: write the
17218     * full set of preferred activities in its canonical XML format.  Returns the
17219     * XML output as a byte array, or null if there is none.
17220     */
17221    @Override
17222    public byte[] getPreferredActivityBackup(int userId) {
17223        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17224            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17225        }
17226
17227        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17228        try {
17229            final XmlSerializer serializer = new FastXmlSerializer();
17230            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17231            serializer.startDocument(null, true);
17232            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17233
17234            synchronized (mPackages) {
17235                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17236            }
17237
17238            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17239            serializer.endDocument();
17240            serializer.flush();
17241        } catch (Exception e) {
17242            if (DEBUG_BACKUP) {
17243                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17244            }
17245            return null;
17246        }
17247
17248        return dataStream.toByteArray();
17249    }
17250
17251    @Override
17252    public void restorePreferredActivities(byte[] backup, int userId) {
17253        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17254            throw new SecurityException("Only the system may call restorePreferredActivities()");
17255        }
17256
17257        try {
17258            final XmlPullParser parser = Xml.newPullParser();
17259            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17260            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17261                    new BlobXmlRestorer() {
17262                        @Override
17263                        public void apply(XmlPullParser parser, int userId)
17264                                throws XmlPullParserException, IOException {
17265                            synchronized (mPackages) {
17266                                mSettings.readPreferredActivitiesLPw(parser, userId);
17267                            }
17268                        }
17269                    } );
17270        } catch (Exception e) {
17271            if (DEBUG_BACKUP) {
17272                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17273            }
17274        }
17275    }
17276
17277    /**
17278     * Non-Binder method, support for the backup/restore mechanism: write the
17279     * default browser (etc) settings in its canonical XML format.  Returns the default
17280     * browser XML representation as a byte array, or null if there is none.
17281     */
17282    @Override
17283    public byte[] getDefaultAppsBackup(int userId) {
17284        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17285            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17286        }
17287
17288        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17289        try {
17290            final XmlSerializer serializer = new FastXmlSerializer();
17291            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17292            serializer.startDocument(null, true);
17293            serializer.startTag(null, TAG_DEFAULT_APPS);
17294
17295            synchronized (mPackages) {
17296                mSettings.writeDefaultAppsLPr(serializer, userId);
17297            }
17298
17299            serializer.endTag(null, TAG_DEFAULT_APPS);
17300            serializer.endDocument();
17301            serializer.flush();
17302        } catch (Exception e) {
17303            if (DEBUG_BACKUP) {
17304                Slog.e(TAG, "Unable to write default apps for backup", e);
17305            }
17306            return null;
17307        }
17308
17309        return dataStream.toByteArray();
17310    }
17311
17312    @Override
17313    public void restoreDefaultApps(byte[] backup, int userId) {
17314        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17315            throw new SecurityException("Only the system may call restoreDefaultApps()");
17316        }
17317
17318        try {
17319            final XmlPullParser parser = Xml.newPullParser();
17320            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17321            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17322                    new BlobXmlRestorer() {
17323                        @Override
17324                        public void apply(XmlPullParser parser, int userId)
17325                                throws XmlPullParserException, IOException {
17326                            synchronized (mPackages) {
17327                                mSettings.readDefaultAppsLPw(parser, userId);
17328                            }
17329                        }
17330                    } );
17331        } catch (Exception e) {
17332            if (DEBUG_BACKUP) {
17333                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17334            }
17335        }
17336    }
17337
17338    @Override
17339    public byte[] getIntentFilterVerificationBackup(int userId) {
17340        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17341            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17342        }
17343
17344        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17345        try {
17346            final XmlSerializer serializer = new FastXmlSerializer();
17347            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17348            serializer.startDocument(null, true);
17349            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17350
17351            synchronized (mPackages) {
17352                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17353            }
17354
17355            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17356            serializer.endDocument();
17357            serializer.flush();
17358        } catch (Exception e) {
17359            if (DEBUG_BACKUP) {
17360                Slog.e(TAG, "Unable to write default apps for backup", e);
17361            }
17362            return null;
17363        }
17364
17365        return dataStream.toByteArray();
17366    }
17367
17368    @Override
17369    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17370        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17371            throw new SecurityException("Only the system may call restorePreferredActivities()");
17372        }
17373
17374        try {
17375            final XmlPullParser parser = Xml.newPullParser();
17376            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17377            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17378                    new BlobXmlRestorer() {
17379                        @Override
17380                        public void apply(XmlPullParser parser, int userId)
17381                                throws XmlPullParserException, IOException {
17382                            synchronized (mPackages) {
17383                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17384                                mSettings.writeLPr();
17385                            }
17386                        }
17387                    } );
17388        } catch (Exception e) {
17389            if (DEBUG_BACKUP) {
17390                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17391            }
17392        }
17393    }
17394
17395    @Override
17396    public byte[] getPermissionGrantBackup(int userId) {
17397        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17398            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17399        }
17400
17401        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17402        try {
17403            final XmlSerializer serializer = new FastXmlSerializer();
17404            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17405            serializer.startDocument(null, true);
17406            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17407
17408            synchronized (mPackages) {
17409                serializeRuntimePermissionGrantsLPr(serializer, userId);
17410            }
17411
17412            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17413            serializer.endDocument();
17414            serializer.flush();
17415        } catch (Exception e) {
17416            if (DEBUG_BACKUP) {
17417                Slog.e(TAG, "Unable to write default apps for backup", e);
17418            }
17419            return null;
17420        }
17421
17422        return dataStream.toByteArray();
17423    }
17424
17425    @Override
17426    public void restorePermissionGrants(byte[] backup, int userId) {
17427        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17428            throw new SecurityException("Only the system may call restorePermissionGrants()");
17429        }
17430
17431        try {
17432            final XmlPullParser parser = Xml.newPullParser();
17433            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17434            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17435                    new BlobXmlRestorer() {
17436                        @Override
17437                        public void apply(XmlPullParser parser, int userId)
17438                                throws XmlPullParserException, IOException {
17439                            synchronized (mPackages) {
17440                                processRestoredPermissionGrantsLPr(parser, userId);
17441                            }
17442                        }
17443                    } );
17444        } catch (Exception e) {
17445            if (DEBUG_BACKUP) {
17446                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17447            }
17448        }
17449    }
17450
17451    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17452            throws IOException {
17453        serializer.startTag(null, TAG_ALL_GRANTS);
17454
17455        final int N = mSettings.mPackages.size();
17456        for (int i = 0; i < N; i++) {
17457            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17458            boolean pkgGrantsKnown = false;
17459
17460            PermissionsState packagePerms = ps.getPermissionsState();
17461
17462            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17463                final int grantFlags = state.getFlags();
17464                // only look at grants that are not system/policy fixed
17465                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17466                    final boolean isGranted = state.isGranted();
17467                    // And only back up the user-twiddled state bits
17468                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17469                        final String packageName = mSettings.mPackages.keyAt(i);
17470                        if (!pkgGrantsKnown) {
17471                            serializer.startTag(null, TAG_GRANT);
17472                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17473                            pkgGrantsKnown = true;
17474                        }
17475
17476                        final boolean userSet =
17477                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17478                        final boolean userFixed =
17479                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17480                        final boolean revoke =
17481                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17482
17483                        serializer.startTag(null, TAG_PERMISSION);
17484                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17485                        if (isGranted) {
17486                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17487                        }
17488                        if (userSet) {
17489                            serializer.attribute(null, ATTR_USER_SET, "true");
17490                        }
17491                        if (userFixed) {
17492                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17493                        }
17494                        if (revoke) {
17495                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17496                        }
17497                        serializer.endTag(null, TAG_PERMISSION);
17498                    }
17499                }
17500            }
17501
17502            if (pkgGrantsKnown) {
17503                serializer.endTag(null, TAG_GRANT);
17504            }
17505        }
17506
17507        serializer.endTag(null, TAG_ALL_GRANTS);
17508    }
17509
17510    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17511            throws XmlPullParserException, IOException {
17512        String pkgName = null;
17513        int outerDepth = parser.getDepth();
17514        int type;
17515        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17516                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17517            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17518                continue;
17519            }
17520
17521            final String tagName = parser.getName();
17522            if (tagName.equals(TAG_GRANT)) {
17523                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17524                if (DEBUG_BACKUP) {
17525                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17526                }
17527            } else if (tagName.equals(TAG_PERMISSION)) {
17528
17529                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17530                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17531
17532                int newFlagSet = 0;
17533                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17534                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17535                }
17536                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17537                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17538                }
17539                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17540                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17541                }
17542                if (DEBUG_BACKUP) {
17543                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17544                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17545                }
17546                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17547                if (ps != null) {
17548                    // Already installed so we apply the grant immediately
17549                    if (DEBUG_BACKUP) {
17550                        Slog.v(TAG, "        + already installed; applying");
17551                    }
17552                    PermissionsState perms = ps.getPermissionsState();
17553                    BasePermission bp = mSettings.mPermissions.get(permName);
17554                    if (bp != null) {
17555                        if (isGranted) {
17556                            perms.grantRuntimePermission(bp, userId);
17557                        }
17558                        if (newFlagSet != 0) {
17559                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17560                        }
17561                    }
17562                } else {
17563                    // Need to wait for post-restore install to apply the grant
17564                    if (DEBUG_BACKUP) {
17565                        Slog.v(TAG, "        - not yet installed; saving for later");
17566                    }
17567                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17568                            isGranted, newFlagSet, userId);
17569                }
17570            } else {
17571                PackageManagerService.reportSettingsProblem(Log.WARN,
17572                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17573                XmlUtils.skipCurrentTag(parser);
17574            }
17575        }
17576
17577        scheduleWriteSettingsLocked();
17578        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17579    }
17580
17581    @Override
17582    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17583            int sourceUserId, int targetUserId, int flags) {
17584        mContext.enforceCallingOrSelfPermission(
17585                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17586        int callingUid = Binder.getCallingUid();
17587        enforceOwnerRights(ownerPackage, callingUid);
17588        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17589        if (intentFilter.countActions() == 0) {
17590            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17591            return;
17592        }
17593        synchronized (mPackages) {
17594            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17595                    ownerPackage, targetUserId, flags);
17596            CrossProfileIntentResolver resolver =
17597                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17598            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17599            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17600            if (existing != null) {
17601                int size = existing.size();
17602                for (int i = 0; i < size; i++) {
17603                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17604                        return;
17605                    }
17606                }
17607            }
17608            resolver.addFilter(newFilter);
17609            scheduleWritePackageRestrictionsLocked(sourceUserId);
17610        }
17611    }
17612
17613    @Override
17614    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17615        mContext.enforceCallingOrSelfPermission(
17616                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17617        int callingUid = Binder.getCallingUid();
17618        enforceOwnerRights(ownerPackage, callingUid);
17619        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17620        synchronized (mPackages) {
17621            CrossProfileIntentResolver resolver =
17622                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17623            ArraySet<CrossProfileIntentFilter> set =
17624                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17625            for (CrossProfileIntentFilter filter : set) {
17626                if (filter.getOwnerPackage().equals(ownerPackage)) {
17627                    resolver.removeFilter(filter);
17628                }
17629            }
17630            scheduleWritePackageRestrictionsLocked(sourceUserId);
17631        }
17632    }
17633
17634    // Enforcing that callingUid is owning pkg on userId
17635    private void enforceOwnerRights(String pkg, int callingUid) {
17636        // The system owns everything.
17637        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17638            return;
17639        }
17640        int callingUserId = UserHandle.getUserId(callingUid);
17641        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17642        if (pi == null) {
17643            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17644                    + callingUserId);
17645        }
17646        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17647            throw new SecurityException("Calling uid " + callingUid
17648                    + " does not own package " + pkg);
17649        }
17650    }
17651
17652    @Override
17653    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17654        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17655    }
17656
17657    private Intent getHomeIntent() {
17658        Intent intent = new Intent(Intent.ACTION_MAIN);
17659        intent.addCategory(Intent.CATEGORY_HOME);
17660        intent.addCategory(Intent.CATEGORY_DEFAULT);
17661        return intent;
17662    }
17663
17664    private IntentFilter getHomeFilter() {
17665        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17666        filter.addCategory(Intent.CATEGORY_HOME);
17667        filter.addCategory(Intent.CATEGORY_DEFAULT);
17668        return filter;
17669    }
17670
17671    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17672            int userId) {
17673        Intent intent  = getHomeIntent();
17674        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17675                PackageManager.GET_META_DATA, userId);
17676        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17677                true, false, false, userId);
17678
17679        allHomeCandidates.clear();
17680        if (list != null) {
17681            for (ResolveInfo ri : list) {
17682                allHomeCandidates.add(ri);
17683            }
17684        }
17685        return (preferred == null || preferred.activityInfo == null)
17686                ? null
17687                : new ComponentName(preferred.activityInfo.packageName,
17688                        preferred.activityInfo.name);
17689    }
17690
17691    @Override
17692    public void setHomeActivity(ComponentName comp, int userId) {
17693        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17694        getHomeActivitiesAsUser(homeActivities, userId);
17695
17696        boolean found = false;
17697
17698        final int size = homeActivities.size();
17699        final ComponentName[] set = new ComponentName[size];
17700        for (int i = 0; i < size; i++) {
17701            final ResolveInfo candidate = homeActivities.get(i);
17702            final ActivityInfo info = candidate.activityInfo;
17703            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17704            set[i] = activityName;
17705            if (!found && activityName.equals(comp)) {
17706                found = true;
17707            }
17708        }
17709        if (!found) {
17710            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17711                    + userId);
17712        }
17713        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17714                set, comp, userId);
17715    }
17716
17717    private @Nullable String getSetupWizardPackageName() {
17718        final Intent intent = new Intent(Intent.ACTION_MAIN);
17719        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17720
17721        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17722                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17723                        | MATCH_DISABLED_COMPONENTS,
17724                UserHandle.myUserId());
17725        if (matches.size() == 1) {
17726            return matches.get(0).getComponentInfo().packageName;
17727        } else {
17728            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17729                    + ": matches=" + matches);
17730            return null;
17731        }
17732    }
17733
17734    @Override
17735    public void setApplicationEnabledSetting(String appPackageName,
17736            int newState, int flags, int userId, String callingPackage) {
17737        if (!sUserManager.exists(userId)) return;
17738        if (callingPackage == null) {
17739            callingPackage = Integer.toString(Binder.getCallingUid());
17740        }
17741        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17742    }
17743
17744    @Override
17745    public void setComponentEnabledSetting(ComponentName componentName,
17746            int newState, int flags, int userId) {
17747        if (!sUserManager.exists(userId)) return;
17748        setEnabledSetting(componentName.getPackageName(),
17749                componentName.getClassName(), newState, flags, userId, null);
17750    }
17751
17752    private void setEnabledSetting(final String packageName, String className, int newState,
17753            final int flags, int userId, String callingPackage) {
17754        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17755              || newState == COMPONENT_ENABLED_STATE_ENABLED
17756              || newState == COMPONENT_ENABLED_STATE_DISABLED
17757              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17758              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17759            throw new IllegalArgumentException("Invalid new component state: "
17760                    + newState);
17761        }
17762        PackageSetting pkgSetting;
17763        final int uid = Binder.getCallingUid();
17764        final int permission;
17765        if (uid == Process.SYSTEM_UID) {
17766            permission = PackageManager.PERMISSION_GRANTED;
17767        } else {
17768            permission = mContext.checkCallingOrSelfPermission(
17769                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17770        }
17771        enforceCrossUserPermission(uid, userId,
17772                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17773        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17774        boolean sendNow = false;
17775        boolean isApp = (className == null);
17776        String componentName = isApp ? packageName : className;
17777        int packageUid = -1;
17778        ArrayList<String> components;
17779
17780        // writer
17781        synchronized (mPackages) {
17782            pkgSetting = mSettings.mPackages.get(packageName);
17783            if (pkgSetting == null) {
17784                if (className == null) {
17785                    throw new IllegalArgumentException("Unknown package: " + packageName);
17786                }
17787                throw new IllegalArgumentException(
17788                        "Unknown component: " + packageName + "/" + className);
17789            }
17790        }
17791
17792        // Limit who can change which apps
17793        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17794            // Don't allow apps that don't have permission to modify other apps
17795            if (!allowedByPermission) {
17796                throw new SecurityException(
17797                        "Permission Denial: attempt to change component state from pid="
17798                        + Binder.getCallingPid()
17799                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17800            }
17801            // Don't allow changing protected packages.
17802            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17803                throw new SecurityException("Cannot disable a protected package: " + packageName);
17804            }
17805        }
17806
17807        synchronized (mPackages) {
17808            if (uid == Process.SHELL_UID) {
17809                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17810                int oldState = pkgSetting.getEnabled(userId);
17811                if (className == null
17812                    &&
17813                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17814                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17815                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17816                    &&
17817                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17818                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17819                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17820                    // ok
17821                } else {
17822                    throw new SecurityException(
17823                            "Shell cannot change component state for " + packageName + "/"
17824                            + className + " to " + newState);
17825                }
17826            }
17827            if (className == null) {
17828                // We're dealing with an application/package level state change
17829                if (pkgSetting.getEnabled(userId) == newState) {
17830                    // Nothing to do
17831                    return;
17832                }
17833                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17834                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17835                    // Don't care about who enables an app.
17836                    callingPackage = null;
17837                }
17838                pkgSetting.setEnabled(newState, userId, callingPackage);
17839                // pkgSetting.pkg.mSetEnabled = newState;
17840            } else {
17841                // We're dealing with a component level state change
17842                // First, verify that this is a valid class name.
17843                PackageParser.Package pkg = pkgSetting.pkg;
17844                if (pkg == null || !pkg.hasComponentClassName(className)) {
17845                    if (pkg != null &&
17846                            pkg.applicationInfo.targetSdkVersion >=
17847                                    Build.VERSION_CODES.JELLY_BEAN) {
17848                        throw new IllegalArgumentException("Component class " + className
17849                                + " does not exist in " + packageName);
17850                    } else {
17851                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17852                                + className + " does not exist in " + packageName);
17853                    }
17854                }
17855                switch (newState) {
17856                case COMPONENT_ENABLED_STATE_ENABLED:
17857                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17858                        return;
17859                    }
17860                    break;
17861                case COMPONENT_ENABLED_STATE_DISABLED:
17862                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17863                        return;
17864                    }
17865                    break;
17866                case COMPONENT_ENABLED_STATE_DEFAULT:
17867                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17868                        return;
17869                    }
17870                    break;
17871                default:
17872                    Slog.e(TAG, "Invalid new component state: " + newState);
17873                    return;
17874                }
17875            }
17876            scheduleWritePackageRestrictionsLocked(userId);
17877            components = mPendingBroadcasts.get(userId, packageName);
17878            final boolean newPackage = components == null;
17879            if (newPackage) {
17880                components = new ArrayList<String>();
17881            }
17882            if (!components.contains(componentName)) {
17883                components.add(componentName);
17884            }
17885            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17886                sendNow = true;
17887                // Purge entry from pending broadcast list if another one exists already
17888                // since we are sending one right away.
17889                mPendingBroadcasts.remove(userId, packageName);
17890            } else {
17891                if (newPackage) {
17892                    mPendingBroadcasts.put(userId, packageName, components);
17893                }
17894                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17895                    // Schedule a message
17896                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17897                }
17898            }
17899        }
17900
17901        long callingId = Binder.clearCallingIdentity();
17902        try {
17903            if (sendNow) {
17904                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17905                sendPackageChangedBroadcast(packageName,
17906                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17907            }
17908        } finally {
17909            Binder.restoreCallingIdentity(callingId);
17910        }
17911    }
17912
17913    @Override
17914    public void flushPackageRestrictionsAsUser(int userId) {
17915        if (!sUserManager.exists(userId)) {
17916            return;
17917        }
17918        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17919                false /* checkShell */, "flushPackageRestrictions");
17920        synchronized (mPackages) {
17921            mSettings.writePackageRestrictionsLPr(userId);
17922            mDirtyUsers.remove(userId);
17923            if (mDirtyUsers.isEmpty()) {
17924                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17925            }
17926        }
17927    }
17928
17929    private void sendPackageChangedBroadcast(String packageName,
17930            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17931        if (DEBUG_INSTALL)
17932            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17933                    + componentNames);
17934        Bundle extras = new Bundle(4);
17935        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17936        String nameList[] = new String[componentNames.size()];
17937        componentNames.toArray(nameList);
17938        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17939        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17940        extras.putInt(Intent.EXTRA_UID, packageUid);
17941        // If this is not reporting a change of the overall package, then only send it
17942        // to registered receivers.  We don't want to launch a swath of apps for every
17943        // little component state change.
17944        final int flags = !componentNames.contains(packageName)
17945                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17946        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17947                new int[] {UserHandle.getUserId(packageUid)});
17948    }
17949
17950    @Override
17951    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17952        if (!sUserManager.exists(userId)) return;
17953        final int uid = Binder.getCallingUid();
17954        final int permission = mContext.checkCallingOrSelfPermission(
17955                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17956        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17957        enforceCrossUserPermission(uid, userId,
17958                true /* requireFullPermission */, true /* checkShell */, "stop package");
17959        // writer
17960        synchronized (mPackages) {
17961            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17962                    allowedByPermission, uid, userId)) {
17963                scheduleWritePackageRestrictionsLocked(userId);
17964            }
17965        }
17966    }
17967
17968    @Override
17969    public String getInstallerPackageName(String packageName) {
17970        // reader
17971        synchronized (mPackages) {
17972            return mSettings.getInstallerPackageNameLPr(packageName);
17973        }
17974    }
17975
17976    public boolean isOrphaned(String packageName) {
17977        // reader
17978        synchronized (mPackages) {
17979            return mSettings.isOrphaned(packageName);
17980        }
17981    }
17982
17983    @Override
17984    public int getApplicationEnabledSetting(String packageName, int userId) {
17985        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17986        int uid = Binder.getCallingUid();
17987        enforceCrossUserPermission(uid, userId,
17988                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17989        // reader
17990        synchronized (mPackages) {
17991            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17992        }
17993    }
17994
17995    @Override
17996    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17997        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17998        int uid = Binder.getCallingUid();
17999        enforceCrossUserPermission(uid, userId,
18000                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18001        // reader
18002        synchronized (mPackages) {
18003            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18004        }
18005    }
18006
18007    @Override
18008    public void enterSafeMode() {
18009        enforceSystemOrRoot("Only the system can request entering safe mode");
18010
18011        if (!mSystemReady) {
18012            mSafeMode = true;
18013        }
18014    }
18015
18016    @Override
18017    public void systemReady() {
18018        mSystemReady = true;
18019
18020        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18021        // disabled after already being started.
18022        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18023                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18024
18025        // Read the compatibilty setting when the system is ready.
18026        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18027                mContext.getContentResolver(),
18028                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18029        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18030        if (DEBUG_SETTINGS) {
18031            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18032        }
18033
18034        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18035
18036        synchronized (mPackages) {
18037            // Verify that all of the preferred activity components actually
18038            // exist.  It is possible for applications to be updated and at
18039            // that point remove a previously declared activity component that
18040            // had been set as a preferred activity.  We try to clean this up
18041            // the next time we encounter that preferred activity, but it is
18042            // possible for the user flow to never be able to return to that
18043            // situation so here we do a sanity check to make sure we haven't
18044            // left any junk around.
18045            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18046            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18047                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18048                removed.clear();
18049                for (PreferredActivity pa : pir.filterSet()) {
18050                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18051                        removed.add(pa);
18052                    }
18053                }
18054                if (removed.size() > 0) {
18055                    for (int r=0; r<removed.size(); r++) {
18056                        PreferredActivity pa = removed.get(r);
18057                        Slog.w(TAG, "Removing dangling preferred activity: "
18058                                + pa.mPref.mComponent);
18059                        pir.removeFilter(pa);
18060                    }
18061                    mSettings.writePackageRestrictionsLPr(
18062                            mSettings.mPreferredActivities.keyAt(i));
18063                }
18064            }
18065
18066            for (int userId : UserManagerService.getInstance().getUserIds()) {
18067                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18068                    grantPermissionsUserIds = ArrayUtils.appendInt(
18069                            grantPermissionsUserIds, userId);
18070                }
18071            }
18072        }
18073        sUserManager.systemReady();
18074
18075        // If we upgraded grant all default permissions before kicking off.
18076        for (int userId : grantPermissionsUserIds) {
18077            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18078        }
18079
18080        // If we did not grant default permissions, we preload from this the
18081        // default permission exceptions lazily to ensure we don't hit the
18082        // disk on a new user creation.
18083        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18084            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18085        }
18086
18087        // Kick off any messages waiting for system ready
18088        if (mPostSystemReadyMessages != null) {
18089            for (Message msg : mPostSystemReadyMessages) {
18090                msg.sendToTarget();
18091            }
18092            mPostSystemReadyMessages = null;
18093        }
18094
18095        // Watch for external volumes that come and go over time
18096        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18097        storage.registerListener(mStorageListener);
18098
18099        mInstallerService.systemReady();
18100        mPackageDexOptimizer.systemReady();
18101
18102        MountServiceInternal mountServiceInternal = LocalServices.getService(
18103                MountServiceInternal.class);
18104        mountServiceInternal.addExternalStoragePolicy(
18105                new MountServiceInternal.ExternalStorageMountPolicy() {
18106            @Override
18107            public int getMountMode(int uid, String packageName) {
18108                if (Process.isIsolated(uid)) {
18109                    return Zygote.MOUNT_EXTERNAL_NONE;
18110                }
18111                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18112                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18113                }
18114                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18115                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18116                }
18117                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18118                    return Zygote.MOUNT_EXTERNAL_READ;
18119                }
18120                return Zygote.MOUNT_EXTERNAL_WRITE;
18121            }
18122
18123            @Override
18124            public boolean hasExternalStorage(int uid, String packageName) {
18125                return true;
18126            }
18127        });
18128
18129        // Now that we're mostly running, clean up stale users and apps
18130        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18131        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18132    }
18133
18134    @Override
18135    public boolean isSafeMode() {
18136        return mSafeMode;
18137    }
18138
18139    @Override
18140    public boolean hasSystemUidErrors() {
18141        return mHasSystemUidErrors;
18142    }
18143
18144    static String arrayToString(int[] array) {
18145        StringBuffer buf = new StringBuffer(128);
18146        buf.append('[');
18147        if (array != null) {
18148            for (int i=0; i<array.length; i++) {
18149                if (i > 0) buf.append(", ");
18150                buf.append(array[i]);
18151            }
18152        }
18153        buf.append(']');
18154        return buf.toString();
18155    }
18156
18157    static class DumpState {
18158        public static final int DUMP_LIBS = 1 << 0;
18159        public static final int DUMP_FEATURES = 1 << 1;
18160        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18161        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18162        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18163        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18164        public static final int DUMP_PERMISSIONS = 1 << 6;
18165        public static final int DUMP_PACKAGES = 1 << 7;
18166        public static final int DUMP_SHARED_USERS = 1 << 8;
18167        public static final int DUMP_MESSAGES = 1 << 9;
18168        public static final int DUMP_PROVIDERS = 1 << 10;
18169        public static final int DUMP_VERIFIERS = 1 << 11;
18170        public static final int DUMP_PREFERRED = 1 << 12;
18171        public static final int DUMP_PREFERRED_XML = 1 << 13;
18172        public static final int DUMP_KEYSETS = 1 << 14;
18173        public static final int DUMP_VERSION = 1 << 15;
18174        public static final int DUMP_INSTALLS = 1 << 16;
18175        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18176        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18177        public static final int DUMP_FROZEN = 1 << 19;
18178        public static final int DUMP_DEXOPT = 1 << 20;
18179        public static final int DUMP_COMPILER_STATS = 1 << 21;
18180
18181        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18182
18183        private int mTypes;
18184
18185        private int mOptions;
18186
18187        private boolean mTitlePrinted;
18188
18189        private SharedUserSetting mSharedUser;
18190
18191        public boolean isDumping(int type) {
18192            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18193                return true;
18194            }
18195
18196            return (mTypes & type) != 0;
18197        }
18198
18199        public void setDump(int type) {
18200            mTypes |= type;
18201        }
18202
18203        public boolean isOptionEnabled(int option) {
18204            return (mOptions & option) != 0;
18205        }
18206
18207        public void setOptionEnabled(int option) {
18208            mOptions |= option;
18209        }
18210
18211        public boolean onTitlePrinted() {
18212            final boolean printed = mTitlePrinted;
18213            mTitlePrinted = true;
18214            return printed;
18215        }
18216
18217        public boolean getTitlePrinted() {
18218            return mTitlePrinted;
18219        }
18220
18221        public void setTitlePrinted(boolean enabled) {
18222            mTitlePrinted = enabled;
18223        }
18224
18225        public SharedUserSetting getSharedUser() {
18226            return mSharedUser;
18227        }
18228
18229        public void setSharedUser(SharedUserSetting user) {
18230            mSharedUser = user;
18231        }
18232    }
18233
18234    @Override
18235    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18236            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18237        (new PackageManagerShellCommand(this)).exec(
18238                this, in, out, err, args, resultReceiver);
18239    }
18240
18241    @Override
18242    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18243        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18244                != PackageManager.PERMISSION_GRANTED) {
18245            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18246                    + Binder.getCallingPid()
18247                    + ", uid=" + Binder.getCallingUid()
18248                    + " without permission "
18249                    + android.Manifest.permission.DUMP);
18250            return;
18251        }
18252
18253        DumpState dumpState = new DumpState();
18254        boolean fullPreferred = false;
18255        boolean checkin = false;
18256
18257        String packageName = null;
18258        ArraySet<String> permissionNames = null;
18259
18260        int opti = 0;
18261        while (opti < args.length) {
18262            String opt = args[opti];
18263            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18264                break;
18265            }
18266            opti++;
18267
18268            if ("-a".equals(opt)) {
18269                // Right now we only know how to print all.
18270            } else if ("-h".equals(opt)) {
18271                pw.println("Package manager dump options:");
18272                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18273                pw.println("    --checkin: dump for a checkin");
18274                pw.println("    -f: print details of intent filters");
18275                pw.println("    -h: print this help");
18276                pw.println("  cmd may be one of:");
18277                pw.println("    l[ibraries]: list known shared libraries");
18278                pw.println("    f[eatures]: list device features");
18279                pw.println("    k[eysets]: print known keysets");
18280                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18281                pw.println("    perm[issions]: dump permissions");
18282                pw.println("    permission [name ...]: dump declaration and use of given permission");
18283                pw.println("    pref[erred]: print preferred package settings");
18284                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18285                pw.println("    prov[iders]: dump content providers");
18286                pw.println("    p[ackages]: dump installed packages");
18287                pw.println("    s[hared-users]: dump shared user IDs");
18288                pw.println("    m[essages]: print collected runtime messages");
18289                pw.println("    v[erifiers]: print package verifier info");
18290                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18291                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18292                pw.println("    version: print database version info");
18293                pw.println("    write: write current settings now");
18294                pw.println("    installs: details about install sessions");
18295                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18296                pw.println("    dexopt: dump dexopt state");
18297                pw.println("    compiler-stats: dump compiler statistics");
18298                pw.println("    <package.name>: info about given package");
18299                return;
18300            } else if ("--checkin".equals(opt)) {
18301                checkin = true;
18302            } else if ("-f".equals(opt)) {
18303                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18304            } else {
18305                pw.println("Unknown argument: " + opt + "; use -h for help");
18306            }
18307        }
18308
18309        // Is the caller requesting to dump a particular piece of data?
18310        if (opti < args.length) {
18311            String cmd = args[opti];
18312            opti++;
18313            // Is this a package name?
18314            if ("android".equals(cmd) || cmd.contains(".")) {
18315                packageName = cmd;
18316                // When dumping a single package, we always dump all of its
18317                // filter information since the amount of data will be reasonable.
18318                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18319            } else if ("check-permission".equals(cmd)) {
18320                if (opti >= args.length) {
18321                    pw.println("Error: check-permission missing permission argument");
18322                    return;
18323                }
18324                String perm = args[opti];
18325                opti++;
18326                if (opti >= args.length) {
18327                    pw.println("Error: check-permission missing package argument");
18328                    return;
18329                }
18330                String pkg = args[opti];
18331                opti++;
18332                int user = UserHandle.getUserId(Binder.getCallingUid());
18333                if (opti < args.length) {
18334                    try {
18335                        user = Integer.parseInt(args[opti]);
18336                    } catch (NumberFormatException e) {
18337                        pw.println("Error: check-permission user argument is not a number: "
18338                                + args[opti]);
18339                        return;
18340                    }
18341                }
18342                pw.println(checkPermission(perm, pkg, user));
18343                return;
18344            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18345                dumpState.setDump(DumpState.DUMP_LIBS);
18346            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18347                dumpState.setDump(DumpState.DUMP_FEATURES);
18348            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18349                if (opti >= args.length) {
18350                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18351                            | DumpState.DUMP_SERVICE_RESOLVERS
18352                            | DumpState.DUMP_RECEIVER_RESOLVERS
18353                            | DumpState.DUMP_CONTENT_RESOLVERS);
18354                } else {
18355                    while (opti < args.length) {
18356                        String name = args[opti];
18357                        if ("a".equals(name) || "activity".equals(name)) {
18358                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18359                        } else if ("s".equals(name) || "service".equals(name)) {
18360                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18361                        } else if ("r".equals(name) || "receiver".equals(name)) {
18362                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18363                        } else if ("c".equals(name) || "content".equals(name)) {
18364                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18365                        } else {
18366                            pw.println("Error: unknown resolver table type: " + name);
18367                            return;
18368                        }
18369                        opti++;
18370                    }
18371                }
18372            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18373                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18374            } else if ("permission".equals(cmd)) {
18375                if (opti >= args.length) {
18376                    pw.println("Error: permission requires permission name");
18377                    return;
18378                }
18379                permissionNames = new ArraySet<>();
18380                while (opti < args.length) {
18381                    permissionNames.add(args[opti]);
18382                    opti++;
18383                }
18384                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18385                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18386            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18387                dumpState.setDump(DumpState.DUMP_PREFERRED);
18388            } else if ("preferred-xml".equals(cmd)) {
18389                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18390                if (opti < args.length && "--full".equals(args[opti])) {
18391                    fullPreferred = true;
18392                    opti++;
18393                }
18394            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18395                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18396            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18397                dumpState.setDump(DumpState.DUMP_PACKAGES);
18398            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18399                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18400            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18401                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18402            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18403                dumpState.setDump(DumpState.DUMP_MESSAGES);
18404            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18405                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18406            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18407                    || "intent-filter-verifiers".equals(cmd)) {
18408                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18409            } else if ("version".equals(cmd)) {
18410                dumpState.setDump(DumpState.DUMP_VERSION);
18411            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18412                dumpState.setDump(DumpState.DUMP_KEYSETS);
18413            } else if ("installs".equals(cmd)) {
18414                dumpState.setDump(DumpState.DUMP_INSTALLS);
18415            } else if ("frozen".equals(cmd)) {
18416                dumpState.setDump(DumpState.DUMP_FROZEN);
18417            } else if ("dexopt".equals(cmd)) {
18418                dumpState.setDump(DumpState.DUMP_DEXOPT);
18419            } else if ("compiler-stats".equals(cmd)) {
18420                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18421            } else if ("write".equals(cmd)) {
18422                synchronized (mPackages) {
18423                    mSettings.writeLPr();
18424                    pw.println("Settings written.");
18425                    return;
18426                }
18427            }
18428        }
18429
18430        if (checkin) {
18431            pw.println("vers,1");
18432        }
18433
18434        // reader
18435        synchronized (mPackages) {
18436            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18437                if (!checkin) {
18438                    if (dumpState.onTitlePrinted())
18439                        pw.println();
18440                    pw.println("Database versions:");
18441                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18442                }
18443            }
18444
18445            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18446                if (!checkin) {
18447                    if (dumpState.onTitlePrinted())
18448                        pw.println();
18449                    pw.println("Verifiers:");
18450                    pw.print("  Required: ");
18451                    pw.print(mRequiredVerifierPackage);
18452                    pw.print(" (uid=");
18453                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18454                            UserHandle.USER_SYSTEM));
18455                    pw.println(")");
18456                } else if (mRequiredVerifierPackage != null) {
18457                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18458                    pw.print(",");
18459                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18460                            UserHandle.USER_SYSTEM));
18461                }
18462            }
18463
18464            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18465                    packageName == null) {
18466                if (mIntentFilterVerifierComponent != null) {
18467                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18468                    if (!checkin) {
18469                        if (dumpState.onTitlePrinted())
18470                            pw.println();
18471                        pw.println("Intent Filter Verifier:");
18472                        pw.print("  Using: ");
18473                        pw.print(verifierPackageName);
18474                        pw.print(" (uid=");
18475                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18476                                UserHandle.USER_SYSTEM));
18477                        pw.println(")");
18478                    } else if (verifierPackageName != null) {
18479                        pw.print("ifv,"); pw.print(verifierPackageName);
18480                        pw.print(",");
18481                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18482                                UserHandle.USER_SYSTEM));
18483                    }
18484                } else {
18485                    pw.println();
18486                    pw.println("No Intent Filter Verifier available!");
18487                }
18488            }
18489
18490            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18491                boolean printedHeader = false;
18492                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18493                while (it.hasNext()) {
18494                    String name = it.next();
18495                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18496                    if (!checkin) {
18497                        if (!printedHeader) {
18498                            if (dumpState.onTitlePrinted())
18499                                pw.println();
18500                            pw.println("Libraries:");
18501                            printedHeader = true;
18502                        }
18503                        pw.print("  ");
18504                    } else {
18505                        pw.print("lib,");
18506                    }
18507                    pw.print(name);
18508                    if (!checkin) {
18509                        pw.print(" -> ");
18510                    }
18511                    if (ent.path != null) {
18512                        if (!checkin) {
18513                            pw.print("(jar) ");
18514                            pw.print(ent.path);
18515                        } else {
18516                            pw.print(",jar,");
18517                            pw.print(ent.path);
18518                        }
18519                    } else {
18520                        if (!checkin) {
18521                            pw.print("(apk) ");
18522                            pw.print(ent.apk);
18523                        } else {
18524                            pw.print(",apk,");
18525                            pw.print(ent.apk);
18526                        }
18527                    }
18528                    pw.println();
18529                }
18530            }
18531
18532            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18533                if (dumpState.onTitlePrinted())
18534                    pw.println();
18535                if (!checkin) {
18536                    pw.println("Features:");
18537                }
18538
18539                for (FeatureInfo feat : mAvailableFeatures.values()) {
18540                    if (checkin) {
18541                        pw.print("feat,");
18542                        pw.print(feat.name);
18543                        pw.print(",");
18544                        pw.println(feat.version);
18545                    } else {
18546                        pw.print("  ");
18547                        pw.print(feat.name);
18548                        if (feat.version > 0) {
18549                            pw.print(" version=");
18550                            pw.print(feat.version);
18551                        }
18552                        pw.println();
18553                    }
18554                }
18555            }
18556
18557            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18558                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18559                        : "Activity Resolver Table:", "  ", packageName,
18560                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18561                    dumpState.setTitlePrinted(true);
18562                }
18563            }
18564            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18565                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18566                        : "Receiver Resolver Table:", "  ", packageName,
18567                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18568                    dumpState.setTitlePrinted(true);
18569                }
18570            }
18571            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18572                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18573                        : "Service Resolver Table:", "  ", packageName,
18574                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18575                    dumpState.setTitlePrinted(true);
18576                }
18577            }
18578            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18579                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18580                        : "Provider Resolver Table:", "  ", packageName,
18581                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18582                    dumpState.setTitlePrinted(true);
18583                }
18584            }
18585
18586            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18587                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18588                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18589                    int user = mSettings.mPreferredActivities.keyAt(i);
18590                    if (pir.dump(pw,
18591                            dumpState.getTitlePrinted()
18592                                ? "\nPreferred Activities User " + user + ":"
18593                                : "Preferred Activities User " + user + ":", "  ",
18594                            packageName, true, false)) {
18595                        dumpState.setTitlePrinted(true);
18596                    }
18597                }
18598            }
18599
18600            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18601                pw.flush();
18602                FileOutputStream fout = new FileOutputStream(fd);
18603                BufferedOutputStream str = new BufferedOutputStream(fout);
18604                XmlSerializer serializer = new FastXmlSerializer();
18605                try {
18606                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18607                    serializer.startDocument(null, true);
18608                    serializer.setFeature(
18609                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18610                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18611                    serializer.endDocument();
18612                    serializer.flush();
18613                } catch (IllegalArgumentException e) {
18614                    pw.println("Failed writing: " + e);
18615                } catch (IllegalStateException e) {
18616                    pw.println("Failed writing: " + e);
18617                } catch (IOException e) {
18618                    pw.println("Failed writing: " + e);
18619                }
18620            }
18621
18622            if (!checkin
18623                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18624                    && packageName == null) {
18625                pw.println();
18626                int count = mSettings.mPackages.size();
18627                if (count == 0) {
18628                    pw.println("No applications!");
18629                    pw.println();
18630                } else {
18631                    final String prefix = "  ";
18632                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18633                    if (allPackageSettings.size() == 0) {
18634                        pw.println("No domain preferred apps!");
18635                        pw.println();
18636                    } else {
18637                        pw.println("App verification status:");
18638                        pw.println();
18639                        count = 0;
18640                        for (PackageSetting ps : allPackageSettings) {
18641                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18642                            if (ivi == null || ivi.getPackageName() == null) continue;
18643                            pw.println(prefix + "Package: " + ivi.getPackageName());
18644                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18645                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18646                            pw.println();
18647                            count++;
18648                        }
18649                        if (count == 0) {
18650                            pw.println(prefix + "No app verification established.");
18651                            pw.println();
18652                        }
18653                        for (int userId : sUserManager.getUserIds()) {
18654                            pw.println("App linkages for user " + userId + ":");
18655                            pw.println();
18656                            count = 0;
18657                            for (PackageSetting ps : allPackageSettings) {
18658                                final long status = ps.getDomainVerificationStatusForUser(userId);
18659                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18660                                    continue;
18661                                }
18662                                pw.println(prefix + "Package: " + ps.name);
18663                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18664                                String statusStr = IntentFilterVerificationInfo.
18665                                        getStatusStringFromValue(status);
18666                                pw.println(prefix + "Status:  " + statusStr);
18667                                pw.println();
18668                                count++;
18669                            }
18670                            if (count == 0) {
18671                                pw.println(prefix + "No configured app linkages.");
18672                                pw.println();
18673                            }
18674                        }
18675                    }
18676                }
18677            }
18678
18679            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18680                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18681                if (packageName == null && permissionNames == null) {
18682                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18683                        if (iperm == 0) {
18684                            if (dumpState.onTitlePrinted())
18685                                pw.println();
18686                            pw.println("AppOp Permissions:");
18687                        }
18688                        pw.print("  AppOp Permission ");
18689                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18690                        pw.println(":");
18691                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18692                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18693                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18694                        }
18695                    }
18696                }
18697            }
18698
18699            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18700                boolean printedSomething = false;
18701                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18702                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18703                        continue;
18704                    }
18705                    if (!printedSomething) {
18706                        if (dumpState.onTitlePrinted())
18707                            pw.println();
18708                        pw.println("Registered ContentProviders:");
18709                        printedSomething = true;
18710                    }
18711                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18712                    pw.print("    "); pw.println(p.toString());
18713                }
18714                printedSomething = false;
18715                for (Map.Entry<String, PackageParser.Provider> entry :
18716                        mProvidersByAuthority.entrySet()) {
18717                    PackageParser.Provider p = entry.getValue();
18718                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18719                        continue;
18720                    }
18721                    if (!printedSomething) {
18722                        if (dumpState.onTitlePrinted())
18723                            pw.println();
18724                        pw.println("ContentProvider Authorities:");
18725                        printedSomething = true;
18726                    }
18727                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18728                    pw.print("    "); pw.println(p.toString());
18729                    if (p.info != null && p.info.applicationInfo != null) {
18730                        final String appInfo = p.info.applicationInfo.toString();
18731                        pw.print("      applicationInfo="); pw.println(appInfo);
18732                    }
18733                }
18734            }
18735
18736            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18737                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18738            }
18739
18740            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18741                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18742            }
18743
18744            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18745                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18746            }
18747
18748            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18749                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18750            }
18751
18752            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18753                // XXX should handle packageName != null by dumping only install data that
18754                // the given package is involved with.
18755                if (dumpState.onTitlePrinted()) pw.println();
18756                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18757            }
18758
18759            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18760                // XXX should handle packageName != null by dumping only install data that
18761                // the given package is involved with.
18762                if (dumpState.onTitlePrinted()) pw.println();
18763
18764                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18765                ipw.println();
18766                ipw.println("Frozen packages:");
18767                ipw.increaseIndent();
18768                if (mFrozenPackages.size() == 0) {
18769                    ipw.println("(none)");
18770                } else {
18771                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18772                        ipw.println(mFrozenPackages.valueAt(i));
18773                    }
18774                }
18775                ipw.decreaseIndent();
18776            }
18777
18778            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18779                if (dumpState.onTitlePrinted()) pw.println();
18780                dumpDexoptStateLPr(pw, packageName);
18781            }
18782
18783            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18784                if (dumpState.onTitlePrinted()) pw.println();
18785                dumpCompilerStatsLPr(pw, packageName);
18786            }
18787
18788            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18789                if (dumpState.onTitlePrinted()) pw.println();
18790                mSettings.dumpReadMessagesLPr(pw, dumpState);
18791
18792                pw.println();
18793                pw.println("Package warning messages:");
18794                BufferedReader in = null;
18795                String line = null;
18796                try {
18797                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18798                    while ((line = in.readLine()) != null) {
18799                        if (line.contains("ignored: updated version")) continue;
18800                        pw.println(line);
18801                    }
18802                } catch (IOException ignored) {
18803                } finally {
18804                    IoUtils.closeQuietly(in);
18805                }
18806            }
18807
18808            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18809                BufferedReader in = null;
18810                String line = null;
18811                try {
18812                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18813                    while ((line = in.readLine()) != null) {
18814                        if (line.contains("ignored: updated version")) continue;
18815                        pw.print("msg,");
18816                        pw.println(line);
18817                    }
18818                } catch (IOException ignored) {
18819                } finally {
18820                    IoUtils.closeQuietly(in);
18821                }
18822            }
18823        }
18824    }
18825
18826    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18827        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18828        ipw.println();
18829        ipw.println("Dexopt state:");
18830        ipw.increaseIndent();
18831        Collection<PackageParser.Package> packages = null;
18832        if (packageName != null) {
18833            PackageParser.Package targetPackage = mPackages.get(packageName);
18834            if (targetPackage != null) {
18835                packages = Collections.singletonList(targetPackage);
18836            } else {
18837                ipw.println("Unable to find package: " + packageName);
18838                return;
18839            }
18840        } else {
18841            packages = mPackages.values();
18842        }
18843
18844        for (PackageParser.Package pkg : packages) {
18845            ipw.println("[" + pkg.packageName + "]");
18846            ipw.increaseIndent();
18847            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18848            ipw.decreaseIndent();
18849        }
18850    }
18851
18852    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
18853        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18854        ipw.println();
18855        ipw.println("Compiler stats:");
18856        ipw.increaseIndent();
18857        Collection<PackageParser.Package> packages = null;
18858        if (packageName != null) {
18859            PackageParser.Package targetPackage = mPackages.get(packageName);
18860            if (targetPackage != null) {
18861                packages = Collections.singletonList(targetPackage);
18862            } else {
18863                ipw.println("Unable to find package: " + packageName);
18864                return;
18865            }
18866        } else {
18867            packages = mPackages.values();
18868        }
18869
18870        for (PackageParser.Package pkg : packages) {
18871            ipw.println("[" + pkg.packageName + "]");
18872            ipw.increaseIndent();
18873
18874            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
18875            if (stats == null) {
18876                ipw.println("(No recorded stats)");
18877            } else {
18878                stats.dump(ipw);
18879            }
18880            ipw.decreaseIndent();
18881        }
18882    }
18883
18884    private String dumpDomainString(String packageName) {
18885        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18886                .getList();
18887        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18888
18889        ArraySet<String> result = new ArraySet<>();
18890        if (iviList.size() > 0) {
18891            for (IntentFilterVerificationInfo ivi : iviList) {
18892                for (String host : ivi.getDomains()) {
18893                    result.add(host);
18894                }
18895            }
18896        }
18897        if (filters != null && filters.size() > 0) {
18898            for (IntentFilter filter : filters) {
18899                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18900                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18901                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18902                    result.addAll(filter.getHostsList());
18903                }
18904            }
18905        }
18906
18907        StringBuilder sb = new StringBuilder(result.size() * 16);
18908        for (String domain : result) {
18909            if (sb.length() > 0) sb.append(" ");
18910            sb.append(domain);
18911        }
18912        return sb.toString();
18913    }
18914
18915    // ------- apps on sdcard specific code -------
18916    static final boolean DEBUG_SD_INSTALL = false;
18917
18918    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18919
18920    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18921
18922    private boolean mMediaMounted = false;
18923
18924    static String getEncryptKey() {
18925        try {
18926            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18927                    SD_ENCRYPTION_KEYSTORE_NAME);
18928            if (sdEncKey == null) {
18929                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18930                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18931                if (sdEncKey == null) {
18932                    Slog.e(TAG, "Failed to create encryption keys");
18933                    return null;
18934                }
18935            }
18936            return sdEncKey;
18937        } catch (NoSuchAlgorithmException nsae) {
18938            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18939            return null;
18940        } catch (IOException ioe) {
18941            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18942            return null;
18943        }
18944    }
18945
18946    /*
18947     * Update media status on PackageManager.
18948     */
18949    @Override
18950    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18951        int callingUid = Binder.getCallingUid();
18952        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18953            throw new SecurityException("Media status can only be updated by the system");
18954        }
18955        // reader; this apparently protects mMediaMounted, but should probably
18956        // be a different lock in that case.
18957        synchronized (mPackages) {
18958            Log.i(TAG, "Updating external media status from "
18959                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18960                    + (mediaStatus ? "mounted" : "unmounted"));
18961            if (DEBUG_SD_INSTALL)
18962                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18963                        + ", mMediaMounted=" + mMediaMounted);
18964            if (mediaStatus == mMediaMounted) {
18965                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18966                        : 0, -1);
18967                mHandler.sendMessage(msg);
18968                return;
18969            }
18970            mMediaMounted = mediaStatus;
18971        }
18972        // Queue up an async operation since the package installation may take a
18973        // little while.
18974        mHandler.post(new Runnable() {
18975            public void run() {
18976                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18977            }
18978        });
18979    }
18980
18981    /**
18982     * Called by MountService when the initial ASECs to scan are available.
18983     * Should block until all the ASEC containers are finished being scanned.
18984     */
18985    public void scanAvailableAsecs() {
18986        updateExternalMediaStatusInner(true, false, false);
18987    }
18988
18989    /*
18990     * Collect information of applications on external media, map them against
18991     * existing containers and update information based on current mount status.
18992     * Please note that we always have to report status if reportStatus has been
18993     * set to true especially when unloading packages.
18994     */
18995    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18996            boolean externalStorage) {
18997        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18998        int[] uidArr = EmptyArray.INT;
18999
19000        final String[] list = PackageHelper.getSecureContainerList();
19001        if (ArrayUtils.isEmpty(list)) {
19002            Log.i(TAG, "No secure containers found");
19003        } else {
19004            // Process list of secure containers and categorize them
19005            // as active or stale based on their package internal state.
19006
19007            // reader
19008            synchronized (mPackages) {
19009                for (String cid : list) {
19010                    // Leave stages untouched for now; installer service owns them
19011                    if (PackageInstallerService.isStageName(cid)) continue;
19012
19013                    if (DEBUG_SD_INSTALL)
19014                        Log.i(TAG, "Processing container " + cid);
19015                    String pkgName = getAsecPackageName(cid);
19016                    if (pkgName == null) {
19017                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19018                        continue;
19019                    }
19020                    if (DEBUG_SD_INSTALL)
19021                        Log.i(TAG, "Looking for pkg : " + pkgName);
19022
19023                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19024                    if (ps == null) {
19025                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19026                        continue;
19027                    }
19028
19029                    /*
19030                     * Skip packages that are not external if we're unmounting
19031                     * external storage.
19032                     */
19033                    if (externalStorage && !isMounted && !isExternal(ps)) {
19034                        continue;
19035                    }
19036
19037                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19038                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19039                    // The package status is changed only if the code path
19040                    // matches between settings and the container id.
19041                    if (ps.codePathString != null
19042                            && ps.codePathString.startsWith(args.getCodePath())) {
19043                        if (DEBUG_SD_INSTALL) {
19044                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19045                                    + " at code path: " + ps.codePathString);
19046                        }
19047
19048                        // We do have a valid package installed on sdcard
19049                        processCids.put(args, ps.codePathString);
19050                        final int uid = ps.appId;
19051                        if (uid != -1) {
19052                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19053                        }
19054                    } else {
19055                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19056                                + ps.codePathString);
19057                    }
19058                }
19059            }
19060
19061            Arrays.sort(uidArr);
19062        }
19063
19064        // Process packages with valid entries.
19065        if (isMounted) {
19066            if (DEBUG_SD_INSTALL)
19067                Log.i(TAG, "Loading packages");
19068            loadMediaPackages(processCids, uidArr, externalStorage);
19069            startCleaningPackages();
19070            mInstallerService.onSecureContainersAvailable();
19071        } else {
19072            if (DEBUG_SD_INSTALL)
19073                Log.i(TAG, "Unloading packages");
19074            unloadMediaPackages(processCids, uidArr, reportStatus);
19075        }
19076    }
19077
19078    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19079            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19080        final int size = infos.size();
19081        final String[] packageNames = new String[size];
19082        final int[] packageUids = new int[size];
19083        for (int i = 0; i < size; i++) {
19084            final ApplicationInfo info = infos.get(i);
19085            packageNames[i] = info.packageName;
19086            packageUids[i] = info.uid;
19087        }
19088        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19089                finishedReceiver);
19090    }
19091
19092    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19093            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19094        sendResourcesChangedBroadcast(mediaStatus, replacing,
19095                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19096    }
19097
19098    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19099            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19100        int size = pkgList.length;
19101        if (size > 0) {
19102            // Send broadcasts here
19103            Bundle extras = new Bundle();
19104            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19105            if (uidArr != null) {
19106                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19107            }
19108            if (replacing) {
19109                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19110            }
19111            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19112                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19113            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19114        }
19115    }
19116
19117   /*
19118     * Look at potentially valid container ids from processCids If package
19119     * information doesn't match the one on record or package scanning fails,
19120     * the cid is added to list of removeCids. We currently don't delete stale
19121     * containers.
19122     */
19123    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19124            boolean externalStorage) {
19125        ArrayList<String> pkgList = new ArrayList<String>();
19126        Set<AsecInstallArgs> keys = processCids.keySet();
19127
19128        for (AsecInstallArgs args : keys) {
19129            String codePath = processCids.get(args);
19130            if (DEBUG_SD_INSTALL)
19131                Log.i(TAG, "Loading container : " + args.cid);
19132            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19133            try {
19134                // Make sure there are no container errors first.
19135                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19136                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19137                            + " when installing from sdcard");
19138                    continue;
19139                }
19140                // Check code path here.
19141                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19142                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19143                            + " does not match one in settings " + codePath);
19144                    continue;
19145                }
19146                // Parse package
19147                int parseFlags = mDefParseFlags;
19148                if (args.isExternalAsec()) {
19149                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19150                }
19151                if (args.isFwdLocked()) {
19152                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19153                }
19154
19155                synchronized (mInstallLock) {
19156                    PackageParser.Package pkg = null;
19157                    try {
19158                        // Sadly we don't know the package name yet to freeze it
19159                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19160                                SCAN_IGNORE_FROZEN, 0, null);
19161                    } catch (PackageManagerException e) {
19162                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19163                    }
19164                    // Scan the package
19165                    if (pkg != null) {
19166                        /*
19167                         * TODO why is the lock being held? doPostInstall is
19168                         * called in other places without the lock. This needs
19169                         * to be straightened out.
19170                         */
19171                        // writer
19172                        synchronized (mPackages) {
19173                            retCode = PackageManager.INSTALL_SUCCEEDED;
19174                            pkgList.add(pkg.packageName);
19175                            // Post process args
19176                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19177                                    pkg.applicationInfo.uid);
19178                        }
19179                    } else {
19180                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19181                    }
19182                }
19183
19184            } finally {
19185                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19186                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19187                }
19188            }
19189        }
19190        // writer
19191        synchronized (mPackages) {
19192            // If the platform SDK has changed since the last time we booted,
19193            // we need to re-grant app permission to catch any new ones that
19194            // appear. This is really a hack, and means that apps can in some
19195            // cases get permissions that the user didn't initially explicitly
19196            // allow... it would be nice to have some better way to handle
19197            // this situation.
19198            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19199                    : mSettings.getInternalVersion();
19200            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19201                    : StorageManager.UUID_PRIVATE_INTERNAL;
19202
19203            int updateFlags = UPDATE_PERMISSIONS_ALL;
19204            if (ver.sdkVersion != mSdkVersion) {
19205                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19206                        + mSdkVersion + "; regranting permissions for external");
19207                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19208            }
19209            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19210
19211            // Yay, everything is now upgraded
19212            ver.forceCurrent();
19213
19214            // can downgrade to reader
19215            // Persist settings
19216            mSettings.writeLPr();
19217        }
19218        // Send a broadcast to let everyone know we are done processing
19219        if (pkgList.size() > 0) {
19220            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19221        }
19222    }
19223
19224   /*
19225     * Utility method to unload a list of specified containers
19226     */
19227    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19228        // Just unmount all valid containers.
19229        for (AsecInstallArgs arg : cidArgs) {
19230            synchronized (mInstallLock) {
19231                arg.doPostDeleteLI(false);
19232           }
19233       }
19234   }
19235
19236    /*
19237     * Unload packages mounted on external media. This involves deleting package
19238     * data from internal structures, sending broadcasts about disabled packages,
19239     * gc'ing to free up references, unmounting all secure containers
19240     * corresponding to packages on external media, and posting a
19241     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19242     * that we always have to post this message if status has been requested no
19243     * matter what.
19244     */
19245    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19246            final boolean reportStatus) {
19247        if (DEBUG_SD_INSTALL)
19248            Log.i(TAG, "unloading media packages");
19249        ArrayList<String> pkgList = new ArrayList<String>();
19250        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19251        final Set<AsecInstallArgs> keys = processCids.keySet();
19252        for (AsecInstallArgs args : keys) {
19253            String pkgName = args.getPackageName();
19254            if (DEBUG_SD_INSTALL)
19255                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19256            // Delete package internally
19257            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19258            synchronized (mInstallLock) {
19259                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19260                final boolean res;
19261                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19262                        "unloadMediaPackages")) {
19263                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19264                            null);
19265                }
19266                if (res) {
19267                    pkgList.add(pkgName);
19268                } else {
19269                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19270                    failedList.add(args);
19271                }
19272            }
19273        }
19274
19275        // reader
19276        synchronized (mPackages) {
19277            // We didn't update the settings after removing each package;
19278            // write them now for all packages.
19279            mSettings.writeLPr();
19280        }
19281
19282        // We have to absolutely send UPDATED_MEDIA_STATUS only
19283        // after confirming that all the receivers processed the ordered
19284        // broadcast when packages get disabled, force a gc to clean things up.
19285        // and unload all the containers.
19286        if (pkgList.size() > 0) {
19287            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19288                    new IIntentReceiver.Stub() {
19289                public void performReceive(Intent intent, int resultCode, String data,
19290                        Bundle extras, boolean ordered, boolean sticky,
19291                        int sendingUser) throws RemoteException {
19292                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19293                            reportStatus ? 1 : 0, 1, keys);
19294                    mHandler.sendMessage(msg);
19295                }
19296            });
19297        } else {
19298            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19299                    keys);
19300            mHandler.sendMessage(msg);
19301        }
19302    }
19303
19304    private void loadPrivatePackages(final VolumeInfo vol) {
19305        mHandler.post(new Runnable() {
19306            @Override
19307            public void run() {
19308                loadPrivatePackagesInner(vol);
19309            }
19310        });
19311    }
19312
19313    private void loadPrivatePackagesInner(VolumeInfo vol) {
19314        final String volumeUuid = vol.fsUuid;
19315        if (TextUtils.isEmpty(volumeUuid)) {
19316            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19317            return;
19318        }
19319
19320        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19321        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19322        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19323
19324        final VersionInfo ver;
19325        final List<PackageSetting> packages;
19326        synchronized (mPackages) {
19327            ver = mSettings.findOrCreateVersion(volumeUuid);
19328            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19329        }
19330
19331        for (PackageSetting ps : packages) {
19332            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19333            synchronized (mInstallLock) {
19334                final PackageParser.Package pkg;
19335                try {
19336                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19337                    loaded.add(pkg.applicationInfo);
19338
19339                } catch (PackageManagerException e) {
19340                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19341                }
19342
19343                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19344                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19345                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19346                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19347                }
19348            }
19349        }
19350
19351        // Reconcile app data for all started/unlocked users
19352        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19353        final UserManager um = mContext.getSystemService(UserManager.class);
19354        UserManagerInternal umInternal = getUserManagerInternal();
19355        for (UserInfo user : um.getUsers()) {
19356            final int flags;
19357            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19358                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19359            } else if (umInternal.isUserRunning(user.id)) {
19360                flags = StorageManager.FLAG_STORAGE_DE;
19361            } else {
19362                continue;
19363            }
19364
19365            try {
19366                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19367                synchronized (mInstallLock) {
19368                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19369                }
19370            } catch (IllegalStateException e) {
19371                // Device was probably ejected, and we'll process that event momentarily
19372                Slog.w(TAG, "Failed to prepare storage: " + e);
19373            }
19374        }
19375
19376        synchronized (mPackages) {
19377            int updateFlags = UPDATE_PERMISSIONS_ALL;
19378            if (ver.sdkVersion != mSdkVersion) {
19379                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19380                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19381                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19382            }
19383            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19384
19385            // Yay, everything is now upgraded
19386            ver.forceCurrent();
19387
19388            mSettings.writeLPr();
19389        }
19390
19391        for (PackageFreezer freezer : freezers) {
19392            freezer.close();
19393        }
19394
19395        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19396        sendResourcesChangedBroadcast(true, false, loaded, null);
19397    }
19398
19399    private void unloadPrivatePackages(final VolumeInfo vol) {
19400        mHandler.post(new Runnable() {
19401            @Override
19402            public void run() {
19403                unloadPrivatePackagesInner(vol);
19404            }
19405        });
19406    }
19407
19408    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19409        final String volumeUuid = vol.fsUuid;
19410        if (TextUtils.isEmpty(volumeUuid)) {
19411            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19412            return;
19413        }
19414
19415        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19416        synchronized (mInstallLock) {
19417        synchronized (mPackages) {
19418            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19419            for (PackageSetting ps : packages) {
19420                if (ps.pkg == null) continue;
19421
19422                final ApplicationInfo info = ps.pkg.applicationInfo;
19423                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19424                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19425
19426                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19427                        "unloadPrivatePackagesInner")) {
19428                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19429                            false, null)) {
19430                        unloaded.add(info);
19431                    } else {
19432                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19433                    }
19434                }
19435
19436                // Try very hard to release any references to this package
19437                // so we don't risk the system server being killed due to
19438                // open FDs
19439                AttributeCache.instance().removePackage(ps.name);
19440            }
19441
19442            mSettings.writeLPr();
19443        }
19444        }
19445
19446        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19447        sendResourcesChangedBroadcast(false, false, unloaded, null);
19448
19449        // Try very hard to release any references to this path so we don't risk
19450        // the system server being killed due to open FDs
19451        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19452
19453        for (int i = 0; i < 3; i++) {
19454            System.gc();
19455            System.runFinalization();
19456        }
19457    }
19458
19459    /**
19460     * Prepare storage areas for given user on all mounted devices.
19461     */
19462    void prepareUserData(int userId, int userSerial, int flags) {
19463        synchronized (mInstallLock) {
19464            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19465            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19466                final String volumeUuid = vol.getFsUuid();
19467                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19468            }
19469        }
19470    }
19471
19472    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19473            boolean allowRecover) {
19474        // Prepare storage and verify that serial numbers are consistent; if
19475        // there's a mismatch we need to destroy to avoid leaking data
19476        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19477        try {
19478            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19479
19480            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19481                UserManagerService.enforceSerialNumber(
19482                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19483                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19484                    UserManagerService.enforceSerialNumber(
19485                            Environment.getDataSystemDeDirectory(userId), userSerial);
19486                }
19487            }
19488            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19489                UserManagerService.enforceSerialNumber(
19490                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19491                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19492                    UserManagerService.enforceSerialNumber(
19493                            Environment.getDataSystemCeDirectory(userId), userSerial);
19494                }
19495            }
19496
19497            synchronized (mInstallLock) {
19498                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19499            }
19500        } catch (Exception e) {
19501            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19502                    + " because we failed to prepare: " + e);
19503            destroyUserDataLI(volumeUuid, userId,
19504                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19505
19506            if (allowRecover) {
19507                // Try one last time; if we fail again we're really in trouble
19508                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19509            }
19510        }
19511    }
19512
19513    /**
19514     * Destroy storage areas for given user on all mounted devices.
19515     */
19516    void destroyUserData(int userId, int flags) {
19517        synchronized (mInstallLock) {
19518            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19519            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19520                final String volumeUuid = vol.getFsUuid();
19521                destroyUserDataLI(volumeUuid, userId, flags);
19522            }
19523        }
19524    }
19525
19526    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19527        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19528        try {
19529            // Clean up app data, profile data, and media data
19530            mInstaller.destroyUserData(volumeUuid, userId, flags);
19531
19532            // Clean up system data
19533            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19534                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19535                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19536                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19537                }
19538                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19539                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19540                }
19541            }
19542
19543            // Data with special labels is now gone, so finish the job
19544            storage.destroyUserStorage(volumeUuid, userId, flags);
19545
19546        } catch (Exception e) {
19547            logCriticalInfo(Log.WARN,
19548                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19549        }
19550    }
19551
19552    /**
19553     * Examine all users present on given mounted volume, and destroy data
19554     * belonging to users that are no longer valid, or whose user ID has been
19555     * recycled.
19556     */
19557    private void reconcileUsers(String volumeUuid) {
19558        final List<File> files = new ArrayList<>();
19559        Collections.addAll(files, FileUtils
19560                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19561        Collections.addAll(files, FileUtils
19562                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19563        Collections.addAll(files, FileUtils
19564                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19565        Collections.addAll(files, FileUtils
19566                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19567        for (File file : files) {
19568            if (!file.isDirectory()) continue;
19569
19570            final int userId;
19571            final UserInfo info;
19572            try {
19573                userId = Integer.parseInt(file.getName());
19574                info = sUserManager.getUserInfo(userId);
19575            } catch (NumberFormatException e) {
19576                Slog.w(TAG, "Invalid user directory " + file);
19577                continue;
19578            }
19579
19580            boolean destroyUser = false;
19581            if (info == null) {
19582                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19583                        + " because no matching user was found");
19584                destroyUser = true;
19585            } else if (!mOnlyCore) {
19586                try {
19587                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19588                } catch (IOException e) {
19589                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19590                            + " because we failed to enforce serial number: " + e);
19591                    destroyUser = true;
19592                }
19593            }
19594
19595            if (destroyUser) {
19596                synchronized (mInstallLock) {
19597                    destroyUserDataLI(volumeUuid, userId,
19598                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19599                }
19600            }
19601        }
19602    }
19603
19604    private void assertPackageKnown(String volumeUuid, String packageName)
19605            throws PackageManagerException {
19606        synchronized (mPackages) {
19607            final PackageSetting ps = mSettings.mPackages.get(packageName);
19608            if (ps == null) {
19609                throw new PackageManagerException("Package " + packageName + " is unknown");
19610            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19611                throw new PackageManagerException(
19612                        "Package " + packageName + " found on unknown volume " + volumeUuid
19613                                + "; expected volume " + ps.volumeUuid);
19614            }
19615        }
19616    }
19617
19618    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19619            throws PackageManagerException {
19620        synchronized (mPackages) {
19621            final PackageSetting ps = mSettings.mPackages.get(packageName);
19622            if (ps == null) {
19623                throw new PackageManagerException("Package " + packageName + " is unknown");
19624            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19625                throw new PackageManagerException(
19626                        "Package " + packageName + " found on unknown volume " + volumeUuid
19627                                + "; expected volume " + ps.volumeUuid);
19628            } else if (!ps.getInstalled(userId)) {
19629                throw new PackageManagerException(
19630                        "Package " + packageName + " not installed for user " + userId);
19631            }
19632        }
19633    }
19634
19635    /**
19636     * Examine all apps present on given mounted volume, and destroy apps that
19637     * aren't expected, either due to uninstallation or reinstallation on
19638     * another volume.
19639     */
19640    private void reconcileApps(String volumeUuid) {
19641        final File[] files = FileUtils
19642                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19643        for (File file : files) {
19644            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19645                    && !PackageInstallerService.isStageName(file.getName());
19646            if (!isPackage) {
19647                // Ignore entries which are not packages
19648                continue;
19649            }
19650
19651            try {
19652                final PackageLite pkg = PackageParser.parsePackageLite(file,
19653                        PackageParser.PARSE_MUST_BE_APK);
19654                assertPackageKnown(volumeUuid, pkg.packageName);
19655
19656            } catch (PackageParserException | PackageManagerException e) {
19657                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19658                synchronized (mInstallLock) {
19659                    removeCodePathLI(file);
19660                }
19661            }
19662        }
19663    }
19664
19665    /**
19666     * Reconcile all app data for the given user.
19667     * <p>
19668     * Verifies that directories exist and that ownership and labeling is
19669     * correct for all installed apps on all mounted volumes.
19670     */
19671    void reconcileAppsData(int userId, int flags) {
19672        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19673        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19674            final String volumeUuid = vol.getFsUuid();
19675            synchronized (mInstallLock) {
19676                reconcileAppsDataLI(volumeUuid, userId, flags);
19677            }
19678        }
19679    }
19680
19681    /**
19682     * Reconcile all app data on given mounted volume.
19683     * <p>
19684     * Destroys app data that isn't expected, either due to uninstallation or
19685     * reinstallation on another volume.
19686     * <p>
19687     * Verifies that directories exist and that ownership and labeling is
19688     * correct for all installed apps.
19689     */
19690    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19691        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19692                + Integer.toHexString(flags));
19693
19694        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19695        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19696
19697        boolean restoreconNeeded = false;
19698
19699        // First look for stale data that doesn't belong, and check if things
19700        // have changed since we did our last restorecon
19701        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19702            if (StorageManager.isFileEncryptedNativeOrEmulated()
19703                    && !StorageManager.isUserKeyUnlocked(userId)) {
19704                throw new RuntimeException(
19705                        "Yikes, someone asked us to reconcile CE storage while " + userId
19706                                + " was still locked; this would have caused massive data loss!");
19707            }
19708
19709            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19710
19711            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19712            for (File file : files) {
19713                final String packageName = file.getName();
19714                try {
19715                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19716                } catch (PackageManagerException e) {
19717                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19718                    try {
19719                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19720                                StorageManager.FLAG_STORAGE_CE, 0);
19721                    } catch (InstallerException e2) {
19722                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19723                    }
19724                }
19725            }
19726        }
19727        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19728            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19729
19730            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19731            for (File file : files) {
19732                final String packageName = file.getName();
19733                try {
19734                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19735                } catch (PackageManagerException e) {
19736                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19737                    try {
19738                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19739                                StorageManager.FLAG_STORAGE_DE, 0);
19740                    } catch (InstallerException e2) {
19741                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19742                    }
19743                }
19744            }
19745        }
19746
19747        // Ensure that data directories are ready to roll for all packages
19748        // installed for this volume and user
19749        final List<PackageSetting> packages;
19750        synchronized (mPackages) {
19751            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19752        }
19753        int preparedCount = 0;
19754        for (PackageSetting ps : packages) {
19755            final String packageName = ps.name;
19756            if (ps.pkg == null) {
19757                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19758                // TODO: might be due to legacy ASEC apps; we should circle back
19759                // and reconcile again once they're scanned
19760                continue;
19761            }
19762
19763            if (ps.getInstalled(userId)) {
19764                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19765
19766                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19767                    // We may have just shuffled around app data directories, so
19768                    // prepare them one more time
19769                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19770                }
19771
19772                preparedCount++;
19773            }
19774        }
19775
19776        if (restoreconNeeded) {
19777            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19778                SELinuxMMAC.setRestoreconDone(ceDir);
19779            }
19780            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19781                SELinuxMMAC.setRestoreconDone(deDir);
19782            }
19783        }
19784
19785        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19786                + " packages; restoreconNeeded was " + restoreconNeeded);
19787    }
19788
19789    /**
19790     * Prepare app data for the given app just after it was installed or
19791     * upgraded. This method carefully only touches users that it's installed
19792     * for, and it forces a restorecon to handle any seinfo changes.
19793     * <p>
19794     * Verifies that directories exist and that ownership and labeling is
19795     * correct for all installed apps. If there is an ownership mismatch, it
19796     * will try recovering system apps by wiping data; third-party app data is
19797     * left intact.
19798     * <p>
19799     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19800     */
19801    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19802        final PackageSetting ps;
19803        synchronized (mPackages) {
19804            ps = mSettings.mPackages.get(pkg.packageName);
19805            mSettings.writeKernelMappingLPr(ps);
19806        }
19807
19808        final UserManager um = mContext.getSystemService(UserManager.class);
19809        UserManagerInternal umInternal = getUserManagerInternal();
19810        for (UserInfo user : um.getUsers()) {
19811            final int flags;
19812            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19813                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19814            } else if (umInternal.isUserRunning(user.id)) {
19815                flags = StorageManager.FLAG_STORAGE_DE;
19816            } else {
19817                continue;
19818            }
19819
19820            if (ps.getInstalled(user.id)) {
19821                // Whenever an app changes, force a restorecon of its data
19822                // TODO: when user data is locked, mark that we're still dirty
19823                prepareAppDataLIF(pkg, user.id, flags, true);
19824            }
19825        }
19826    }
19827
19828    /**
19829     * Prepare app data for the given app.
19830     * <p>
19831     * Verifies that directories exist and that ownership and labeling is
19832     * correct for all installed apps. If there is an ownership mismatch, this
19833     * will try recovering system apps by wiping data; third-party app data is
19834     * left intact.
19835     */
19836    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19837            boolean restoreconNeeded) {
19838        if (pkg == null) {
19839            Slog.wtf(TAG, "Package was null!", new Throwable());
19840            return;
19841        }
19842        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19843        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19844        for (int i = 0; i < childCount; i++) {
19845            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19846        }
19847    }
19848
19849    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19850            boolean restoreconNeeded) {
19851        if (DEBUG_APP_DATA) {
19852            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19853                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19854        }
19855
19856        final String volumeUuid = pkg.volumeUuid;
19857        final String packageName = pkg.packageName;
19858        final ApplicationInfo app = pkg.applicationInfo;
19859        final int appId = UserHandle.getAppId(app.uid);
19860
19861        Preconditions.checkNotNull(app.seinfo);
19862
19863        try {
19864            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19865                    appId, app.seinfo, app.targetSdkVersion);
19866        } catch (InstallerException e) {
19867            if (app.isSystemApp()) {
19868                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19869                        + ", but trying to recover: " + e);
19870                destroyAppDataLeafLIF(pkg, userId, flags);
19871                try {
19872                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19873                            appId, app.seinfo, app.targetSdkVersion);
19874                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19875                } catch (InstallerException e2) {
19876                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19877                }
19878            } else {
19879                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19880            }
19881        }
19882
19883        if (restoreconNeeded) {
19884            try {
19885                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19886                        app.seinfo);
19887            } catch (InstallerException e) {
19888                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19889            }
19890        }
19891
19892        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19893            try {
19894                // CE storage is unlocked right now, so read out the inode and
19895                // remember for use later when it's locked
19896                // TODO: mark this structure as dirty so we persist it!
19897                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19898                        StorageManager.FLAG_STORAGE_CE);
19899                synchronized (mPackages) {
19900                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19901                    if (ps != null) {
19902                        ps.setCeDataInode(ceDataInode, userId);
19903                    }
19904                }
19905            } catch (InstallerException e) {
19906                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19907            }
19908        }
19909
19910        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19911    }
19912
19913    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19914        if (pkg == null) {
19915            Slog.wtf(TAG, "Package was null!", new Throwable());
19916            return;
19917        }
19918        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19919        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19920        for (int i = 0; i < childCount; i++) {
19921            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19922        }
19923    }
19924
19925    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19926        final String volumeUuid = pkg.volumeUuid;
19927        final String packageName = pkg.packageName;
19928        final ApplicationInfo app = pkg.applicationInfo;
19929
19930        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19931            // Create a native library symlink only if we have native libraries
19932            // and if the native libraries are 32 bit libraries. We do not provide
19933            // this symlink for 64 bit libraries.
19934            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19935                final String nativeLibPath = app.nativeLibraryDir;
19936                try {
19937                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19938                            nativeLibPath, userId);
19939                } catch (InstallerException e) {
19940                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19941                }
19942            }
19943        }
19944    }
19945
19946    /**
19947     * For system apps on non-FBE devices, this method migrates any existing
19948     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19949     * requested by the app.
19950     */
19951    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19952        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19953                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19954            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19955                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19956            try {
19957                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19958                        storageTarget);
19959            } catch (InstallerException e) {
19960                logCriticalInfo(Log.WARN,
19961                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19962            }
19963            return true;
19964        } else {
19965            return false;
19966        }
19967    }
19968
19969    public PackageFreezer freezePackage(String packageName, String killReason) {
19970        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
19971    }
19972
19973    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
19974        return new PackageFreezer(packageName, userId, killReason);
19975    }
19976
19977    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19978            String killReason) {
19979        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
19980    }
19981
19982    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
19983            String killReason) {
19984        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19985            return new PackageFreezer();
19986        } else {
19987            return freezePackage(packageName, userId, killReason);
19988        }
19989    }
19990
19991    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19992            String killReason) {
19993        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
19994    }
19995
19996    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
19997            String killReason) {
19998        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19999            return new PackageFreezer();
20000        } else {
20001            return freezePackage(packageName, userId, killReason);
20002        }
20003    }
20004
20005    /**
20006     * Class that freezes and kills the given package upon creation, and
20007     * unfreezes it upon closing. This is typically used when doing surgery on
20008     * app code/data to prevent the app from running while you're working.
20009     */
20010    private class PackageFreezer implements AutoCloseable {
20011        private final String mPackageName;
20012        private final PackageFreezer[] mChildren;
20013
20014        private final boolean mWeFroze;
20015
20016        private final AtomicBoolean mClosed = new AtomicBoolean();
20017        private final CloseGuard mCloseGuard = CloseGuard.get();
20018
20019        /**
20020         * Create and return a stub freezer that doesn't actually do anything,
20021         * typically used when someone requested
20022         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20023         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20024         */
20025        public PackageFreezer() {
20026            mPackageName = null;
20027            mChildren = null;
20028            mWeFroze = false;
20029            mCloseGuard.open("close");
20030        }
20031
20032        public PackageFreezer(String packageName, int userId, String killReason) {
20033            synchronized (mPackages) {
20034                mPackageName = packageName;
20035                mWeFroze = mFrozenPackages.add(mPackageName);
20036
20037                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20038                if (ps != null) {
20039                    killApplication(ps.name, ps.appId, userId, killReason);
20040                }
20041
20042                final PackageParser.Package p = mPackages.get(packageName);
20043                if (p != null && p.childPackages != null) {
20044                    final int N = p.childPackages.size();
20045                    mChildren = new PackageFreezer[N];
20046                    for (int i = 0; i < N; i++) {
20047                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20048                                userId, killReason);
20049                    }
20050                } else {
20051                    mChildren = null;
20052                }
20053            }
20054            mCloseGuard.open("close");
20055        }
20056
20057        @Override
20058        protected void finalize() throws Throwable {
20059            try {
20060                mCloseGuard.warnIfOpen();
20061                close();
20062            } finally {
20063                super.finalize();
20064            }
20065        }
20066
20067        @Override
20068        public void close() {
20069            mCloseGuard.close();
20070            if (mClosed.compareAndSet(false, true)) {
20071                synchronized (mPackages) {
20072                    if (mWeFroze) {
20073                        mFrozenPackages.remove(mPackageName);
20074                    }
20075
20076                    if (mChildren != null) {
20077                        for (PackageFreezer freezer : mChildren) {
20078                            freezer.close();
20079                        }
20080                    }
20081                }
20082            }
20083        }
20084    }
20085
20086    /**
20087     * Verify that given package is currently frozen.
20088     */
20089    private void checkPackageFrozen(String packageName) {
20090        synchronized (mPackages) {
20091            if (!mFrozenPackages.contains(packageName)) {
20092                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20093            }
20094        }
20095    }
20096
20097    @Override
20098    public int movePackage(final String packageName, final String volumeUuid) {
20099        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20100
20101        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20102        final int moveId = mNextMoveId.getAndIncrement();
20103        mHandler.post(new Runnable() {
20104            @Override
20105            public void run() {
20106                try {
20107                    movePackageInternal(packageName, volumeUuid, moveId, user);
20108                } catch (PackageManagerException e) {
20109                    Slog.w(TAG, "Failed to move " + packageName, e);
20110                    mMoveCallbacks.notifyStatusChanged(moveId,
20111                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20112                }
20113            }
20114        });
20115        return moveId;
20116    }
20117
20118    private void movePackageInternal(final String packageName, final String volumeUuid,
20119            final int moveId, UserHandle user) throws PackageManagerException {
20120        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20121        final PackageManager pm = mContext.getPackageManager();
20122
20123        final boolean currentAsec;
20124        final String currentVolumeUuid;
20125        final File codeFile;
20126        final String installerPackageName;
20127        final String packageAbiOverride;
20128        final int appId;
20129        final String seinfo;
20130        final String label;
20131        final int targetSdkVersion;
20132        final PackageFreezer freezer;
20133        final int[] installedUserIds;
20134
20135        // reader
20136        synchronized (mPackages) {
20137            final PackageParser.Package pkg = mPackages.get(packageName);
20138            final PackageSetting ps = mSettings.mPackages.get(packageName);
20139            if (pkg == null || ps == null) {
20140                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20141            }
20142
20143            if (pkg.applicationInfo.isSystemApp()) {
20144                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20145                        "Cannot move system application");
20146            }
20147
20148            if (pkg.applicationInfo.isExternalAsec()) {
20149                currentAsec = true;
20150                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20151            } else if (pkg.applicationInfo.isForwardLocked()) {
20152                currentAsec = true;
20153                currentVolumeUuid = "forward_locked";
20154            } else {
20155                currentAsec = false;
20156                currentVolumeUuid = ps.volumeUuid;
20157
20158                final File probe = new File(pkg.codePath);
20159                final File probeOat = new File(probe, "oat");
20160                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20161                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20162                            "Move only supported for modern cluster style installs");
20163                }
20164            }
20165
20166            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20167                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20168                        "Package already moved to " + volumeUuid);
20169            }
20170            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20171                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20172                        "Device admin cannot be moved");
20173            }
20174
20175            if (mFrozenPackages.contains(packageName)) {
20176                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20177                        "Failed to move already frozen package");
20178            }
20179
20180            codeFile = new File(pkg.codePath);
20181            installerPackageName = ps.installerPackageName;
20182            packageAbiOverride = ps.cpuAbiOverrideString;
20183            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20184            seinfo = pkg.applicationInfo.seinfo;
20185            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20186            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20187            freezer = freezePackage(packageName, "movePackageInternal");
20188            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20189        }
20190
20191        final Bundle extras = new Bundle();
20192        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20193        extras.putString(Intent.EXTRA_TITLE, label);
20194        mMoveCallbacks.notifyCreated(moveId, extras);
20195
20196        int installFlags;
20197        final boolean moveCompleteApp;
20198        final File measurePath;
20199
20200        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20201            installFlags = INSTALL_INTERNAL;
20202            moveCompleteApp = !currentAsec;
20203            measurePath = Environment.getDataAppDirectory(volumeUuid);
20204        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20205            installFlags = INSTALL_EXTERNAL;
20206            moveCompleteApp = false;
20207            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20208        } else {
20209            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20210            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20211                    || !volume.isMountedWritable()) {
20212                freezer.close();
20213                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20214                        "Move location not mounted private volume");
20215            }
20216
20217            Preconditions.checkState(!currentAsec);
20218
20219            installFlags = INSTALL_INTERNAL;
20220            moveCompleteApp = true;
20221            measurePath = Environment.getDataAppDirectory(volumeUuid);
20222        }
20223
20224        final PackageStats stats = new PackageStats(null, -1);
20225        synchronized (mInstaller) {
20226            for (int userId : installedUserIds) {
20227                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20228                    freezer.close();
20229                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20230                            "Failed to measure package size");
20231                }
20232            }
20233        }
20234
20235        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20236                + stats.dataSize);
20237
20238        final long startFreeBytes = measurePath.getFreeSpace();
20239        final long sizeBytes;
20240        if (moveCompleteApp) {
20241            sizeBytes = stats.codeSize + stats.dataSize;
20242        } else {
20243            sizeBytes = stats.codeSize;
20244        }
20245
20246        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20247            freezer.close();
20248            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20249                    "Not enough free space to move");
20250        }
20251
20252        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20253
20254        final CountDownLatch installedLatch = new CountDownLatch(1);
20255        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20256            @Override
20257            public void onUserActionRequired(Intent intent) throws RemoteException {
20258                throw new IllegalStateException();
20259            }
20260
20261            @Override
20262            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20263                    Bundle extras) throws RemoteException {
20264                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20265                        + PackageManager.installStatusToString(returnCode, msg));
20266
20267                installedLatch.countDown();
20268                freezer.close();
20269
20270                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20271                switch (status) {
20272                    case PackageInstaller.STATUS_SUCCESS:
20273                        mMoveCallbacks.notifyStatusChanged(moveId,
20274                                PackageManager.MOVE_SUCCEEDED);
20275                        break;
20276                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20277                        mMoveCallbacks.notifyStatusChanged(moveId,
20278                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20279                        break;
20280                    default:
20281                        mMoveCallbacks.notifyStatusChanged(moveId,
20282                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20283                        break;
20284                }
20285            }
20286        };
20287
20288        final MoveInfo move;
20289        if (moveCompleteApp) {
20290            // Kick off a thread to report progress estimates
20291            new Thread() {
20292                @Override
20293                public void run() {
20294                    while (true) {
20295                        try {
20296                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20297                                break;
20298                            }
20299                        } catch (InterruptedException ignored) {
20300                        }
20301
20302                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20303                        final int progress = 10 + (int) MathUtils.constrain(
20304                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20305                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20306                    }
20307                }
20308            }.start();
20309
20310            final String dataAppName = codeFile.getName();
20311            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20312                    dataAppName, appId, seinfo, targetSdkVersion);
20313        } else {
20314            move = null;
20315        }
20316
20317        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20318
20319        final Message msg = mHandler.obtainMessage(INIT_COPY);
20320        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20321        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20322                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20323                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20324        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20325        msg.obj = params;
20326
20327        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20328                System.identityHashCode(msg.obj));
20329        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20330                System.identityHashCode(msg.obj));
20331
20332        mHandler.sendMessage(msg);
20333    }
20334
20335    @Override
20336    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20337        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20338
20339        final int realMoveId = mNextMoveId.getAndIncrement();
20340        final Bundle extras = new Bundle();
20341        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20342        mMoveCallbacks.notifyCreated(realMoveId, extras);
20343
20344        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20345            @Override
20346            public void onCreated(int moveId, Bundle extras) {
20347                // Ignored
20348            }
20349
20350            @Override
20351            public void onStatusChanged(int moveId, int status, long estMillis) {
20352                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20353            }
20354        };
20355
20356        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20357        storage.setPrimaryStorageUuid(volumeUuid, callback);
20358        return realMoveId;
20359    }
20360
20361    @Override
20362    public int getMoveStatus(int moveId) {
20363        mContext.enforceCallingOrSelfPermission(
20364                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20365        return mMoveCallbacks.mLastStatus.get(moveId);
20366    }
20367
20368    @Override
20369    public void registerMoveCallback(IPackageMoveObserver callback) {
20370        mContext.enforceCallingOrSelfPermission(
20371                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20372        mMoveCallbacks.register(callback);
20373    }
20374
20375    @Override
20376    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20377        mContext.enforceCallingOrSelfPermission(
20378                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20379        mMoveCallbacks.unregister(callback);
20380    }
20381
20382    @Override
20383    public boolean setInstallLocation(int loc) {
20384        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20385                null);
20386        if (getInstallLocation() == loc) {
20387            return true;
20388        }
20389        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20390                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20391            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20392                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20393            return true;
20394        }
20395        return false;
20396   }
20397
20398    @Override
20399    public int getInstallLocation() {
20400        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20401                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20402                PackageHelper.APP_INSTALL_AUTO);
20403    }
20404
20405    /** Called by UserManagerService */
20406    void cleanUpUser(UserManagerService userManager, int userHandle) {
20407        synchronized (mPackages) {
20408            mDirtyUsers.remove(userHandle);
20409            mUserNeedsBadging.delete(userHandle);
20410            mSettings.removeUserLPw(userHandle);
20411            mPendingBroadcasts.remove(userHandle);
20412            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20413            removeUnusedPackagesLPw(userManager, userHandle);
20414        }
20415    }
20416
20417    /**
20418     * We're removing userHandle and would like to remove any downloaded packages
20419     * that are no longer in use by any other user.
20420     * @param userHandle the user being removed
20421     */
20422    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20423        final boolean DEBUG_CLEAN_APKS = false;
20424        int [] users = userManager.getUserIds();
20425        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20426        while (psit.hasNext()) {
20427            PackageSetting ps = psit.next();
20428            if (ps.pkg == null) {
20429                continue;
20430            }
20431            final String packageName = ps.pkg.packageName;
20432            // Skip over if system app
20433            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20434                continue;
20435            }
20436            if (DEBUG_CLEAN_APKS) {
20437                Slog.i(TAG, "Checking package " + packageName);
20438            }
20439            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20440            if (keep) {
20441                if (DEBUG_CLEAN_APKS) {
20442                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20443                }
20444            } else {
20445                for (int i = 0; i < users.length; i++) {
20446                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20447                        keep = true;
20448                        if (DEBUG_CLEAN_APKS) {
20449                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20450                                    + users[i]);
20451                        }
20452                        break;
20453                    }
20454                }
20455            }
20456            if (!keep) {
20457                if (DEBUG_CLEAN_APKS) {
20458                    Slog.i(TAG, "  Removing package " + packageName);
20459                }
20460                mHandler.post(new Runnable() {
20461                    public void run() {
20462                        deletePackageX(packageName, userHandle, 0);
20463                    } //end run
20464                });
20465            }
20466        }
20467    }
20468
20469    /** Called by UserManagerService */
20470    void createNewUser(int userId) {
20471        synchronized (mInstallLock) {
20472            mSettings.createNewUserLI(this, mInstaller, userId);
20473        }
20474        synchronized (mPackages) {
20475            scheduleWritePackageRestrictionsLocked(userId);
20476            scheduleWritePackageListLocked(userId);
20477            applyFactoryDefaultBrowserLPw(userId);
20478            primeDomainVerificationsLPw(userId);
20479        }
20480    }
20481
20482    void onNewUserCreated(final int userId) {
20483        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20484        // If permission review for legacy apps is required, we represent
20485        // dagerous permissions for such apps as always granted runtime
20486        // permissions to keep per user flag state whether review is needed.
20487        // Hence, if a new user is added we have to propagate dangerous
20488        // permission grants for these legacy apps.
20489        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20490            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20491                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20492        }
20493    }
20494
20495    @Override
20496    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20497        mContext.enforceCallingOrSelfPermission(
20498                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20499                "Only package verification agents can read the verifier device identity");
20500
20501        synchronized (mPackages) {
20502            return mSettings.getVerifierDeviceIdentityLPw();
20503        }
20504    }
20505
20506    @Override
20507    public void setPermissionEnforced(String permission, boolean enforced) {
20508        // TODO: Now that we no longer change GID for storage, this should to away.
20509        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20510                "setPermissionEnforced");
20511        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20512            synchronized (mPackages) {
20513                if (mSettings.mReadExternalStorageEnforced == null
20514                        || mSettings.mReadExternalStorageEnforced != enforced) {
20515                    mSettings.mReadExternalStorageEnforced = enforced;
20516                    mSettings.writeLPr();
20517                }
20518            }
20519            // kill any non-foreground processes so we restart them and
20520            // grant/revoke the GID.
20521            final IActivityManager am = ActivityManagerNative.getDefault();
20522            if (am != null) {
20523                final long token = Binder.clearCallingIdentity();
20524                try {
20525                    am.killProcessesBelowForeground("setPermissionEnforcement");
20526                } catch (RemoteException e) {
20527                } finally {
20528                    Binder.restoreCallingIdentity(token);
20529                }
20530            }
20531        } else {
20532            throw new IllegalArgumentException("No selective enforcement for " + permission);
20533        }
20534    }
20535
20536    @Override
20537    @Deprecated
20538    public boolean isPermissionEnforced(String permission) {
20539        return true;
20540    }
20541
20542    @Override
20543    public boolean isStorageLow() {
20544        final long token = Binder.clearCallingIdentity();
20545        try {
20546            final DeviceStorageMonitorInternal
20547                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20548            if (dsm != null) {
20549                return dsm.isMemoryLow();
20550            } else {
20551                return false;
20552            }
20553        } finally {
20554            Binder.restoreCallingIdentity(token);
20555        }
20556    }
20557
20558    @Override
20559    public IPackageInstaller getPackageInstaller() {
20560        return mInstallerService;
20561    }
20562
20563    private boolean userNeedsBadging(int userId) {
20564        int index = mUserNeedsBadging.indexOfKey(userId);
20565        if (index < 0) {
20566            final UserInfo userInfo;
20567            final long token = Binder.clearCallingIdentity();
20568            try {
20569                userInfo = sUserManager.getUserInfo(userId);
20570            } finally {
20571                Binder.restoreCallingIdentity(token);
20572            }
20573            final boolean b;
20574            if (userInfo != null && userInfo.isManagedProfile()) {
20575                b = true;
20576            } else {
20577                b = false;
20578            }
20579            mUserNeedsBadging.put(userId, b);
20580            return b;
20581        }
20582        return mUserNeedsBadging.valueAt(index);
20583    }
20584
20585    @Override
20586    public KeySet getKeySetByAlias(String packageName, String alias) {
20587        if (packageName == null || alias == null) {
20588            return null;
20589        }
20590        synchronized(mPackages) {
20591            final PackageParser.Package pkg = mPackages.get(packageName);
20592            if (pkg == null) {
20593                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20594                throw new IllegalArgumentException("Unknown package: " + packageName);
20595            }
20596            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20597            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20598        }
20599    }
20600
20601    @Override
20602    public KeySet getSigningKeySet(String packageName) {
20603        if (packageName == null) {
20604            return null;
20605        }
20606        synchronized(mPackages) {
20607            final PackageParser.Package pkg = mPackages.get(packageName);
20608            if (pkg == null) {
20609                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20610                throw new IllegalArgumentException("Unknown package: " + packageName);
20611            }
20612            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20613                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20614                throw new SecurityException("May not access signing KeySet of other apps.");
20615            }
20616            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20617            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20618        }
20619    }
20620
20621    @Override
20622    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20623        if (packageName == null || ks == null) {
20624            return false;
20625        }
20626        synchronized(mPackages) {
20627            final PackageParser.Package pkg = mPackages.get(packageName);
20628            if (pkg == null) {
20629                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20630                throw new IllegalArgumentException("Unknown package: " + packageName);
20631            }
20632            IBinder ksh = ks.getToken();
20633            if (ksh instanceof KeySetHandle) {
20634                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20635                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20636            }
20637            return false;
20638        }
20639    }
20640
20641    @Override
20642    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20643        if (packageName == null || ks == null) {
20644            return false;
20645        }
20646        synchronized(mPackages) {
20647            final PackageParser.Package pkg = mPackages.get(packageName);
20648            if (pkg == null) {
20649                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20650                throw new IllegalArgumentException("Unknown package: " + packageName);
20651            }
20652            IBinder ksh = ks.getToken();
20653            if (ksh instanceof KeySetHandle) {
20654                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20655                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20656            }
20657            return false;
20658        }
20659    }
20660
20661    private void deletePackageIfUnusedLPr(final String packageName) {
20662        PackageSetting ps = mSettings.mPackages.get(packageName);
20663        if (ps == null) {
20664            return;
20665        }
20666        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20667            // TODO Implement atomic delete if package is unused
20668            // It is currently possible that the package will be deleted even if it is installed
20669            // after this method returns.
20670            mHandler.post(new Runnable() {
20671                public void run() {
20672                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20673                }
20674            });
20675        }
20676    }
20677
20678    /**
20679     * Check and throw if the given before/after packages would be considered a
20680     * downgrade.
20681     */
20682    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20683            throws PackageManagerException {
20684        if (after.versionCode < before.mVersionCode) {
20685            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20686                    "Update version code " + after.versionCode + " is older than current "
20687                    + before.mVersionCode);
20688        } else if (after.versionCode == before.mVersionCode) {
20689            if (after.baseRevisionCode < before.baseRevisionCode) {
20690                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20691                        "Update base revision code " + after.baseRevisionCode
20692                        + " is older than current " + before.baseRevisionCode);
20693            }
20694
20695            if (!ArrayUtils.isEmpty(after.splitNames)) {
20696                for (int i = 0; i < after.splitNames.length; i++) {
20697                    final String splitName = after.splitNames[i];
20698                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20699                    if (j != -1) {
20700                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20701                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20702                                    "Update split " + splitName + " revision code "
20703                                    + after.splitRevisionCodes[i] + " is older than current "
20704                                    + before.splitRevisionCodes[j]);
20705                        }
20706                    }
20707                }
20708            }
20709        }
20710    }
20711
20712    private static class MoveCallbacks extends Handler {
20713        private static final int MSG_CREATED = 1;
20714        private static final int MSG_STATUS_CHANGED = 2;
20715
20716        private final RemoteCallbackList<IPackageMoveObserver>
20717                mCallbacks = new RemoteCallbackList<>();
20718
20719        private final SparseIntArray mLastStatus = new SparseIntArray();
20720
20721        public MoveCallbacks(Looper looper) {
20722            super(looper);
20723        }
20724
20725        public void register(IPackageMoveObserver callback) {
20726            mCallbacks.register(callback);
20727        }
20728
20729        public void unregister(IPackageMoveObserver callback) {
20730            mCallbacks.unregister(callback);
20731        }
20732
20733        @Override
20734        public void handleMessage(Message msg) {
20735            final SomeArgs args = (SomeArgs) msg.obj;
20736            final int n = mCallbacks.beginBroadcast();
20737            for (int i = 0; i < n; i++) {
20738                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20739                try {
20740                    invokeCallback(callback, msg.what, args);
20741                } catch (RemoteException ignored) {
20742                }
20743            }
20744            mCallbacks.finishBroadcast();
20745            args.recycle();
20746        }
20747
20748        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20749                throws RemoteException {
20750            switch (what) {
20751                case MSG_CREATED: {
20752                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20753                    break;
20754                }
20755                case MSG_STATUS_CHANGED: {
20756                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20757                    break;
20758                }
20759            }
20760        }
20761
20762        private void notifyCreated(int moveId, Bundle extras) {
20763            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20764
20765            final SomeArgs args = SomeArgs.obtain();
20766            args.argi1 = moveId;
20767            args.arg2 = extras;
20768            obtainMessage(MSG_CREATED, args).sendToTarget();
20769        }
20770
20771        private void notifyStatusChanged(int moveId, int status) {
20772            notifyStatusChanged(moveId, status, -1);
20773        }
20774
20775        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20776            Slog.v(TAG, "Move " + moveId + " status " + status);
20777
20778            final SomeArgs args = SomeArgs.obtain();
20779            args.argi1 = moveId;
20780            args.argi2 = status;
20781            args.arg3 = estMillis;
20782            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20783
20784            synchronized (mLastStatus) {
20785                mLastStatus.put(moveId, status);
20786            }
20787        }
20788    }
20789
20790    private final static class OnPermissionChangeListeners extends Handler {
20791        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20792
20793        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20794                new RemoteCallbackList<>();
20795
20796        public OnPermissionChangeListeners(Looper looper) {
20797            super(looper);
20798        }
20799
20800        @Override
20801        public void handleMessage(Message msg) {
20802            switch (msg.what) {
20803                case MSG_ON_PERMISSIONS_CHANGED: {
20804                    final int uid = msg.arg1;
20805                    handleOnPermissionsChanged(uid);
20806                } break;
20807            }
20808        }
20809
20810        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20811            mPermissionListeners.register(listener);
20812
20813        }
20814
20815        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20816            mPermissionListeners.unregister(listener);
20817        }
20818
20819        public void onPermissionsChanged(int uid) {
20820            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20821                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20822            }
20823        }
20824
20825        private void handleOnPermissionsChanged(int uid) {
20826            final int count = mPermissionListeners.beginBroadcast();
20827            try {
20828                for (int i = 0; i < count; i++) {
20829                    IOnPermissionsChangeListener callback = mPermissionListeners
20830                            .getBroadcastItem(i);
20831                    try {
20832                        callback.onPermissionsChanged(uid);
20833                    } catch (RemoteException e) {
20834                        Log.e(TAG, "Permission listener is dead", e);
20835                    }
20836                }
20837            } finally {
20838                mPermissionListeners.finishBroadcast();
20839            }
20840        }
20841    }
20842
20843    private class PackageManagerInternalImpl extends PackageManagerInternal {
20844        @Override
20845        public void setLocationPackagesProvider(PackagesProvider provider) {
20846            synchronized (mPackages) {
20847                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20848            }
20849        }
20850
20851        @Override
20852        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20853            synchronized (mPackages) {
20854                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20855            }
20856        }
20857
20858        @Override
20859        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20860            synchronized (mPackages) {
20861                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20862            }
20863        }
20864
20865        @Override
20866        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20867            synchronized (mPackages) {
20868                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20869            }
20870        }
20871
20872        @Override
20873        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20874            synchronized (mPackages) {
20875                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20876            }
20877        }
20878
20879        @Override
20880        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20881            synchronized (mPackages) {
20882                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20883            }
20884        }
20885
20886        @Override
20887        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20888            synchronized (mPackages) {
20889                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20890                        packageName, userId);
20891            }
20892        }
20893
20894        @Override
20895        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20896            synchronized (mPackages) {
20897                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20898                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20899                        packageName, userId);
20900            }
20901        }
20902
20903        @Override
20904        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20905            synchronized (mPackages) {
20906                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20907                        packageName, userId);
20908            }
20909        }
20910
20911        @Override
20912        public void setKeepUninstalledPackages(final List<String> packageList) {
20913            Preconditions.checkNotNull(packageList);
20914            List<String> removedFromList = null;
20915            synchronized (mPackages) {
20916                if (mKeepUninstalledPackages != null) {
20917                    final int packagesCount = mKeepUninstalledPackages.size();
20918                    for (int i = 0; i < packagesCount; i++) {
20919                        String oldPackage = mKeepUninstalledPackages.get(i);
20920                        if (packageList != null && packageList.contains(oldPackage)) {
20921                            continue;
20922                        }
20923                        if (removedFromList == null) {
20924                            removedFromList = new ArrayList<>();
20925                        }
20926                        removedFromList.add(oldPackage);
20927                    }
20928                }
20929                mKeepUninstalledPackages = new ArrayList<>(packageList);
20930                if (removedFromList != null) {
20931                    final int removedCount = removedFromList.size();
20932                    for (int i = 0; i < removedCount; i++) {
20933                        deletePackageIfUnusedLPr(removedFromList.get(i));
20934                    }
20935                }
20936            }
20937        }
20938
20939        @Override
20940        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20941            synchronized (mPackages) {
20942                // If we do not support permission review, done.
20943                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20944                    return false;
20945                }
20946
20947                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20948                if (packageSetting == null) {
20949                    return false;
20950                }
20951
20952                // Permission review applies only to apps not supporting the new permission model.
20953                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20954                    return false;
20955                }
20956
20957                // Legacy apps have the permission and get user consent on launch.
20958                PermissionsState permissionsState = packageSetting.getPermissionsState();
20959                return permissionsState.isPermissionReviewRequired(userId);
20960            }
20961        }
20962
20963        @Override
20964        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20965            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20966        }
20967
20968        @Override
20969        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20970                int userId) {
20971            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20972        }
20973
20974        @Override
20975        public void setDeviceAndProfileOwnerPackages(
20976                int deviceOwnerUserId, String deviceOwnerPackage,
20977                SparseArray<String> profileOwnerPackages) {
20978            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20979                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20980        }
20981
20982        @Override
20983        public boolean isPackageDataProtected(int userId, String packageName) {
20984            return mProtectedPackages.isPackageDataProtected(userId, packageName);
20985        }
20986    }
20987
20988    @Override
20989    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20990        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20991        synchronized (mPackages) {
20992            final long identity = Binder.clearCallingIdentity();
20993            try {
20994                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20995                        packageNames, userId);
20996            } finally {
20997                Binder.restoreCallingIdentity(identity);
20998            }
20999        }
21000    }
21001
21002    private static void enforceSystemOrPhoneCaller(String tag) {
21003        int callingUid = Binder.getCallingUid();
21004        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21005            throw new SecurityException(
21006                    "Cannot call " + tag + " from UID " + callingUid);
21007        }
21008    }
21009
21010    boolean isHistoricalPackageUsageAvailable() {
21011        return mPackageUsage.isHistoricalPackageUsageAvailable();
21012    }
21013
21014    /**
21015     * Return a <b>copy</b> of the collection of packages known to the package manager.
21016     * @return A copy of the values of mPackages.
21017     */
21018    Collection<PackageParser.Package> getPackages() {
21019        synchronized (mPackages) {
21020            return new ArrayList<>(mPackages.values());
21021        }
21022    }
21023
21024    /**
21025     * Logs process start information (including base APK hash) to the security log.
21026     * @hide
21027     */
21028    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21029            String apkFile, int pid) {
21030        if (!SecurityLog.isLoggingEnabled()) {
21031            return;
21032        }
21033        Bundle data = new Bundle();
21034        data.putLong("startTimestamp", System.currentTimeMillis());
21035        data.putString("processName", processName);
21036        data.putInt("uid", uid);
21037        data.putString("seinfo", seinfo);
21038        data.putString("apkFile", apkFile);
21039        data.putInt("pid", pid);
21040        Message msg = mProcessLoggingHandler.obtainMessage(
21041                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21042        msg.setData(data);
21043        mProcessLoggingHandler.sendMessage(msg);
21044    }
21045
21046    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21047        return mCompilerStats.getPackageStats(pkgName);
21048    }
21049
21050    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21051        return getOrCreateCompilerPackageStats(pkg.packageName);
21052    }
21053
21054    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21055        return mCompilerStats.getOrCreatePackageStats(pkgName);
21056    }
21057
21058    public void deleteCompilerPackageStats(String pkgName) {
21059        mCompilerStats.deletePackageStats(pkgName);
21060    }
21061}
21062