PackageManagerService.java revision 4c06f55f14538d8b065d97d7f3fd2b79976fb94b
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.ContentResolver;
113import android.content.Context;
114import android.content.IIntentReceiver;
115import android.content.Intent;
116import android.content.IntentFilter;
117import android.content.IntentSender;
118import android.content.IntentSender.SendIntentException;
119import android.content.ServiceConnection;
120import android.content.pm.ActivityInfo;
121import android.content.pm.ApplicationInfo;
122import android.content.pm.AppsQueryHelper;
123import android.content.pm.ComponentInfo;
124import android.content.pm.EphemeralApplicationInfo;
125import android.content.pm.EphemeralResolveInfo;
126import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
128import android.content.pm.FeatureInfo;
129import android.content.pm.IOnPermissionsChangeListener;
130import android.content.pm.IPackageDataObserver;
131import android.content.pm.IPackageDeleteObserver;
132import android.content.pm.IPackageDeleteObserver2;
133import android.content.pm.IPackageInstallObserver2;
134import android.content.pm.IPackageInstaller;
135import android.content.pm.IPackageManager;
136import android.content.pm.IPackageMoveObserver;
137import android.content.pm.IPackageStatsObserver;
138import android.content.pm.InstrumentationInfo;
139import android.content.pm.IntentFilterVerificationInfo;
140import android.content.pm.KeySet;
141import android.content.pm.PackageCleanItem;
142import android.content.pm.PackageInfo;
143import android.content.pm.PackageInfoLite;
144import android.content.pm.PackageInstaller;
145import android.content.pm.PackageManager;
146import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
147import android.content.pm.PackageManagerInternal;
148import android.content.pm.PackageParser;
149import android.content.pm.PackageParser.ActivityIntentInfo;
150import android.content.pm.PackageParser.PackageLite;
151import android.content.pm.PackageParser.PackageParserException;
152import android.content.pm.PackageStats;
153import android.content.pm.PackageUserState;
154import android.content.pm.ParceledListSlice;
155import android.content.pm.PermissionGroupInfo;
156import android.content.pm.PermissionInfo;
157import android.content.pm.ProviderInfo;
158import android.content.pm.ResolveInfo;
159import android.content.pm.ServiceInfo;
160import android.content.pm.Signature;
161import android.content.pm.UserInfo;
162import android.content.pm.VerifierDeviceIdentity;
163import android.content.pm.VerifierInfo;
164import android.content.res.Resources;
165import android.graphics.Bitmap;
166import android.hardware.display.DisplayManager;
167import android.net.Uri;
168import android.os.Binder;
169import android.os.Build;
170import android.os.Bundle;
171import android.os.Debug;
172import android.os.Environment;
173import android.os.Environment.UserEnvironment;
174import android.os.FileUtils;
175import android.os.Handler;
176import android.os.IBinder;
177import android.os.Looper;
178import android.os.Message;
179import android.os.Parcel;
180import android.os.ParcelFileDescriptor;
181import android.os.PatternMatcher;
182import android.os.Process;
183import android.os.RemoteCallbackList;
184import android.os.RemoteException;
185import android.os.ResultReceiver;
186import android.os.SELinux;
187import android.os.ServiceManager;
188import android.os.SystemClock;
189import android.os.SystemProperties;
190import android.os.Trace;
191import android.os.UserHandle;
192import android.os.UserManager;
193import android.os.UserManagerInternal;
194import android.os.storage.IMountService;
195import android.os.storage.MountServiceInternal;
196import android.os.storage.StorageEventListener;
197import android.os.storage.StorageManager;
198import android.os.storage.VolumeInfo;
199import android.os.storage.VolumeRecord;
200import android.provider.Settings.Global;
201import android.provider.Settings.Secure;
202import android.security.KeyStore;
203import android.security.SystemKeyStore;
204import android.system.ErrnoException;
205import android.system.Os;
206import android.text.TextUtils;
207import android.text.format.DateUtils;
208import android.util.ArrayMap;
209import android.util.ArraySet;
210import android.util.DisplayMetrics;
211import android.util.EventLog;
212import android.util.ExceptionUtils;
213import android.util.Log;
214import android.util.LogPrinter;
215import android.util.MathUtils;
216import android.util.Pair;
217import android.util.PrintStreamPrinter;
218import android.util.Slog;
219import android.util.SparseArray;
220import android.util.SparseBooleanArray;
221import android.util.SparseIntArray;
222import android.util.Xml;
223import android.util.jar.StrictJarFile;
224import android.view.Display;
225
226import com.android.internal.R;
227import com.android.internal.annotations.GuardedBy;
228import com.android.internal.app.IMediaContainerService;
229import com.android.internal.app.ResolverActivity;
230import com.android.internal.content.NativeLibraryHelper;
231import com.android.internal.content.PackageHelper;
232import com.android.internal.logging.MetricsLogger;
233import com.android.internal.os.IParcelFileDescriptorFactory;
234import com.android.internal.os.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.Installer.InstallerException;
253import com.android.server.pm.PermissionsState.PermissionState;
254import com.android.server.pm.Settings.DatabaseVersion;
255import com.android.server.pm.Settings.VersionInfo;
256import com.android.server.pm.dex.DexManager;
257import com.android.server.storage.DeviceStorageMonitorInternal;
258
259import dalvik.system.CloseGuard;
260import dalvik.system.DexFile;
261import dalvik.system.VMRuntime;
262
263import libcore.io.IoUtils;
264import libcore.util.EmptyArray;
265
266import org.xmlpull.v1.XmlPullParser;
267import org.xmlpull.v1.XmlPullParserException;
268import org.xmlpull.v1.XmlSerializer;
269
270import java.io.BufferedOutputStream;
271import java.io.BufferedReader;
272import java.io.ByteArrayInputStream;
273import java.io.ByteArrayOutputStream;
274import java.io.File;
275import java.io.FileDescriptor;
276import java.io.FileInputStream;
277import java.io.FileNotFoundException;
278import java.io.FileOutputStream;
279import java.io.FileReader;
280import java.io.FilenameFilter;
281import java.io.IOException;
282import java.io.PrintWriter;
283import java.nio.charset.StandardCharsets;
284import java.security.DigestInputStream;
285import java.security.MessageDigest;
286import java.security.NoSuchAlgorithmException;
287import java.security.PublicKey;
288import java.security.cert.Certificate;
289import java.security.cert.CertificateEncodingException;
290import java.security.cert.CertificateException;
291import java.text.SimpleDateFormat;
292import java.util.ArrayList;
293import java.util.Arrays;
294import java.util.Collection;
295import java.util.Collections;
296import java.util.Comparator;
297import java.util.Date;
298import java.util.HashSet;
299import java.util.HashMap;
300import java.util.Iterator;
301import java.util.List;
302import java.util.Map;
303import java.util.Objects;
304import java.util.Set;
305import java.util.concurrent.CountDownLatch;
306import java.util.concurrent.TimeUnit;
307import java.util.concurrent.atomic.AtomicBoolean;
308import java.util.concurrent.atomic.AtomicInteger;
309
310/**
311 * Keep track of all those APKs everywhere.
312 * <p>
313 * Internally there are two important locks:
314 * <ul>
315 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
316 * and other related state. It is a fine-grained lock that should only be held
317 * momentarily, as it's one of the most contended locks in the system.
318 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
319 * operations typically involve heavy lifting of application data on disk. Since
320 * {@code installd} is single-threaded, and it's operations can often be slow,
321 * this lock should never be acquired while already holding {@link #mPackages}.
322 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
323 * holding {@link #mInstallLock}.
324 * </ul>
325 * Many internal methods rely on the caller to hold the appropriate locks, and
326 * this contract is expressed through method name suffixes:
327 * <ul>
328 * <li>fooLI(): the caller must hold {@link #mInstallLock}
329 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
330 * being modified must be frozen
331 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
332 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
333 * </ul>
334 * <p>
335 * Because this class is very central to the platform's security; please run all
336 * CTS and unit tests whenever making modifications:
337 *
338 * <pre>
339 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
340 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
341 * </pre>
342 */
343public class PackageManagerService extends IPackageManager.Stub {
344    static final String TAG = "PackageManager";
345    static final boolean DEBUG_SETTINGS = false;
346    static final boolean DEBUG_PREFERRED = false;
347    static final boolean DEBUG_UPGRADE = false;
348    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
349    private static final boolean DEBUG_BACKUP = false;
350    private static final boolean DEBUG_INSTALL = false;
351    private static final boolean DEBUG_REMOVE = false;
352    private static final boolean DEBUG_BROADCASTS = false;
353    private static final boolean DEBUG_SHOW_INFO = false;
354    private static final boolean DEBUG_PACKAGE_INFO = false;
355    private static final boolean DEBUG_INTENT_MATCHING = false;
356    private static final boolean DEBUG_PACKAGE_SCANNING = false;
357    private static final boolean DEBUG_VERIFY = false;
358    private static final boolean DEBUG_FILTERS = false;
359
360    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
361    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
362    // user, but by default initialize to this.
363    static final boolean DEBUG_DEXOPT = false;
364
365    private static final boolean DEBUG_ABI_SELECTION = false;
366    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
367    private static final boolean DEBUG_TRIAGED_MISSING = false;
368    private static final boolean DEBUG_APP_DATA = false;
369
370    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
371
372    private static final boolean DISABLE_EPHEMERAL_APPS = false;
373    private static final boolean HIDE_EPHEMERAL_APIS = true;
374
375    private static final boolean ENABLE_QUOTA =
376            SystemProperties.getBoolean("persist.fw.quota", false);
377
378    private static final int RADIO_UID = Process.PHONE_UID;
379    private static final int LOG_UID = Process.LOG_UID;
380    private static final int NFC_UID = Process.NFC_UID;
381    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
382    private static final int SHELL_UID = Process.SHELL_UID;
383
384    // Cap the size of permission trees that 3rd party apps can define
385    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
386
387    // Suffix used during package installation when copying/moving
388    // package apks to install directory.
389    private static final String INSTALL_PACKAGE_SUFFIX = "-";
390
391    static final int SCAN_NO_DEX = 1<<1;
392    static final int SCAN_FORCE_DEX = 1<<2;
393    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
394    static final int SCAN_NEW_INSTALL = 1<<4;
395    static final int SCAN_NO_PATHS = 1<<5;
396    static final int SCAN_UPDATE_TIME = 1<<6;
397    static final int SCAN_DEFER_DEX = 1<<7;
398    static final int SCAN_BOOTING = 1<<8;
399    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
400    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
401    static final int SCAN_REPLACING = 1<<11;
402    static final int SCAN_REQUIRE_KNOWN = 1<<12;
403    static final int SCAN_MOVE = 1<<13;
404    static final int SCAN_INITIAL = 1<<14;
405    static final int SCAN_CHECK_ONLY = 1<<15;
406    static final int SCAN_DONT_KILL_APP = 1<<17;
407    static final int SCAN_IGNORE_FROZEN = 1<<18;
408
409    static final int REMOVE_CHATTY = 1<<16;
410
411    private static final int[] EMPTY_INT_ARRAY = new int[0];
412
413    /**
414     * Timeout (in milliseconds) after which the watchdog should declare that
415     * our handler thread is wedged.  The usual default for such things is one
416     * minute but we sometimes do very lengthy I/O operations on this thread,
417     * such as installing multi-gigabyte applications, so ours needs to be longer.
418     */
419    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
420
421    /**
422     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
423     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
424     * settings entry if available, otherwise we use the hardcoded default.  If it's been
425     * more than this long since the last fstrim, we force one during the boot sequence.
426     *
427     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
428     * one gets run at the next available charging+idle time.  This final mandatory
429     * no-fstrim check kicks in only of the other scheduling criteria is never met.
430     */
431    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
432
433    /**
434     * Whether verification is enabled by default.
435     */
436    private static final boolean DEFAULT_VERIFY_ENABLE = true;
437
438    /**
439     * The default maximum time to wait for the verification agent to return in
440     * milliseconds.
441     */
442    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
443
444    /**
445     * The default response for package verification timeout.
446     *
447     * This can be either PackageManager.VERIFICATION_ALLOW or
448     * PackageManager.VERIFICATION_REJECT.
449     */
450    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
451
452    static final String PLATFORM_PACKAGE_NAME = "android";
453
454    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
455
456    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
457            DEFAULT_CONTAINER_PACKAGE,
458            "com.android.defcontainer.DefaultContainerService");
459
460    private static final String KILL_APP_REASON_GIDS_CHANGED =
461            "permission grant or revoke changed gids";
462
463    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
464            "permissions revoked";
465
466    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
467
468    private static final String PACKAGE_SCHEME = "package";
469
470    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
471    /**
472     * If VENDOR_OVERLAY_SKU_PROPERTY is set, search for runtime resource overlay APKs in
473     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_SKU_PROPERTY> rather than in
474     * VENDOR_OVERLAY_DIR.
475     */
476    private static final String VENDOR_OVERLAY_SKU_PROPERTY = "ro.boot.vendor.overlay.sku";
477
478    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
479    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
480
481    /** Permission grant: not grant the permission. */
482    private static final int GRANT_DENIED = 1;
483
484    /** Permission grant: grant the permission as an install permission. */
485    private static final int GRANT_INSTALL = 2;
486
487    /** Permission grant: grant the permission as a runtime one. */
488    private static final int GRANT_RUNTIME = 3;
489
490    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
491    private static final int GRANT_UPGRADE = 4;
492
493    /** Canonical intent used to identify what counts as a "web browser" app */
494    private static final Intent sBrowserIntent;
495    static {
496        sBrowserIntent = new Intent();
497        sBrowserIntent.setAction(Intent.ACTION_VIEW);
498        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
499        sBrowserIntent.setData(Uri.parse("http:"));
500    }
501
502    /**
503     * The set of all protected actions [i.e. those actions for which a high priority
504     * intent filter is disallowed].
505     */
506    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
507    static {
508        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
509        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
510        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
511        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
512    }
513
514    // Compilation reasons.
515    public static final int REASON_FIRST_BOOT = 0;
516    public static final int REASON_BOOT = 1;
517    public static final int REASON_INSTALL = 2;
518    public static final int REASON_BACKGROUND_DEXOPT = 3;
519    public static final int REASON_AB_OTA = 4;
520    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
521    public static final int REASON_SHARED_APK = 6;
522    public static final int REASON_FORCED_DEXOPT = 7;
523    public static final int REASON_CORE_APP = 8;
524
525    public static final int REASON_LAST = REASON_CORE_APP;
526
527    final ServiceThread mHandlerThread;
528
529    final PackageHandler mHandler;
530
531    private final ProcessLoggingHandler mProcessLoggingHandler;
532
533    /**
534     * Messages for {@link #mHandler} that need to wait for system ready before
535     * being dispatched.
536     */
537    private ArrayList<Message> mPostSystemReadyMessages;
538
539    final int mSdkVersion = Build.VERSION.SDK_INT;
540
541    final Context mContext;
542    final boolean mFactoryTest;
543    final boolean mOnlyCore;
544    final DisplayMetrics mMetrics;
545    final int mDefParseFlags;
546    final String[] mSeparateProcesses;
547    final boolean mIsUpgrade;
548    final boolean mIsPreNUpgrade;
549    final boolean mIsPreNMR1Upgrade;
550
551    @GuardedBy("mPackages")
552    private boolean mDexOptDialogShown;
553
554    /** The location for ASEC container files on internal storage. */
555    final String mAsecInternalPath;
556
557    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
558    // LOCK HELD.  Can be called with mInstallLock held.
559    @GuardedBy("mInstallLock")
560    final Installer mInstaller;
561
562    /** Directory where installed third-party apps stored */
563    final File mAppInstallDir;
564    final File mEphemeralInstallDir;
565
566    /**
567     * Directory to which applications installed internally have their
568     * 32 bit native libraries copied.
569     */
570    private File mAppLib32InstallDir;
571
572    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
573    // apps.
574    final File mDrmAppPrivateInstallDir;
575
576    // ----------------------------------------------------------------
577
578    // Lock for state used when installing and doing other long running
579    // operations.  Methods that must be called with this lock held have
580    // the suffix "LI".
581    final Object mInstallLock = new Object();
582
583    // ----------------------------------------------------------------
584
585    // Keys are String (package name), values are Package.  This also serves
586    // as the lock for the global state.  Methods that must be called with
587    // this lock held have the prefix "LP".
588    @GuardedBy("mPackages")
589    final ArrayMap<String, PackageParser.Package> mPackages =
590            new ArrayMap<String, PackageParser.Package>();
591
592    final ArrayMap<String, Set<String>> mKnownCodebase =
593            new ArrayMap<String, Set<String>>();
594
595    // Tracks available target package names -> overlay package paths.
596    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
597        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
598
599    /**
600     * Tracks new system packages [received in an OTA] that we expect to
601     * find updated user-installed versions. Keys are package name, values
602     * are package location.
603     */
604    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
605    /**
606     * Tracks high priority intent filters for protected actions. During boot, certain
607     * filter actions are protected and should never be allowed to have a high priority
608     * intent filter for them. However, there is one, and only one exception -- the
609     * setup wizard. It must be able to define a high priority intent filter for these
610     * actions to ensure there are no escapes from the wizard. We need to delay processing
611     * of these during boot as we need to look at all of the system packages in order
612     * to know which component is the setup wizard.
613     */
614    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
615    /**
616     * Whether or not processing protected filters should be deferred.
617     */
618    private boolean mDeferProtectedFilters = true;
619
620    /**
621     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
622     */
623    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
624    /**
625     * Whether or not system app permissions should be promoted from install to runtime.
626     */
627    boolean mPromoteSystemApps;
628
629    @GuardedBy("mPackages")
630    final Settings mSettings;
631
632    /**
633     * Set of package names that are currently "frozen", which means active
634     * surgery is being done on the code/data for that package. The platform
635     * will refuse to launch frozen packages to avoid race conditions.
636     *
637     * @see PackageFreezer
638     */
639    @GuardedBy("mPackages")
640    final ArraySet<String> mFrozenPackages = new ArraySet<>();
641
642    final ProtectedPackages mProtectedPackages;
643
644    boolean mFirstBoot;
645
646    // System configuration read by SystemConfig.
647    final int[] mGlobalGids;
648    final SparseArray<ArraySet<String>> mSystemPermissions;
649    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
650
651    // If mac_permissions.xml was found for seinfo labeling.
652    boolean mFoundPolicyFile;
653
654    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
655
656    public static final class SharedLibraryEntry {
657        public final String path;
658        public final String apk;
659
660        SharedLibraryEntry(String _path, String _apk) {
661            path = _path;
662            apk = _apk;
663        }
664    }
665
666    // Currently known shared libraries.
667    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
668            new ArrayMap<String, SharedLibraryEntry>();
669
670    // All available activities, for your resolving pleasure.
671    final ActivityIntentResolver mActivities =
672            new ActivityIntentResolver();
673
674    // All available receivers, for your resolving pleasure.
675    final ActivityIntentResolver mReceivers =
676            new ActivityIntentResolver();
677
678    // All available services, for your resolving pleasure.
679    final ServiceIntentResolver mServices = new ServiceIntentResolver();
680
681    // All available providers, for your resolving pleasure.
682    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
683
684    // Mapping from provider base names (first directory in content URI codePath)
685    // to the provider information.
686    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
687            new ArrayMap<String, PackageParser.Provider>();
688
689    // Mapping from instrumentation class names to info about them.
690    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
691            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
692
693    // Mapping from permission names to info about them.
694    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
695            new ArrayMap<String, PackageParser.PermissionGroup>();
696
697    // Packages whose data we have transfered into another package, thus
698    // should no longer exist.
699    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
700
701    // Broadcast actions that are only available to the system.
702    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
703
704    /** List of packages waiting for verification. */
705    final SparseArray<PackageVerificationState> mPendingVerification
706            = new SparseArray<PackageVerificationState>();
707
708    /** Set of packages associated with each app op permission. */
709    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
710
711    final PackageInstallerService mInstallerService;
712
713    private final PackageDexOptimizer mPackageDexOptimizer;
714    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
715    // is used by other apps).
716    private final DexManager mDexManager;
717
718    private AtomicInteger mNextMoveId = new AtomicInteger();
719    private final MoveCallbacks mMoveCallbacks;
720
721    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
722
723    // Cache of users who need badging.
724    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
725
726    /** Token for keys in mPendingVerification. */
727    private int mPendingVerificationToken = 0;
728
729    volatile boolean mSystemReady;
730    volatile boolean mSafeMode;
731    volatile boolean mHasSystemUidErrors;
732
733    ApplicationInfo mAndroidApplication;
734    final ActivityInfo mResolveActivity = new ActivityInfo();
735    final ResolveInfo mResolveInfo = new ResolveInfo();
736    ComponentName mResolveComponentName;
737    PackageParser.Package mPlatformPackage;
738    ComponentName mCustomResolverComponentName;
739
740    boolean mResolverReplaced = false;
741
742    private final @Nullable ComponentName mIntentFilterVerifierComponent;
743    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
744
745    private int mIntentFilterVerificationToken = 0;
746
747    /** Component that knows whether or not an ephemeral application exists */
748    final ComponentName mEphemeralResolverComponent;
749    /** The service connection to the ephemeral resolver */
750    final EphemeralResolverConnection mEphemeralResolverConnection;
751
752    /** Component used to install ephemeral applications */
753    final ComponentName mEphemeralInstallerComponent;
754    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
755    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
756
757    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
758            = new SparseArray<IntentFilterVerificationState>();
759
760    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
761
762    // List of packages names to keep cached, even if they are uninstalled for all users
763    private List<String> mKeepUninstalledPackages;
764
765    private UserManagerInternal mUserManagerInternal;
766
767    private static class IFVerificationParams {
768        PackageParser.Package pkg;
769        boolean replacing;
770        int userId;
771        int verifierUid;
772
773        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
774                int _userId, int _verifierUid) {
775            pkg = _pkg;
776            replacing = _replacing;
777            userId = _userId;
778            replacing = _replacing;
779            verifierUid = _verifierUid;
780        }
781    }
782
783    private interface IntentFilterVerifier<T extends IntentFilter> {
784        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
785                                               T filter, String packageName);
786        void startVerifications(int userId);
787        void receiveVerificationResponse(int verificationId);
788    }
789
790    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
791        private Context mContext;
792        private ComponentName mIntentFilterVerifierComponent;
793        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
794
795        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
796            mContext = context;
797            mIntentFilterVerifierComponent = verifierComponent;
798        }
799
800        private String getDefaultScheme() {
801            return IntentFilter.SCHEME_HTTPS;
802        }
803
804        @Override
805        public void startVerifications(int userId) {
806            // Launch verifications requests
807            int count = mCurrentIntentFilterVerifications.size();
808            for (int n=0; n<count; n++) {
809                int verificationId = mCurrentIntentFilterVerifications.get(n);
810                final IntentFilterVerificationState ivs =
811                        mIntentFilterVerificationStates.get(verificationId);
812
813                String packageName = ivs.getPackageName();
814
815                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
816                final int filterCount = filters.size();
817                ArraySet<String> domainsSet = new ArraySet<>();
818                for (int m=0; m<filterCount; m++) {
819                    PackageParser.ActivityIntentInfo filter = filters.get(m);
820                    domainsSet.addAll(filter.getHostsList());
821                }
822                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
823                synchronized (mPackages) {
824                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
825                            packageName, domainsList) != null) {
826                        scheduleWriteSettingsLocked();
827                    }
828                }
829                sendVerificationRequest(userId, verificationId, ivs);
830            }
831            mCurrentIntentFilterVerifications.clear();
832        }
833
834        private void sendVerificationRequest(int userId, int verificationId,
835                IntentFilterVerificationState ivs) {
836
837            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
838            verificationIntent.putExtra(
839                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
840                    verificationId);
841            verificationIntent.putExtra(
842                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
843                    getDefaultScheme());
844            verificationIntent.putExtra(
845                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
846                    ivs.getHostsString());
847            verificationIntent.putExtra(
848                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
849                    ivs.getPackageName());
850            verificationIntent.setComponent(mIntentFilterVerifierComponent);
851            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
852
853            UserHandle user = new UserHandle(userId);
854            mContext.sendBroadcastAsUser(verificationIntent, user);
855            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
856                    "Sending IntentFilter verification broadcast");
857        }
858
859        public void receiveVerificationResponse(int verificationId) {
860            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
861
862            final boolean verified = ivs.isVerified();
863
864            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
865            final int count = filters.size();
866            if (DEBUG_DOMAIN_VERIFICATION) {
867                Slog.i(TAG, "Received verification response " + verificationId
868                        + " for " + count + " filters, verified=" + verified);
869            }
870            for (int n=0; n<count; n++) {
871                PackageParser.ActivityIntentInfo filter = filters.get(n);
872                filter.setVerified(verified);
873
874                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
875                        + " verified with result:" + verified + " and hosts:"
876                        + ivs.getHostsString());
877            }
878
879            mIntentFilterVerificationStates.remove(verificationId);
880
881            final String packageName = ivs.getPackageName();
882            IntentFilterVerificationInfo ivi = null;
883
884            synchronized (mPackages) {
885                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
886            }
887            if (ivi == null) {
888                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
889                        + verificationId + " packageName:" + packageName);
890                return;
891            }
892            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
893                    "Updating IntentFilterVerificationInfo for package " + packageName
894                            +" verificationId:" + verificationId);
895
896            synchronized (mPackages) {
897                if (verified) {
898                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
899                } else {
900                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
901                }
902                scheduleWriteSettingsLocked();
903
904                final int userId = ivs.getUserId();
905                if (userId != UserHandle.USER_ALL) {
906                    final int userStatus =
907                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
908
909                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
910                    boolean needUpdate = false;
911
912                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
913                    // already been set by the User thru the Disambiguation dialog
914                    switch (userStatus) {
915                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
916                            if (verified) {
917                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
918                            } else {
919                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
920                            }
921                            needUpdate = true;
922                            break;
923
924                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
925                            if (verified) {
926                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
927                                needUpdate = true;
928                            }
929                            break;
930
931                        default:
932                            // Nothing to do
933                    }
934
935                    if (needUpdate) {
936                        mSettings.updateIntentFilterVerificationStatusLPw(
937                                packageName, updatedStatus, userId);
938                        scheduleWritePackageRestrictionsLocked(userId);
939                    }
940                }
941            }
942        }
943
944        @Override
945        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
946                    ActivityIntentInfo filter, String packageName) {
947            if (!hasValidDomains(filter)) {
948                return false;
949            }
950            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
951            if (ivs == null) {
952                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
953                        packageName);
954            }
955            if (DEBUG_DOMAIN_VERIFICATION) {
956                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
957            }
958            ivs.addFilter(filter);
959            return true;
960        }
961
962        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
963                int userId, int verificationId, String packageName) {
964            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
965                    verifierUid, userId, packageName);
966            ivs.setPendingState();
967            synchronized (mPackages) {
968                mIntentFilterVerificationStates.append(verificationId, ivs);
969                mCurrentIntentFilterVerifications.add(verificationId);
970            }
971            return ivs;
972        }
973    }
974
975    private static boolean hasValidDomains(ActivityIntentInfo filter) {
976        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
977                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
978                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
979    }
980
981    // Set of pending broadcasts for aggregating enable/disable of components.
982    static class PendingPackageBroadcasts {
983        // for each user id, a map of <package name -> components within that package>
984        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
985
986        public PendingPackageBroadcasts() {
987            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
988        }
989
990        public ArrayList<String> get(int userId, String packageName) {
991            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
992            return packages.get(packageName);
993        }
994
995        public void put(int userId, String packageName, ArrayList<String> components) {
996            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
997            packages.put(packageName, components);
998        }
999
1000        public void remove(int userId, String packageName) {
1001            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1002            if (packages != null) {
1003                packages.remove(packageName);
1004            }
1005        }
1006
1007        public void remove(int userId) {
1008            mUidMap.remove(userId);
1009        }
1010
1011        public int userIdCount() {
1012            return mUidMap.size();
1013        }
1014
1015        public int userIdAt(int n) {
1016            return mUidMap.keyAt(n);
1017        }
1018
1019        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1020            return mUidMap.get(userId);
1021        }
1022
1023        public int size() {
1024            // total number of pending broadcast entries across all userIds
1025            int num = 0;
1026            for (int i = 0; i< mUidMap.size(); i++) {
1027                num += mUidMap.valueAt(i).size();
1028            }
1029            return num;
1030        }
1031
1032        public void clear() {
1033            mUidMap.clear();
1034        }
1035
1036        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1037            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1038            if (map == null) {
1039                map = new ArrayMap<String, ArrayList<String>>();
1040                mUidMap.put(userId, map);
1041            }
1042            return map;
1043        }
1044    }
1045    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1046
1047    // Service Connection to remote media container service to copy
1048    // package uri's from external media onto secure containers
1049    // or internal storage.
1050    private IMediaContainerService mContainerService = null;
1051
1052    static final int SEND_PENDING_BROADCAST = 1;
1053    static final int MCS_BOUND = 3;
1054    static final int END_COPY = 4;
1055    static final int INIT_COPY = 5;
1056    static final int MCS_UNBIND = 6;
1057    static final int START_CLEANING_PACKAGE = 7;
1058    static final int FIND_INSTALL_LOC = 8;
1059    static final int POST_INSTALL = 9;
1060    static final int MCS_RECONNECT = 10;
1061    static final int MCS_GIVE_UP = 11;
1062    static final int UPDATED_MEDIA_STATUS = 12;
1063    static final int WRITE_SETTINGS = 13;
1064    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1065    static final int PACKAGE_VERIFIED = 15;
1066    static final int CHECK_PENDING_VERIFICATION = 16;
1067    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1068    static final int INTENT_FILTER_VERIFIED = 18;
1069    static final int WRITE_PACKAGE_LIST = 19;
1070
1071    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1072
1073    // Delay time in millisecs
1074    static final int BROADCAST_DELAY = 10 * 1000;
1075
1076    static UserManagerService sUserManager;
1077
1078    // Stores a list of users whose package restrictions file needs to be updated
1079    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1080
1081    final private DefaultContainerConnection mDefContainerConn =
1082            new DefaultContainerConnection();
1083    class DefaultContainerConnection implements ServiceConnection {
1084        public void onServiceConnected(ComponentName name, IBinder service) {
1085            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1086            IMediaContainerService imcs =
1087                IMediaContainerService.Stub.asInterface(service);
1088            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1089        }
1090
1091        public void onServiceDisconnected(ComponentName name) {
1092            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1093        }
1094    }
1095
1096    // Recordkeeping of restore-after-install operations that are currently in flight
1097    // between the Package Manager and the Backup Manager
1098    static class PostInstallData {
1099        public InstallArgs args;
1100        public PackageInstalledInfo res;
1101
1102        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1103            args = _a;
1104            res = _r;
1105        }
1106    }
1107
1108    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1109    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1110
1111    // XML tags for backup/restore of various bits of state
1112    private static final String TAG_PREFERRED_BACKUP = "pa";
1113    private static final String TAG_DEFAULT_APPS = "da";
1114    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1115
1116    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1117    private static final String TAG_ALL_GRANTS = "rt-grants";
1118    private static final String TAG_GRANT = "grant";
1119    private static final String ATTR_PACKAGE_NAME = "pkg";
1120
1121    private static final String TAG_PERMISSION = "perm";
1122    private static final String ATTR_PERMISSION_NAME = "name";
1123    private static final String ATTR_IS_GRANTED = "g";
1124    private static final String ATTR_USER_SET = "set";
1125    private static final String ATTR_USER_FIXED = "fixed";
1126    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1127
1128    // System/policy permission grants are not backed up
1129    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1130            FLAG_PERMISSION_POLICY_FIXED
1131            | FLAG_PERMISSION_SYSTEM_FIXED
1132            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1133
1134    // And we back up these user-adjusted states
1135    private static final int USER_RUNTIME_GRANT_MASK =
1136            FLAG_PERMISSION_USER_SET
1137            | FLAG_PERMISSION_USER_FIXED
1138            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1139
1140    final @Nullable String mRequiredVerifierPackage;
1141    final @NonNull String mRequiredInstallerPackage;
1142    final @NonNull String mRequiredUninstallerPackage;
1143    final @Nullable String mSetupWizardPackage;
1144    final @Nullable String mStorageManagerPackage;
1145    final @NonNull String mServicesSystemSharedLibraryPackageName;
1146    final @NonNull String mSharedSystemSharedLibraryPackageName;
1147
1148    final boolean mPermissionReviewRequired;
1149
1150    private final PackageUsage mPackageUsage = new PackageUsage();
1151    private final CompilerStats mCompilerStats = new CompilerStats();
1152
1153    class PackageHandler extends Handler {
1154        private boolean mBound = false;
1155        final ArrayList<HandlerParams> mPendingInstalls =
1156            new ArrayList<HandlerParams>();
1157
1158        private boolean connectToService() {
1159            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1160                    " DefaultContainerService");
1161            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1162            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1163            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1164                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1165                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1166                mBound = true;
1167                return true;
1168            }
1169            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1170            return false;
1171        }
1172
1173        private void disconnectService() {
1174            mContainerService = null;
1175            mBound = false;
1176            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1177            mContext.unbindService(mDefContainerConn);
1178            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1179        }
1180
1181        PackageHandler(Looper looper) {
1182            super(looper);
1183        }
1184
1185        public void handleMessage(Message msg) {
1186            try {
1187                doHandleMessage(msg);
1188            } finally {
1189                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1190            }
1191        }
1192
1193        void doHandleMessage(Message msg) {
1194            switch (msg.what) {
1195                case INIT_COPY: {
1196                    HandlerParams params = (HandlerParams) msg.obj;
1197                    int idx = mPendingInstalls.size();
1198                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1199                    // If a bind was already initiated we dont really
1200                    // need to do anything. The pending install
1201                    // will be processed later on.
1202                    if (!mBound) {
1203                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1204                                System.identityHashCode(mHandler));
1205                        // If this is the only one pending we might
1206                        // have to bind to the service again.
1207                        if (!connectToService()) {
1208                            Slog.e(TAG, "Failed to bind to media container service");
1209                            params.serviceError();
1210                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1211                                    System.identityHashCode(mHandler));
1212                            if (params.traceMethod != null) {
1213                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1214                                        params.traceCookie);
1215                            }
1216                            return;
1217                        } else {
1218                            // Once we bind to the service, the first
1219                            // pending request will be processed.
1220                            mPendingInstalls.add(idx, params);
1221                        }
1222                    } else {
1223                        mPendingInstalls.add(idx, params);
1224                        // Already bound to the service. Just make
1225                        // sure we trigger off processing the first request.
1226                        if (idx == 0) {
1227                            mHandler.sendEmptyMessage(MCS_BOUND);
1228                        }
1229                    }
1230                    break;
1231                }
1232                case MCS_BOUND: {
1233                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1234                    if (msg.obj != null) {
1235                        mContainerService = (IMediaContainerService) msg.obj;
1236                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1237                                System.identityHashCode(mHandler));
1238                    }
1239                    if (mContainerService == null) {
1240                        if (!mBound) {
1241                            // Something seriously wrong since we are not bound and we are not
1242                            // waiting for connection. Bail out.
1243                            Slog.e(TAG, "Cannot bind to media container service");
1244                            for (HandlerParams params : mPendingInstalls) {
1245                                // Indicate service bind error
1246                                params.serviceError();
1247                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1248                                        System.identityHashCode(params));
1249                                if (params.traceMethod != null) {
1250                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1251                                            params.traceMethod, params.traceCookie);
1252                                }
1253                                return;
1254                            }
1255                            mPendingInstalls.clear();
1256                        } else {
1257                            Slog.w(TAG, "Waiting to connect to media container service");
1258                        }
1259                    } else if (mPendingInstalls.size() > 0) {
1260                        HandlerParams params = mPendingInstalls.get(0);
1261                        if (params != null) {
1262                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1263                                    System.identityHashCode(params));
1264                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1265                            if (params.startCopy()) {
1266                                // We are done...  look for more work or to
1267                                // go idle.
1268                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1269                                        "Checking for more work or unbind...");
1270                                // Delete pending install
1271                                if (mPendingInstalls.size() > 0) {
1272                                    mPendingInstalls.remove(0);
1273                                }
1274                                if (mPendingInstalls.size() == 0) {
1275                                    if (mBound) {
1276                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1277                                                "Posting delayed MCS_UNBIND");
1278                                        removeMessages(MCS_UNBIND);
1279                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1280                                        // Unbind after a little delay, to avoid
1281                                        // continual thrashing.
1282                                        sendMessageDelayed(ubmsg, 10000);
1283                                    }
1284                                } else {
1285                                    // There are more pending requests in queue.
1286                                    // Just post MCS_BOUND message to trigger processing
1287                                    // of next pending install.
1288                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1289                                            "Posting MCS_BOUND for next work");
1290                                    mHandler.sendEmptyMessage(MCS_BOUND);
1291                                }
1292                            }
1293                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1294                        }
1295                    } else {
1296                        // Should never happen ideally.
1297                        Slog.w(TAG, "Empty queue");
1298                    }
1299                    break;
1300                }
1301                case MCS_RECONNECT: {
1302                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1303                    if (mPendingInstalls.size() > 0) {
1304                        if (mBound) {
1305                            disconnectService();
1306                        }
1307                        if (!connectToService()) {
1308                            Slog.e(TAG, "Failed to bind to media container service");
1309                            for (HandlerParams params : mPendingInstalls) {
1310                                // Indicate service bind error
1311                                params.serviceError();
1312                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1313                                        System.identityHashCode(params));
1314                            }
1315                            mPendingInstalls.clear();
1316                        }
1317                    }
1318                    break;
1319                }
1320                case MCS_UNBIND: {
1321                    // If there is no actual work left, then time to unbind.
1322                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1323
1324                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1325                        if (mBound) {
1326                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1327
1328                            disconnectService();
1329                        }
1330                    } else if (mPendingInstalls.size() > 0) {
1331                        // There are more pending requests in queue.
1332                        // Just post MCS_BOUND message to trigger processing
1333                        // of next pending install.
1334                        mHandler.sendEmptyMessage(MCS_BOUND);
1335                    }
1336
1337                    break;
1338                }
1339                case MCS_GIVE_UP: {
1340                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1341                    HandlerParams params = mPendingInstalls.remove(0);
1342                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1343                            System.identityHashCode(params));
1344                    break;
1345                }
1346                case SEND_PENDING_BROADCAST: {
1347                    String packages[];
1348                    ArrayList<String> components[];
1349                    int size = 0;
1350                    int uids[];
1351                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1352                    synchronized (mPackages) {
1353                        if (mPendingBroadcasts == null) {
1354                            return;
1355                        }
1356                        size = mPendingBroadcasts.size();
1357                        if (size <= 0) {
1358                            // Nothing to be done. Just return
1359                            return;
1360                        }
1361                        packages = new String[size];
1362                        components = new ArrayList[size];
1363                        uids = new int[size];
1364                        int i = 0;  // filling out the above arrays
1365
1366                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1367                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1368                            Iterator<Map.Entry<String, ArrayList<String>>> it
1369                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1370                                            .entrySet().iterator();
1371                            while (it.hasNext() && i < size) {
1372                                Map.Entry<String, ArrayList<String>> ent = it.next();
1373                                packages[i] = ent.getKey();
1374                                components[i] = ent.getValue();
1375                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1376                                uids[i] = (ps != null)
1377                                        ? UserHandle.getUid(packageUserId, ps.appId)
1378                                        : -1;
1379                                i++;
1380                            }
1381                        }
1382                        size = i;
1383                        mPendingBroadcasts.clear();
1384                    }
1385                    // Send broadcasts
1386                    for (int i = 0; i < size; i++) {
1387                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1388                    }
1389                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1390                    break;
1391                }
1392                case START_CLEANING_PACKAGE: {
1393                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1394                    final String packageName = (String)msg.obj;
1395                    final int userId = msg.arg1;
1396                    final boolean andCode = msg.arg2 != 0;
1397                    synchronized (mPackages) {
1398                        if (userId == UserHandle.USER_ALL) {
1399                            int[] users = sUserManager.getUserIds();
1400                            for (int user : users) {
1401                                mSettings.addPackageToCleanLPw(
1402                                        new PackageCleanItem(user, packageName, andCode));
1403                            }
1404                        } else {
1405                            mSettings.addPackageToCleanLPw(
1406                                    new PackageCleanItem(userId, packageName, andCode));
1407                        }
1408                    }
1409                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1410                    startCleaningPackages();
1411                } break;
1412                case POST_INSTALL: {
1413                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1414
1415                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1416                    final boolean didRestore = (msg.arg2 != 0);
1417                    mRunningInstalls.delete(msg.arg1);
1418
1419                    if (data != null) {
1420                        InstallArgs args = data.args;
1421                        PackageInstalledInfo parentRes = data.res;
1422
1423                        final boolean grantPermissions = (args.installFlags
1424                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1425                        final boolean killApp = (args.installFlags
1426                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1427                        final String[] grantedPermissions = args.installGrantPermissions;
1428
1429                        // Handle the parent package
1430                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1431                                grantedPermissions, didRestore, args.installerPackageName,
1432                                args.observer);
1433
1434                        // Handle the child packages
1435                        final int childCount = (parentRes.addedChildPackages != null)
1436                                ? parentRes.addedChildPackages.size() : 0;
1437                        for (int i = 0; i < childCount; i++) {
1438                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1439                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1440                                    grantedPermissions, false, args.installerPackageName,
1441                                    args.observer);
1442                        }
1443
1444                        // Log tracing if needed
1445                        if (args.traceMethod != null) {
1446                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1447                                    args.traceCookie);
1448                        }
1449                    } else {
1450                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1451                    }
1452
1453                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1454                } break;
1455                case UPDATED_MEDIA_STATUS: {
1456                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1457                    boolean reportStatus = msg.arg1 == 1;
1458                    boolean doGc = msg.arg2 == 1;
1459                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1460                    if (doGc) {
1461                        // Force a gc to clear up stale containers.
1462                        Runtime.getRuntime().gc();
1463                    }
1464                    if (msg.obj != null) {
1465                        @SuppressWarnings("unchecked")
1466                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1467                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1468                        // Unload containers
1469                        unloadAllContainers(args);
1470                    }
1471                    if (reportStatus) {
1472                        try {
1473                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1474                            PackageHelper.getMountService().finishMediaUpdate();
1475                        } catch (RemoteException e) {
1476                            Log.e(TAG, "MountService not running?");
1477                        }
1478                    }
1479                } break;
1480                case WRITE_SETTINGS: {
1481                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1482                    synchronized (mPackages) {
1483                        removeMessages(WRITE_SETTINGS);
1484                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1485                        mSettings.writeLPr();
1486                        mDirtyUsers.clear();
1487                    }
1488                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1489                } break;
1490                case WRITE_PACKAGE_RESTRICTIONS: {
1491                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1492                    synchronized (mPackages) {
1493                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1494                        for (int userId : mDirtyUsers) {
1495                            mSettings.writePackageRestrictionsLPr(userId);
1496                        }
1497                        mDirtyUsers.clear();
1498                    }
1499                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1500                } break;
1501                case WRITE_PACKAGE_LIST: {
1502                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1503                    synchronized (mPackages) {
1504                        removeMessages(WRITE_PACKAGE_LIST);
1505                        mSettings.writePackageListLPr(msg.arg1);
1506                    }
1507                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1508                } break;
1509                case CHECK_PENDING_VERIFICATION: {
1510                    final int verificationId = msg.arg1;
1511                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1512
1513                    if ((state != null) && !state.timeoutExtended()) {
1514                        final InstallArgs args = state.getInstallArgs();
1515                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1516
1517                        Slog.i(TAG, "Verification timed out for " + originUri);
1518                        mPendingVerification.remove(verificationId);
1519
1520                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1521
1522                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1523                            Slog.i(TAG, "Continuing with installation of " + originUri);
1524                            state.setVerifierResponse(Binder.getCallingUid(),
1525                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1526                            broadcastPackageVerified(verificationId, originUri,
1527                                    PackageManager.VERIFICATION_ALLOW,
1528                                    state.getInstallArgs().getUser());
1529                            try {
1530                                ret = args.copyApk(mContainerService, true);
1531                            } catch (RemoteException e) {
1532                                Slog.e(TAG, "Could not contact the ContainerService");
1533                            }
1534                        } else {
1535                            broadcastPackageVerified(verificationId, originUri,
1536                                    PackageManager.VERIFICATION_REJECT,
1537                                    state.getInstallArgs().getUser());
1538                        }
1539
1540                        Trace.asyncTraceEnd(
1541                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1542
1543                        processPendingInstall(args, ret);
1544                        mHandler.sendEmptyMessage(MCS_UNBIND);
1545                    }
1546                    break;
1547                }
1548                case PACKAGE_VERIFIED: {
1549                    final int verificationId = msg.arg1;
1550
1551                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1552                    if (state == null) {
1553                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1554                        break;
1555                    }
1556
1557                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1558
1559                    state.setVerifierResponse(response.callerUid, response.code);
1560
1561                    if (state.isVerificationComplete()) {
1562                        mPendingVerification.remove(verificationId);
1563
1564                        final InstallArgs args = state.getInstallArgs();
1565                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1566
1567                        int ret;
1568                        if (state.isInstallAllowed()) {
1569                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1570                            broadcastPackageVerified(verificationId, originUri,
1571                                    response.code, state.getInstallArgs().getUser());
1572                            try {
1573                                ret = args.copyApk(mContainerService, true);
1574                            } catch (RemoteException e) {
1575                                Slog.e(TAG, "Could not contact the ContainerService");
1576                            }
1577                        } else {
1578                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1579                        }
1580
1581                        Trace.asyncTraceEnd(
1582                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1583
1584                        processPendingInstall(args, ret);
1585                        mHandler.sendEmptyMessage(MCS_UNBIND);
1586                    }
1587
1588                    break;
1589                }
1590                case START_INTENT_FILTER_VERIFICATIONS: {
1591                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1592                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1593                            params.replacing, params.pkg);
1594                    break;
1595                }
1596                case INTENT_FILTER_VERIFIED: {
1597                    final int verificationId = msg.arg1;
1598
1599                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1600                            verificationId);
1601                    if (state == null) {
1602                        Slog.w(TAG, "Invalid IntentFilter verification token "
1603                                + verificationId + " received");
1604                        break;
1605                    }
1606
1607                    final int userId = state.getUserId();
1608
1609                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1610                            "Processing IntentFilter verification with token:"
1611                            + verificationId + " and userId:" + userId);
1612
1613                    final IntentFilterVerificationResponse response =
1614                            (IntentFilterVerificationResponse) msg.obj;
1615
1616                    state.setVerifierResponse(response.callerUid, response.code);
1617
1618                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1619                            "IntentFilter verification with token:" + verificationId
1620                            + " and userId:" + userId
1621                            + " is settings verifier response with response code:"
1622                            + response.code);
1623
1624                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1625                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1626                                + response.getFailedDomainsString());
1627                    }
1628
1629                    if (state.isVerificationComplete()) {
1630                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1631                    } else {
1632                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1633                                "IntentFilter verification with token:" + verificationId
1634                                + " was not said to be complete");
1635                    }
1636
1637                    break;
1638                }
1639            }
1640        }
1641    }
1642
1643    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1644            boolean killApp, String[] grantedPermissions,
1645            boolean launchedForRestore, String installerPackage,
1646            IPackageInstallObserver2 installObserver) {
1647        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1648            // Send the removed broadcasts
1649            if (res.removedInfo != null) {
1650                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1651            }
1652
1653            // Now that we successfully installed the package, grant runtime
1654            // permissions if requested before broadcasting the install.
1655            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1656                    >= Build.VERSION_CODES.M) {
1657                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1658            }
1659
1660            final boolean update = res.removedInfo != null
1661                    && res.removedInfo.removedPackage != null;
1662
1663            // If this is the first time we have child packages for a disabled privileged
1664            // app that had no children, we grant requested runtime permissions to the new
1665            // children if the parent on the system image had them already granted.
1666            if (res.pkg.parentPackage != null) {
1667                synchronized (mPackages) {
1668                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1669                }
1670            }
1671
1672            synchronized (mPackages) {
1673                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1674            }
1675
1676            final String packageName = res.pkg.applicationInfo.packageName;
1677            Bundle extras = new Bundle(1);
1678            extras.putInt(Intent.EXTRA_UID, res.uid);
1679
1680            // Determine the set of users who are adding this package for
1681            // the first time vs. those who are seeing an update.
1682            int[] firstUsers = EMPTY_INT_ARRAY;
1683            int[] updateUsers = EMPTY_INT_ARRAY;
1684            if (res.origUsers == null || res.origUsers.length == 0) {
1685                firstUsers = res.newUsers;
1686            } else {
1687                for (int newUser : res.newUsers) {
1688                    boolean isNew = true;
1689                    for (int origUser : res.origUsers) {
1690                        if (origUser == newUser) {
1691                            isNew = false;
1692                            break;
1693                        }
1694                    }
1695                    if (isNew) {
1696                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1697                    } else {
1698                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1699                    }
1700                }
1701            }
1702
1703            // Send installed broadcasts if the install/update is not ephemeral
1704            if (!isEphemeral(res.pkg)) {
1705                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1706
1707                // Send added for users that see the package for the first time
1708                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1709                        extras, 0 /*flags*/, null /*targetPackage*/,
1710                        null /*finishedReceiver*/, firstUsers);
1711
1712                // Send added for users that don't see the package for the first time
1713                if (update) {
1714                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1715                }
1716                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1717                        extras, 0 /*flags*/, null /*targetPackage*/,
1718                        null /*finishedReceiver*/, updateUsers);
1719
1720                // Send replaced for users that don't see the package for the first time
1721                if (update) {
1722                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1723                            packageName, extras, 0 /*flags*/,
1724                            null /*targetPackage*/, null /*finishedReceiver*/,
1725                            updateUsers);
1726                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1727                            null /*package*/, null /*extras*/, 0 /*flags*/,
1728                            packageName /*targetPackage*/,
1729                            null /*finishedReceiver*/, updateUsers);
1730                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1731                    // First-install and we did a restore, so we're responsible for the
1732                    // first-launch broadcast.
1733                    if (DEBUG_BACKUP) {
1734                        Slog.i(TAG, "Post-restore of " + packageName
1735                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1736                    }
1737                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1738                }
1739
1740                // Send broadcast package appeared if forward locked/external for all users
1741                // treat asec-hosted packages like removable media on upgrade
1742                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1743                    if (DEBUG_INSTALL) {
1744                        Slog.i(TAG, "upgrading pkg " + res.pkg
1745                                + " is ASEC-hosted -> AVAILABLE");
1746                    }
1747                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1748                    ArrayList<String> pkgList = new ArrayList<>(1);
1749                    pkgList.add(packageName);
1750                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1751                }
1752            }
1753
1754            // Work that needs to happen on first install within each user
1755            if (firstUsers != null && firstUsers.length > 0) {
1756                synchronized (mPackages) {
1757                    for (int userId : firstUsers) {
1758                        // If this app is a browser and it's newly-installed for some
1759                        // users, clear any default-browser state in those users. The
1760                        // app's nature doesn't depend on the user, so we can just check
1761                        // its browser nature in any user and generalize.
1762                        if (packageIsBrowser(packageName, userId)) {
1763                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1764                        }
1765
1766                        // We may also need to apply pending (restored) runtime
1767                        // permission grants within these users.
1768                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1769                    }
1770                }
1771            }
1772
1773            // Log current value of "unknown sources" setting
1774            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1775                    getUnknownSourcesSettings());
1776
1777            // Force a gc to clear up things
1778            Runtime.getRuntime().gc();
1779
1780            // Remove the replaced package's older resources safely now
1781            // We delete after a gc for applications  on sdcard.
1782            if (res.removedInfo != null && res.removedInfo.args != null) {
1783                synchronized (mInstallLock) {
1784                    res.removedInfo.args.doPostDeleteLI(true);
1785                }
1786            }
1787
1788            if (!isEphemeral(res.pkg)) {
1789                // Notify DexManager that the package was installed for new users.
1790                // The updated users should already be indexed and the package code paths
1791                // should not change.
1792                // Don't notify the manager for ephemeral apps as they are not expected to
1793                // survive long enough to benefit of background optimizations.
1794                for (int userId : firstUsers) {
1795                    PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1796                    mDexManager.notifyPackageInstalled(info, userId);
1797                }
1798            }
1799        }
1800
1801        // If someone is watching installs - notify them
1802        if (installObserver != null) {
1803            try {
1804                Bundle extras = extrasForInstallResult(res);
1805                installObserver.onPackageInstalled(res.name, res.returnCode,
1806                        res.returnMsg, extras);
1807            } catch (RemoteException e) {
1808                Slog.i(TAG, "Observer no longer exists.");
1809            }
1810        }
1811    }
1812
1813    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1814            PackageParser.Package pkg) {
1815        if (pkg.parentPackage == null) {
1816            return;
1817        }
1818        if (pkg.requestedPermissions == null) {
1819            return;
1820        }
1821        final PackageSetting disabledSysParentPs = mSettings
1822                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1823        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1824                || !disabledSysParentPs.isPrivileged()
1825                || (disabledSysParentPs.childPackageNames != null
1826                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1827            return;
1828        }
1829        final int[] allUserIds = sUserManager.getUserIds();
1830        final int permCount = pkg.requestedPermissions.size();
1831        for (int i = 0; i < permCount; i++) {
1832            String permission = pkg.requestedPermissions.get(i);
1833            BasePermission bp = mSettings.mPermissions.get(permission);
1834            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1835                continue;
1836            }
1837            for (int userId : allUserIds) {
1838                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1839                        permission, userId)) {
1840                    grantRuntimePermission(pkg.packageName, permission, userId);
1841                }
1842            }
1843        }
1844    }
1845
1846    private StorageEventListener mStorageListener = new StorageEventListener() {
1847        @Override
1848        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1849            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1850                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1851                    final String volumeUuid = vol.getFsUuid();
1852
1853                    // Clean up any users or apps that were removed or recreated
1854                    // while this volume was missing
1855                    reconcileUsers(volumeUuid);
1856                    reconcileApps(volumeUuid);
1857
1858                    // Clean up any install sessions that expired or were
1859                    // cancelled while this volume was missing
1860                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1861
1862                    loadPrivatePackages(vol);
1863
1864                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1865                    unloadPrivatePackages(vol);
1866                }
1867            }
1868
1869            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1870                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1871                    updateExternalMediaStatus(true, false);
1872                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1873                    updateExternalMediaStatus(false, false);
1874                }
1875            }
1876        }
1877
1878        @Override
1879        public void onVolumeForgotten(String fsUuid) {
1880            if (TextUtils.isEmpty(fsUuid)) {
1881                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1882                return;
1883            }
1884
1885            // Remove any apps installed on the forgotten volume
1886            synchronized (mPackages) {
1887                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1888                for (PackageSetting ps : packages) {
1889                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1890                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1891                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1892                }
1893
1894                mSettings.onVolumeForgotten(fsUuid);
1895                mSettings.writeLPr();
1896            }
1897        }
1898    };
1899
1900    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1901            String[] grantedPermissions) {
1902        for (int userId : userIds) {
1903            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1904        }
1905
1906        // We could have touched GID membership, so flush out packages.list
1907        synchronized (mPackages) {
1908            mSettings.writePackageListLPr();
1909        }
1910    }
1911
1912    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1913            String[] grantedPermissions) {
1914        SettingBase sb = (SettingBase) pkg.mExtras;
1915        if (sb == null) {
1916            return;
1917        }
1918
1919        PermissionsState permissionsState = sb.getPermissionsState();
1920
1921        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1922                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1923
1924        for (String permission : pkg.requestedPermissions) {
1925            final BasePermission bp;
1926            synchronized (mPackages) {
1927                bp = mSettings.mPermissions.get(permission);
1928            }
1929            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1930                    && (grantedPermissions == null
1931                           || ArrayUtils.contains(grantedPermissions, permission))) {
1932                final int flags = permissionsState.getPermissionFlags(permission, userId);
1933                // Installer cannot change immutable permissions.
1934                if ((flags & immutableFlags) == 0) {
1935                    grantRuntimePermission(pkg.packageName, permission, userId);
1936                }
1937            }
1938        }
1939    }
1940
1941    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1942        Bundle extras = null;
1943        switch (res.returnCode) {
1944            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1945                extras = new Bundle();
1946                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1947                        res.origPermission);
1948                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1949                        res.origPackage);
1950                break;
1951            }
1952            case PackageManager.INSTALL_SUCCEEDED: {
1953                extras = new Bundle();
1954                extras.putBoolean(Intent.EXTRA_REPLACING,
1955                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1956                break;
1957            }
1958        }
1959        return extras;
1960    }
1961
1962    void scheduleWriteSettingsLocked() {
1963        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1964            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1965        }
1966    }
1967
1968    void scheduleWritePackageListLocked(int userId) {
1969        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1970            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1971            msg.arg1 = userId;
1972            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1973        }
1974    }
1975
1976    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1977        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1978        scheduleWritePackageRestrictionsLocked(userId);
1979    }
1980
1981    void scheduleWritePackageRestrictionsLocked(int userId) {
1982        final int[] userIds = (userId == UserHandle.USER_ALL)
1983                ? sUserManager.getUserIds() : new int[]{userId};
1984        for (int nextUserId : userIds) {
1985            if (!sUserManager.exists(nextUserId)) return;
1986            mDirtyUsers.add(nextUserId);
1987            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1988                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1989            }
1990        }
1991    }
1992
1993    public static PackageManagerService main(Context context, Installer installer,
1994            boolean factoryTest, boolean onlyCore) {
1995        // Self-check for initial settings.
1996        PackageManagerServiceCompilerMapping.checkProperties();
1997
1998        PackageManagerService m = new PackageManagerService(context, installer,
1999                factoryTest, onlyCore);
2000        m.enableSystemUserPackages();
2001        ServiceManager.addService("package", m);
2002        return m;
2003    }
2004
2005    private void enableSystemUserPackages() {
2006        if (!UserManager.isSplitSystemUser()) {
2007            return;
2008        }
2009        // For system user, enable apps based on the following conditions:
2010        // - app is whitelisted or belong to one of these groups:
2011        //   -- system app which has no launcher icons
2012        //   -- system app which has INTERACT_ACROSS_USERS permission
2013        //   -- system IME app
2014        // - app is not in the blacklist
2015        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2016        Set<String> enableApps = new ArraySet<>();
2017        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2018                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2019                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2020        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2021        enableApps.addAll(wlApps);
2022        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2023                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2024        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2025        enableApps.removeAll(blApps);
2026        Log.i(TAG, "Applications installed for system user: " + enableApps);
2027        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2028                UserHandle.SYSTEM);
2029        final int allAppsSize = allAps.size();
2030        synchronized (mPackages) {
2031            for (int i = 0; i < allAppsSize; i++) {
2032                String pName = allAps.get(i);
2033                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2034                // Should not happen, but we shouldn't be failing if it does
2035                if (pkgSetting == null) {
2036                    continue;
2037                }
2038                boolean install = enableApps.contains(pName);
2039                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2040                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2041                            + " for system user");
2042                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2043                }
2044            }
2045        }
2046    }
2047
2048    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2049        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2050                Context.DISPLAY_SERVICE);
2051        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2052    }
2053
2054    /**
2055     * Requests that files preopted on a secondary system partition be copied to the data partition
2056     * if possible.  Note that the actual copying of the files is accomplished by init for security
2057     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2058     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2059     */
2060    private static void requestCopyPreoptedFiles() {
2061        final int WAIT_TIME_MS = 100;
2062        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2063        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2064            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2065            // We will wait for up to 100 seconds.
2066            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2067            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2068                try {
2069                    Thread.sleep(WAIT_TIME_MS);
2070                } catch (InterruptedException e) {
2071                    // Do nothing
2072                }
2073                if (SystemClock.uptimeMillis() > timeEnd) {
2074                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2075                    Slog.wtf(TAG, "cppreopt did not finish!");
2076                    break;
2077                }
2078            }
2079        }
2080    }
2081
2082    public PackageManagerService(Context context, Installer installer,
2083            boolean factoryTest, boolean onlyCore) {
2084        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2085                SystemClock.uptimeMillis());
2086
2087        if (mSdkVersion <= 0) {
2088            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2089        }
2090
2091        mContext = context;
2092
2093        mPermissionReviewRequired = context.getResources().getBoolean(
2094                R.bool.config_permissionReviewRequired);
2095
2096        mFactoryTest = factoryTest;
2097        mOnlyCore = onlyCore;
2098        mMetrics = new DisplayMetrics();
2099        mSettings = new Settings(mPackages);
2100        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2101                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2102        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2103                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2104        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2105                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2106        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2107                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2108        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2109                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2110        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2111                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2112
2113        String separateProcesses = SystemProperties.get("debug.separate_processes");
2114        if (separateProcesses != null && separateProcesses.length() > 0) {
2115            if ("*".equals(separateProcesses)) {
2116                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2117                mSeparateProcesses = null;
2118                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2119            } else {
2120                mDefParseFlags = 0;
2121                mSeparateProcesses = separateProcesses.split(",");
2122                Slog.w(TAG, "Running with debug.separate_processes: "
2123                        + separateProcesses);
2124            }
2125        } else {
2126            mDefParseFlags = 0;
2127            mSeparateProcesses = null;
2128        }
2129
2130        mInstaller = installer;
2131        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2132                "*dexopt*");
2133        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2134        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2135
2136        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2137                FgThread.get().getLooper());
2138
2139        getDefaultDisplayMetrics(context, mMetrics);
2140
2141        SystemConfig systemConfig = SystemConfig.getInstance();
2142        mGlobalGids = systemConfig.getGlobalGids();
2143        mSystemPermissions = systemConfig.getSystemPermissions();
2144        mAvailableFeatures = systemConfig.getAvailableFeatures();
2145
2146        mProtectedPackages = new ProtectedPackages(mContext);
2147
2148        synchronized (mInstallLock) {
2149        // writer
2150        synchronized (mPackages) {
2151            mHandlerThread = new ServiceThread(TAG,
2152                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2153            mHandlerThread.start();
2154            mHandler = new PackageHandler(mHandlerThread.getLooper());
2155            mProcessLoggingHandler = new ProcessLoggingHandler();
2156            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2157
2158            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2159
2160            File dataDir = Environment.getDataDirectory();
2161            mAppInstallDir = new File(dataDir, "app");
2162            mAppLib32InstallDir = new File(dataDir, "app-lib");
2163            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2164            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2165            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2166
2167            sUserManager = new UserManagerService(context, this, mPackages);
2168
2169            // Propagate permission configuration in to package manager.
2170            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2171                    = systemConfig.getPermissions();
2172            for (int i=0; i<permConfig.size(); i++) {
2173                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2174                BasePermission bp = mSettings.mPermissions.get(perm.name);
2175                if (bp == null) {
2176                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2177                    mSettings.mPermissions.put(perm.name, bp);
2178                }
2179                if (perm.gids != null) {
2180                    bp.setGids(perm.gids, perm.perUser);
2181                }
2182            }
2183
2184            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2185            for (int i=0; i<libConfig.size(); i++) {
2186                mSharedLibraries.put(libConfig.keyAt(i),
2187                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2188            }
2189
2190            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2191
2192            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2193
2194            if (mFirstBoot) {
2195                requestCopyPreoptedFiles();
2196            }
2197
2198            String customResolverActivity = Resources.getSystem().getString(
2199                    R.string.config_customResolverActivity);
2200            if (TextUtils.isEmpty(customResolverActivity)) {
2201                customResolverActivity = null;
2202            } else {
2203                mCustomResolverComponentName = ComponentName.unflattenFromString(
2204                        customResolverActivity);
2205            }
2206
2207            long startTime = SystemClock.uptimeMillis();
2208
2209            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2210                    startTime);
2211
2212            // Set flag to monitor and not change apk file paths when
2213            // scanning install directories.
2214            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2215
2216            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2217            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2218
2219            if (bootClassPath == null) {
2220                Slog.w(TAG, "No BOOTCLASSPATH found!");
2221            }
2222
2223            if (systemServerClassPath == null) {
2224                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2225            }
2226
2227            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2228            final String[] dexCodeInstructionSets =
2229                    getDexCodeInstructionSets(
2230                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2231
2232            /**
2233             * Ensure all external libraries have had dexopt run on them.
2234             */
2235            if (mSharedLibraries.size() > 0) {
2236                // NOTE: For now, we're compiling these system "shared libraries"
2237                // (and framework jars) into all available architectures. It's possible
2238                // to compile them only when we come across an app that uses them (there's
2239                // already logic for that in scanPackageLI) but that adds some complexity.
2240                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2241                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2242                        final String lib = libEntry.path;
2243                        if (lib == null) {
2244                            continue;
2245                        }
2246
2247                        try {
2248                            // Shared libraries do not have profiles so we perform a full
2249                            // AOT compilation (if needed).
2250                            int dexoptNeeded = DexFile.getDexOptNeeded(
2251                                    lib, dexCodeInstructionSet,
2252                                    getCompilerFilterForReason(REASON_SHARED_APK),
2253                                    false /* newProfile */);
2254                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2255                                mInstaller.dexopt(lib, Process.SYSTEM_UID, "*",
2256                                        dexCodeInstructionSet, dexoptNeeded, null,
2257                                        DEXOPT_PUBLIC,
2258                                        getCompilerFilterForReason(REASON_SHARED_APK),
2259                                        StorageManager.UUID_PRIVATE_INTERNAL,
2260                                        PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK);
2261                            }
2262                        } catch (FileNotFoundException e) {
2263                            Slog.w(TAG, "Library not found: " + lib);
2264                        } catch (IOException | InstallerException e) {
2265                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2266                                    + e.getMessage());
2267                        }
2268                    }
2269                }
2270            }
2271
2272            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2273
2274            final VersionInfo ver = mSettings.getInternalVersion();
2275            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2276
2277            // when upgrading from pre-M, promote system app permissions from install to runtime
2278            mPromoteSystemApps =
2279                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2280
2281            // When upgrading from pre-N, we need to handle package extraction like first boot,
2282            // as there is no profiling data available.
2283            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2284
2285            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2286
2287            // save off the names of pre-existing system packages prior to scanning; we don't
2288            // want to automatically grant runtime permissions for new system apps
2289            if (mPromoteSystemApps) {
2290                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2291                while (pkgSettingIter.hasNext()) {
2292                    PackageSetting ps = pkgSettingIter.next();
2293                    if (isSystemApp(ps)) {
2294                        mExistingSystemPackages.add(ps.name);
2295                    }
2296                }
2297            }
2298
2299            // Collect vendor overlay packages.
2300            // (Do this before scanning any apps.)
2301            // For security and version matching reason, only consider
2302            // overlay packages if they reside in the right directory.
2303            File vendorOverlayDir;
2304            String overlaySkuDir = SystemProperties.get(VENDOR_OVERLAY_SKU_PROPERTY);
2305            if (!overlaySkuDir.isEmpty()) {
2306                vendorOverlayDir = new File(VENDOR_OVERLAY_DIR, overlaySkuDir);
2307            } else {
2308                vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2309            }
2310            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2311                    | PackageParser.PARSE_IS_SYSTEM
2312                    | PackageParser.PARSE_IS_SYSTEM_DIR
2313                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2314
2315            // Find base frameworks (resource packages without code).
2316            scanDirTracedLI(frameworkDir, mDefParseFlags
2317                    | PackageParser.PARSE_IS_SYSTEM
2318                    | PackageParser.PARSE_IS_SYSTEM_DIR
2319                    | PackageParser.PARSE_IS_PRIVILEGED,
2320                    scanFlags | SCAN_NO_DEX, 0);
2321
2322            // Collected privileged system packages.
2323            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2324            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2325                    | PackageParser.PARSE_IS_SYSTEM
2326                    | PackageParser.PARSE_IS_SYSTEM_DIR
2327                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2328
2329            // Collect ordinary system packages.
2330            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2331            scanDirTracedLI(systemAppDir, mDefParseFlags
2332                    | PackageParser.PARSE_IS_SYSTEM
2333                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2334
2335            // Collect all vendor packages.
2336            File vendorAppDir = new File("/vendor/app");
2337            try {
2338                vendorAppDir = vendorAppDir.getCanonicalFile();
2339            } catch (IOException e) {
2340                // failed to look up canonical path, continue with original one
2341            }
2342            scanDirTracedLI(vendorAppDir, mDefParseFlags
2343                    | PackageParser.PARSE_IS_SYSTEM
2344                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2345
2346            // Collect all OEM packages.
2347            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2348            scanDirTracedLI(oemAppDir, mDefParseFlags
2349                    | PackageParser.PARSE_IS_SYSTEM
2350                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2351
2352            // Prune any system packages that no longer exist.
2353            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2354            if (!mOnlyCore) {
2355                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2356                while (psit.hasNext()) {
2357                    PackageSetting ps = psit.next();
2358
2359                    /*
2360                     * If this is not a system app, it can't be a
2361                     * disable system app.
2362                     */
2363                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2364                        continue;
2365                    }
2366
2367                    /*
2368                     * If the package is scanned, it's not erased.
2369                     */
2370                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2371                    if (scannedPkg != null) {
2372                        /*
2373                         * If the system app is both scanned and in the
2374                         * disabled packages list, then it must have been
2375                         * added via OTA. Remove it from the currently
2376                         * scanned package so the previously user-installed
2377                         * application can be scanned.
2378                         */
2379                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2380                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2381                                    + ps.name + "; removing system app.  Last known codePath="
2382                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2383                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2384                                    + scannedPkg.mVersionCode);
2385                            removePackageLI(scannedPkg, true);
2386                            mExpectingBetter.put(ps.name, ps.codePath);
2387                        }
2388
2389                        continue;
2390                    }
2391
2392                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2393                        psit.remove();
2394                        logCriticalInfo(Log.WARN, "System package " + ps.name
2395                                + " no longer exists; it's data will be wiped");
2396                        // Actual deletion of code and data will be handled by later
2397                        // reconciliation step
2398                    } else {
2399                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2400                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2401                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2402                        }
2403                    }
2404                }
2405            }
2406
2407            //look for any incomplete package installations
2408            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2409            for (int i = 0; i < deletePkgsList.size(); i++) {
2410                // Actual deletion of code and data will be handled by later
2411                // reconciliation step
2412                final String packageName = deletePkgsList.get(i).name;
2413                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2414                synchronized (mPackages) {
2415                    mSettings.removePackageLPw(packageName);
2416                }
2417            }
2418
2419            //delete tmp files
2420            deleteTempPackageFiles();
2421
2422            // Remove any shared userIDs that have no associated packages
2423            mSettings.pruneSharedUsersLPw();
2424
2425            if (!mOnlyCore) {
2426                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2427                        SystemClock.uptimeMillis());
2428                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2429
2430                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2431                        | PackageParser.PARSE_FORWARD_LOCK,
2432                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2433
2434                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2435                        | PackageParser.PARSE_IS_EPHEMERAL,
2436                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2437
2438                /**
2439                 * Remove disable package settings for any updated system
2440                 * apps that were removed via an OTA. If they're not a
2441                 * previously-updated app, remove them completely.
2442                 * Otherwise, just revoke their system-level permissions.
2443                 */
2444                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2445                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2446                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2447
2448                    String msg;
2449                    if (deletedPkg == null) {
2450                        msg = "Updated system package " + deletedAppName
2451                                + " no longer exists; it's data will be wiped";
2452                        // Actual deletion of code and data will be handled by later
2453                        // reconciliation step
2454                    } else {
2455                        msg = "Updated system app + " + deletedAppName
2456                                + " no longer present; removing system privileges for "
2457                                + deletedAppName;
2458
2459                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2460
2461                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2462                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2463                    }
2464                    logCriticalInfo(Log.WARN, msg);
2465                }
2466
2467                /**
2468                 * Make sure all system apps that we expected to appear on
2469                 * the userdata partition actually showed up. If they never
2470                 * appeared, crawl back and revive the system version.
2471                 */
2472                for (int i = 0; i < mExpectingBetter.size(); i++) {
2473                    final String packageName = mExpectingBetter.keyAt(i);
2474                    if (!mPackages.containsKey(packageName)) {
2475                        final File scanFile = mExpectingBetter.valueAt(i);
2476
2477                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2478                                + " but never showed up; reverting to system");
2479
2480                        int reparseFlags = mDefParseFlags;
2481                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2482                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2483                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2484                                    | PackageParser.PARSE_IS_PRIVILEGED;
2485                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2486                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2487                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2488                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2489                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2490                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2491                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2492                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2493                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2494                        } else {
2495                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2496                            continue;
2497                        }
2498
2499                        mSettings.enableSystemPackageLPw(packageName);
2500
2501                        try {
2502                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2503                        } catch (PackageManagerException e) {
2504                            Slog.e(TAG, "Failed to parse original system package: "
2505                                    + e.getMessage());
2506                        }
2507                    }
2508                }
2509            }
2510            mExpectingBetter.clear();
2511
2512            // Resolve the storage manager.
2513            mStorageManagerPackage = getStorageManagerPackageName();
2514
2515            // Resolve protected action filters. Only the setup wizard is allowed to
2516            // have a high priority filter for these actions.
2517            mSetupWizardPackage = getSetupWizardPackageName();
2518            if (mProtectedFilters.size() > 0) {
2519                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2520                    Slog.i(TAG, "No setup wizard;"
2521                        + " All protected intents capped to priority 0");
2522                }
2523                for (ActivityIntentInfo filter : mProtectedFilters) {
2524                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2525                        if (DEBUG_FILTERS) {
2526                            Slog.i(TAG, "Found setup wizard;"
2527                                + " allow priority " + filter.getPriority() + ";"
2528                                + " package: " + filter.activity.info.packageName
2529                                + " activity: " + filter.activity.className
2530                                + " priority: " + filter.getPriority());
2531                        }
2532                        // skip setup wizard; allow it to keep the high priority filter
2533                        continue;
2534                    }
2535                    Slog.w(TAG, "Protected action; cap priority to 0;"
2536                            + " package: " + filter.activity.info.packageName
2537                            + " activity: " + filter.activity.className
2538                            + " origPrio: " + filter.getPriority());
2539                    filter.setPriority(0);
2540                }
2541            }
2542            mDeferProtectedFilters = false;
2543            mProtectedFilters.clear();
2544
2545            // Now that we know all of the shared libraries, update all clients to have
2546            // the correct library paths.
2547            updateAllSharedLibrariesLPw();
2548
2549            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2550                // NOTE: We ignore potential failures here during a system scan (like
2551                // the rest of the commands above) because there's precious little we
2552                // can do about it. A settings error is reported, though.
2553                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2554                        false /* boot complete */);
2555            }
2556
2557            // Now that we know all the packages we are keeping,
2558            // read and update their last usage times.
2559            mPackageUsage.read(mPackages);
2560            mCompilerStats.read();
2561
2562            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2563                    SystemClock.uptimeMillis());
2564            Slog.i(TAG, "Time to scan packages: "
2565                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2566                    + " seconds");
2567
2568            // If the platform SDK has changed since the last time we booted,
2569            // we need to re-grant app permission to catch any new ones that
2570            // appear.  This is really a hack, and means that apps can in some
2571            // cases get permissions that the user didn't initially explicitly
2572            // allow...  it would be nice to have some better way to handle
2573            // this situation.
2574            int updateFlags = UPDATE_PERMISSIONS_ALL;
2575            if (ver.sdkVersion != mSdkVersion) {
2576                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2577                        + mSdkVersion + "; regranting permissions for internal storage");
2578                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2579            }
2580            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2581            ver.sdkVersion = mSdkVersion;
2582
2583            // If this is the first boot or an update from pre-M, and it is a normal
2584            // boot, then we need to initialize the default preferred apps across
2585            // all defined users.
2586            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2587                for (UserInfo user : sUserManager.getUsers(true)) {
2588                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2589                    applyFactoryDefaultBrowserLPw(user.id);
2590                    primeDomainVerificationsLPw(user.id);
2591                }
2592            }
2593
2594            // Prepare storage for system user really early during boot,
2595            // since core system apps like SettingsProvider and SystemUI
2596            // can't wait for user to start
2597            final int storageFlags;
2598            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2599                storageFlags = StorageManager.FLAG_STORAGE_DE;
2600            } else {
2601                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2602            }
2603            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2604                    storageFlags);
2605
2606            // If this is first boot after an OTA, and a normal boot, then
2607            // we need to clear code cache directories.
2608            // Note that we do *not* clear the application profiles. These remain valid
2609            // across OTAs and are used to drive profile verification (post OTA) and
2610            // profile compilation (without waiting to collect a fresh set of profiles).
2611            if (mIsUpgrade && !onlyCore) {
2612                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2613                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2614                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2615                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2616                        // No apps are running this early, so no need to freeze
2617                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2618                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2619                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2620                    }
2621                }
2622                ver.fingerprint = Build.FINGERPRINT;
2623            }
2624
2625            checkDefaultBrowser();
2626
2627            // clear only after permissions and other defaults have been updated
2628            mExistingSystemPackages.clear();
2629            mPromoteSystemApps = false;
2630
2631            // All the changes are done during package scanning.
2632            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2633
2634            // can downgrade to reader
2635            mSettings.writeLPr();
2636
2637            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2638            // early on (before the package manager declares itself as early) because other
2639            // components in the system server might ask for package contexts for these apps.
2640            //
2641            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2642            // (i.e, that the data partition is unavailable).
2643            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2644                long start = System.nanoTime();
2645                List<PackageParser.Package> coreApps = new ArrayList<>();
2646                for (PackageParser.Package pkg : mPackages.values()) {
2647                    if (pkg.coreApp) {
2648                        coreApps.add(pkg);
2649                    }
2650                }
2651
2652                int[] stats = performDexOptUpgrade(coreApps, false,
2653                        getCompilerFilterForReason(REASON_CORE_APP));
2654
2655                final int elapsedTimeSeconds =
2656                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2657                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2658
2659                if (DEBUG_DEXOPT) {
2660                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2661                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2662                }
2663
2664
2665                // TODO: Should we log these stats to tron too ?
2666                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2667                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2668                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2669                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2670            }
2671
2672            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2673                    SystemClock.uptimeMillis());
2674
2675            if (!mOnlyCore) {
2676                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2677                mRequiredInstallerPackage = getRequiredInstallerLPr();
2678                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2679                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2680                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2681                        mIntentFilterVerifierComponent);
2682                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2683                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2684                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2685                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2686            } else {
2687                mRequiredVerifierPackage = null;
2688                mRequiredInstallerPackage = null;
2689                mRequiredUninstallerPackage = null;
2690                mIntentFilterVerifierComponent = null;
2691                mIntentFilterVerifier = null;
2692                mServicesSystemSharedLibraryPackageName = null;
2693                mSharedSystemSharedLibraryPackageName = null;
2694            }
2695
2696            mInstallerService = new PackageInstallerService(context, this);
2697
2698            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2699            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2700            // both the installer and resolver must be present to enable ephemeral
2701            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2702                if (DEBUG_EPHEMERAL) {
2703                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2704                            + " installer:" + ephemeralInstallerComponent);
2705                }
2706                mEphemeralResolverComponent = ephemeralResolverComponent;
2707                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2708                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2709                mEphemeralResolverConnection =
2710                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2711            } else {
2712                if (DEBUG_EPHEMERAL) {
2713                    final String missingComponent =
2714                            (ephemeralResolverComponent == null)
2715                            ? (ephemeralInstallerComponent == null)
2716                                    ? "resolver and installer"
2717                                    : "resolver"
2718                            : "installer";
2719                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2720                }
2721                mEphemeralResolverComponent = null;
2722                mEphemeralInstallerComponent = null;
2723                mEphemeralResolverConnection = null;
2724            }
2725
2726            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2727
2728            // Read and update the usage of dex files.
2729            // Do this at the end of PM init so that all the packages have their
2730            // data directory reconciled.
2731            // At this point we know the code paths of the packages, so we can validate
2732            // the disk file and build the internal cache.
2733            // The usage file is expected to be small so loading and verifying it
2734            // should take a fairly small time compare to the other activities (e.g. package
2735            // scanning).
2736            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2737            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2738            for (int userId : currentUserIds) {
2739                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2740            }
2741            mDexManager.load(userPackages);
2742        } // synchronized (mPackages)
2743        } // synchronized (mInstallLock)
2744
2745        // Now after opening every single application zip, make sure they
2746        // are all flushed.  Not really needed, but keeps things nice and
2747        // tidy.
2748        Runtime.getRuntime().gc();
2749
2750        // The initial scanning above does many calls into installd while
2751        // holding the mPackages lock, but we're mostly interested in yelling
2752        // once we have a booted system.
2753        mInstaller.setWarnIfHeld(mPackages);
2754
2755        // Expose private service for system components to use.
2756        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2757    }
2758
2759    @Override
2760    public boolean isFirstBoot() {
2761        return mFirstBoot;
2762    }
2763
2764    @Override
2765    public boolean isOnlyCoreApps() {
2766        return mOnlyCore;
2767    }
2768
2769    @Override
2770    public boolean isUpgrade() {
2771        return mIsUpgrade;
2772    }
2773
2774    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2775        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2776
2777        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2778                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2779                UserHandle.USER_SYSTEM);
2780        if (matches.size() == 1) {
2781            return matches.get(0).getComponentInfo().packageName;
2782        } else if (matches.size() == 0) {
2783            Log.e(TAG, "There should probably be a verifier, but, none were found");
2784            return null;
2785        }
2786        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2787    }
2788
2789    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2790        synchronized (mPackages) {
2791            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2792            if (libraryEntry == null) {
2793                throw new IllegalStateException("Missing required shared library:" + libraryName);
2794            }
2795            return libraryEntry.apk;
2796        }
2797    }
2798
2799    private @NonNull String getRequiredInstallerLPr() {
2800        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2801        intent.addCategory(Intent.CATEGORY_DEFAULT);
2802        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2803
2804        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2805                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2806                UserHandle.USER_SYSTEM);
2807        if (matches.size() == 1) {
2808            ResolveInfo resolveInfo = matches.get(0);
2809            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2810                throw new RuntimeException("The installer must be a privileged app");
2811            }
2812            return matches.get(0).getComponentInfo().packageName;
2813        } else {
2814            throw new RuntimeException("There must be exactly one installer; found " + matches);
2815        }
2816    }
2817
2818    private @NonNull String getRequiredUninstallerLPr() {
2819        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2820        intent.addCategory(Intent.CATEGORY_DEFAULT);
2821        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2822
2823        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2824                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2825                UserHandle.USER_SYSTEM);
2826        if (resolveInfo == null ||
2827                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2828            throw new RuntimeException("There must be exactly one uninstaller; found "
2829                    + resolveInfo);
2830        }
2831        return resolveInfo.getComponentInfo().packageName;
2832    }
2833
2834    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2835        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2836
2837        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2838                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2839                UserHandle.USER_SYSTEM);
2840        ResolveInfo best = null;
2841        final int N = matches.size();
2842        for (int i = 0; i < N; i++) {
2843            final ResolveInfo cur = matches.get(i);
2844            final String packageName = cur.getComponentInfo().packageName;
2845            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2846                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2847                continue;
2848            }
2849
2850            if (best == null || cur.priority > best.priority) {
2851                best = cur;
2852            }
2853        }
2854
2855        if (best != null) {
2856            return best.getComponentInfo().getComponentName();
2857        } else {
2858            throw new RuntimeException("There must be at least one intent filter verifier");
2859        }
2860    }
2861
2862    private @Nullable ComponentName getEphemeralResolverLPr() {
2863        final String[] packageArray =
2864                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2865        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2866            if (DEBUG_EPHEMERAL) {
2867                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2868            }
2869            return null;
2870        }
2871
2872        final int resolveFlags =
2873                MATCH_DIRECT_BOOT_AWARE
2874                | MATCH_DIRECT_BOOT_UNAWARE
2875                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2876        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2877        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2878                resolveFlags, UserHandle.USER_SYSTEM);
2879
2880        final int N = resolvers.size();
2881        if (N == 0) {
2882            if (DEBUG_EPHEMERAL) {
2883                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2884            }
2885            return null;
2886        }
2887
2888        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2889        for (int i = 0; i < N; i++) {
2890            final ResolveInfo info = resolvers.get(i);
2891
2892            if (info.serviceInfo == null) {
2893                continue;
2894            }
2895
2896            final String packageName = info.serviceInfo.packageName;
2897            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2898                if (DEBUG_EPHEMERAL) {
2899                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2900                            + " pkg: " + packageName + ", info:" + info);
2901                }
2902                continue;
2903            }
2904
2905            if (DEBUG_EPHEMERAL) {
2906                Slog.v(TAG, "Ephemeral resolver found;"
2907                        + " pkg: " + packageName + ", info:" + info);
2908            }
2909            return new ComponentName(packageName, info.serviceInfo.name);
2910        }
2911        if (DEBUG_EPHEMERAL) {
2912            Slog.v(TAG, "Ephemeral resolver NOT found");
2913        }
2914        return null;
2915    }
2916
2917    private @Nullable ComponentName getEphemeralInstallerLPr() {
2918        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2919        intent.addCategory(Intent.CATEGORY_DEFAULT);
2920        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2921
2922        final int resolveFlags =
2923                MATCH_DIRECT_BOOT_AWARE
2924                | MATCH_DIRECT_BOOT_UNAWARE
2925                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2926        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2927                resolveFlags, UserHandle.USER_SYSTEM);
2928        if (matches.size() == 0) {
2929            return null;
2930        } else if (matches.size() == 1) {
2931            return matches.get(0).getComponentInfo().getComponentName();
2932        } else {
2933            throw new RuntimeException(
2934                    "There must be at most one ephemeral installer; found " + matches);
2935        }
2936    }
2937
2938    private void primeDomainVerificationsLPw(int userId) {
2939        if (DEBUG_DOMAIN_VERIFICATION) {
2940            Slog.d(TAG, "Priming domain verifications in user " + userId);
2941        }
2942
2943        SystemConfig systemConfig = SystemConfig.getInstance();
2944        ArraySet<String> packages = systemConfig.getLinkedApps();
2945        ArraySet<String> domains = new ArraySet<String>();
2946
2947        for (String packageName : packages) {
2948            PackageParser.Package pkg = mPackages.get(packageName);
2949            if (pkg != null) {
2950                if (!pkg.isSystemApp()) {
2951                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2952                    continue;
2953                }
2954
2955                domains.clear();
2956                for (PackageParser.Activity a : pkg.activities) {
2957                    for (ActivityIntentInfo filter : a.intents) {
2958                        if (hasValidDomains(filter)) {
2959                            domains.addAll(filter.getHostsList());
2960                        }
2961                    }
2962                }
2963
2964                if (domains.size() > 0) {
2965                    if (DEBUG_DOMAIN_VERIFICATION) {
2966                        Slog.v(TAG, "      + " + packageName);
2967                    }
2968                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2969                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2970                    // and then 'always' in the per-user state actually used for intent resolution.
2971                    final IntentFilterVerificationInfo ivi;
2972                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2973                            new ArrayList<String>(domains));
2974                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2975                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2976                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2977                } else {
2978                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2979                            + "' does not handle web links");
2980                }
2981            } else {
2982                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2983            }
2984        }
2985
2986        scheduleWritePackageRestrictionsLocked(userId);
2987        scheduleWriteSettingsLocked();
2988    }
2989
2990    private void applyFactoryDefaultBrowserLPw(int userId) {
2991        // The default browser app's package name is stored in a string resource,
2992        // with a product-specific overlay used for vendor customization.
2993        String browserPkg = mContext.getResources().getString(
2994                com.android.internal.R.string.default_browser);
2995        if (!TextUtils.isEmpty(browserPkg)) {
2996            // non-empty string => required to be a known package
2997            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2998            if (ps == null) {
2999                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3000                browserPkg = null;
3001            } else {
3002                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3003            }
3004        }
3005
3006        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3007        // default.  If there's more than one, just leave everything alone.
3008        if (browserPkg == null) {
3009            calculateDefaultBrowserLPw(userId);
3010        }
3011    }
3012
3013    private void calculateDefaultBrowserLPw(int userId) {
3014        List<String> allBrowsers = resolveAllBrowserApps(userId);
3015        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3016        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3017    }
3018
3019    private List<String> resolveAllBrowserApps(int userId) {
3020        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3021        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3022                PackageManager.MATCH_ALL, userId);
3023
3024        final int count = list.size();
3025        List<String> result = new ArrayList<String>(count);
3026        for (int i=0; i<count; i++) {
3027            ResolveInfo info = list.get(i);
3028            if (info.activityInfo == null
3029                    || !info.handleAllWebDataURI
3030                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3031                    || result.contains(info.activityInfo.packageName)) {
3032                continue;
3033            }
3034            result.add(info.activityInfo.packageName);
3035        }
3036
3037        return result;
3038    }
3039
3040    private boolean packageIsBrowser(String packageName, int userId) {
3041        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3042                PackageManager.MATCH_ALL, userId);
3043        final int N = list.size();
3044        for (int i = 0; i < N; i++) {
3045            ResolveInfo info = list.get(i);
3046            if (packageName.equals(info.activityInfo.packageName)) {
3047                return true;
3048            }
3049        }
3050        return false;
3051    }
3052
3053    private void checkDefaultBrowser() {
3054        final int myUserId = UserHandle.myUserId();
3055        final String packageName = getDefaultBrowserPackageName(myUserId);
3056        if (packageName != null) {
3057            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3058            if (info == null) {
3059                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3060                synchronized (mPackages) {
3061                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3062                }
3063            }
3064        }
3065    }
3066
3067    @Override
3068    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3069            throws RemoteException {
3070        try {
3071            return super.onTransact(code, data, reply, flags);
3072        } catch (RuntimeException e) {
3073            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3074                Slog.wtf(TAG, "Package Manager Crash", e);
3075            }
3076            throw e;
3077        }
3078    }
3079
3080    static int[] appendInts(int[] cur, int[] add) {
3081        if (add == null) return cur;
3082        if (cur == null) return add;
3083        final int N = add.length;
3084        for (int i=0; i<N; i++) {
3085            cur = appendInt(cur, add[i]);
3086        }
3087        return cur;
3088    }
3089
3090    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3091        if (!sUserManager.exists(userId)) return null;
3092        if (ps == null) {
3093            return null;
3094        }
3095        final PackageParser.Package p = ps.pkg;
3096        if (p == null) {
3097            return null;
3098        }
3099
3100        final PermissionsState permissionsState = ps.getPermissionsState();
3101
3102        // Compute GIDs only if requested
3103        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3104                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3105        // Compute granted permissions only if package has requested permissions
3106        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3107                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3108        final PackageUserState state = ps.readUserState(userId);
3109
3110        return PackageParser.generatePackageInfo(p, gids, flags,
3111                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3112    }
3113
3114    @Override
3115    public void checkPackageStartable(String packageName, int userId) {
3116        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3117
3118        synchronized (mPackages) {
3119            final PackageSetting ps = mSettings.mPackages.get(packageName);
3120            if (ps == null) {
3121                throw new SecurityException("Package " + packageName + " was not found!");
3122            }
3123
3124            if (!ps.getInstalled(userId)) {
3125                throw new SecurityException(
3126                        "Package " + packageName + " was not installed for user " + userId + "!");
3127            }
3128
3129            if (mSafeMode && !ps.isSystem()) {
3130                throw new SecurityException("Package " + packageName + " not a system app!");
3131            }
3132
3133            if (mFrozenPackages.contains(packageName)) {
3134                throw new SecurityException("Package " + packageName + " is currently frozen!");
3135            }
3136
3137            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3138                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3139                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3140            }
3141        }
3142    }
3143
3144    @Override
3145    public boolean isPackageAvailable(String packageName, int userId) {
3146        if (!sUserManager.exists(userId)) return false;
3147        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3148                false /* requireFullPermission */, false /* checkShell */, "is package available");
3149        synchronized (mPackages) {
3150            PackageParser.Package p = mPackages.get(packageName);
3151            if (p != null) {
3152                final PackageSetting ps = (PackageSetting) p.mExtras;
3153                if (ps != null) {
3154                    final PackageUserState state = ps.readUserState(userId);
3155                    if (state != null) {
3156                        return PackageParser.isAvailable(state);
3157                    }
3158                }
3159            }
3160        }
3161        return false;
3162    }
3163
3164    @Override
3165    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3166        if (!sUserManager.exists(userId)) return null;
3167        flags = updateFlagsForPackage(flags, userId, packageName);
3168        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3169                false /* requireFullPermission */, false /* checkShell */, "get package info");
3170        // reader
3171        synchronized (mPackages) {
3172            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3173            PackageParser.Package p = null;
3174            if (matchFactoryOnly) {
3175                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3176                if (ps != null) {
3177                    return generatePackageInfo(ps, flags, userId);
3178                }
3179            }
3180            if (p == null) {
3181                p = mPackages.get(packageName);
3182                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3183                    return null;
3184                }
3185            }
3186            if (DEBUG_PACKAGE_INFO)
3187                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3188            if (p != null) {
3189                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3190            }
3191            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3192                final PackageSetting ps = mSettings.mPackages.get(packageName);
3193                return generatePackageInfo(ps, flags, userId);
3194            }
3195        }
3196        return null;
3197    }
3198
3199    @Override
3200    public String[] currentToCanonicalPackageNames(String[] names) {
3201        String[] out = new String[names.length];
3202        // reader
3203        synchronized (mPackages) {
3204            for (int i=names.length-1; i>=0; i--) {
3205                PackageSetting ps = mSettings.mPackages.get(names[i]);
3206                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3207            }
3208        }
3209        return out;
3210    }
3211
3212    @Override
3213    public String[] canonicalToCurrentPackageNames(String[] names) {
3214        String[] out = new String[names.length];
3215        // reader
3216        synchronized (mPackages) {
3217            for (int i=names.length-1; i>=0; i--) {
3218                String cur = mSettings.mRenamedPackages.get(names[i]);
3219                out[i] = cur != null ? cur : names[i];
3220            }
3221        }
3222        return out;
3223    }
3224
3225    @Override
3226    public int getPackageUid(String packageName, int flags, int userId) {
3227        if (!sUserManager.exists(userId)) return -1;
3228        flags = updateFlagsForPackage(flags, userId, packageName);
3229        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3230                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3231
3232        // reader
3233        synchronized (mPackages) {
3234            final PackageParser.Package p = mPackages.get(packageName);
3235            if (p != null && p.isMatch(flags)) {
3236                return UserHandle.getUid(userId, p.applicationInfo.uid);
3237            }
3238            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3239                final PackageSetting ps = mSettings.mPackages.get(packageName);
3240                if (ps != null && ps.isMatch(flags)) {
3241                    return UserHandle.getUid(userId, ps.appId);
3242                }
3243            }
3244        }
3245
3246        return -1;
3247    }
3248
3249    @Override
3250    public int[] getPackageGids(String packageName, int flags, int userId) {
3251        if (!sUserManager.exists(userId)) return null;
3252        flags = updateFlagsForPackage(flags, userId, packageName);
3253        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3254                false /* requireFullPermission */, false /* checkShell */,
3255                "getPackageGids");
3256
3257        // reader
3258        synchronized (mPackages) {
3259            final PackageParser.Package p = mPackages.get(packageName);
3260            if (p != null && p.isMatch(flags)) {
3261                PackageSetting ps = (PackageSetting) p.mExtras;
3262                return ps.getPermissionsState().computeGids(userId);
3263            }
3264            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3265                final PackageSetting ps = mSettings.mPackages.get(packageName);
3266                if (ps != null && ps.isMatch(flags)) {
3267                    return ps.getPermissionsState().computeGids(userId);
3268                }
3269            }
3270        }
3271
3272        return null;
3273    }
3274
3275    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3276        if (bp.perm != null) {
3277            return PackageParser.generatePermissionInfo(bp.perm, flags);
3278        }
3279        PermissionInfo pi = new PermissionInfo();
3280        pi.name = bp.name;
3281        pi.packageName = bp.sourcePackage;
3282        pi.nonLocalizedLabel = bp.name;
3283        pi.protectionLevel = bp.protectionLevel;
3284        return pi;
3285    }
3286
3287    @Override
3288    public PermissionInfo getPermissionInfo(String name, int flags) {
3289        // reader
3290        synchronized (mPackages) {
3291            final BasePermission p = mSettings.mPermissions.get(name);
3292            if (p != null) {
3293                return generatePermissionInfo(p, flags);
3294            }
3295            return null;
3296        }
3297    }
3298
3299    @Override
3300    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3301            int flags) {
3302        // reader
3303        synchronized (mPackages) {
3304            if (group != null && !mPermissionGroups.containsKey(group)) {
3305                // This is thrown as NameNotFoundException
3306                return null;
3307            }
3308
3309            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3310            for (BasePermission p : mSettings.mPermissions.values()) {
3311                if (group == null) {
3312                    if (p.perm == null || p.perm.info.group == null) {
3313                        out.add(generatePermissionInfo(p, flags));
3314                    }
3315                } else {
3316                    if (p.perm != null && group.equals(p.perm.info.group)) {
3317                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3318                    }
3319                }
3320            }
3321            return new ParceledListSlice<>(out);
3322        }
3323    }
3324
3325    @Override
3326    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3327        // reader
3328        synchronized (mPackages) {
3329            return PackageParser.generatePermissionGroupInfo(
3330                    mPermissionGroups.get(name), flags);
3331        }
3332    }
3333
3334    @Override
3335    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3336        // reader
3337        synchronized (mPackages) {
3338            final int N = mPermissionGroups.size();
3339            ArrayList<PermissionGroupInfo> out
3340                    = new ArrayList<PermissionGroupInfo>(N);
3341            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3342                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3343            }
3344            return new ParceledListSlice<>(out);
3345        }
3346    }
3347
3348    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3349            int userId) {
3350        if (!sUserManager.exists(userId)) return null;
3351        PackageSetting ps = mSettings.mPackages.get(packageName);
3352        if (ps != null) {
3353            if (ps.pkg == null) {
3354                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3355                if (pInfo != null) {
3356                    return pInfo.applicationInfo;
3357                }
3358                return null;
3359            }
3360            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3361                    ps.readUserState(userId), userId);
3362        }
3363        return null;
3364    }
3365
3366    @Override
3367    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3368        if (!sUserManager.exists(userId)) return null;
3369        flags = updateFlagsForApplication(flags, userId, packageName);
3370        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3371                false /* requireFullPermission */, false /* checkShell */, "get application info");
3372        // writer
3373        synchronized (mPackages) {
3374            PackageParser.Package p = mPackages.get(packageName);
3375            if (DEBUG_PACKAGE_INFO) Log.v(
3376                    TAG, "getApplicationInfo " + packageName
3377                    + ": " + p);
3378            if (p != null) {
3379                PackageSetting ps = mSettings.mPackages.get(packageName);
3380                if (ps == null) return null;
3381                // Note: isEnabledLP() does not apply here - always return info
3382                return PackageParser.generateApplicationInfo(
3383                        p, flags, ps.readUserState(userId), userId);
3384            }
3385            if ("android".equals(packageName)||"system".equals(packageName)) {
3386                return mAndroidApplication;
3387            }
3388            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3389                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3390            }
3391        }
3392        return null;
3393    }
3394
3395    @Override
3396    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3397            final IPackageDataObserver observer) {
3398        mContext.enforceCallingOrSelfPermission(
3399                android.Manifest.permission.CLEAR_APP_CACHE, null);
3400        // Queue up an async operation since clearing cache may take a little while.
3401        mHandler.post(new Runnable() {
3402            public void run() {
3403                mHandler.removeCallbacks(this);
3404                boolean success = true;
3405                synchronized (mInstallLock) {
3406                    try {
3407                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3408                    } catch (InstallerException e) {
3409                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3410                        success = false;
3411                    }
3412                }
3413                if (observer != null) {
3414                    try {
3415                        observer.onRemoveCompleted(null, success);
3416                    } catch (RemoteException e) {
3417                        Slog.w(TAG, "RemoveException when invoking call back");
3418                    }
3419                }
3420            }
3421        });
3422    }
3423
3424    @Override
3425    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3426            final IntentSender pi) {
3427        mContext.enforceCallingOrSelfPermission(
3428                android.Manifest.permission.CLEAR_APP_CACHE, null);
3429        // Queue up an async operation since clearing cache may take a little while.
3430        mHandler.post(new Runnable() {
3431            public void run() {
3432                mHandler.removeCallbacks(this);
3433                boolean success = true;
3434                synchronized (mInstallLock) {
3435                    try {
3436                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3437                    } catch (InstallerException e) {
3438                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3439                        success = false;
3440                    }
3441                }
3442                if(pi != null) {
3443                    try {
3444                        // Callback via pending intent
3445                        int code = success ? 1 : 0;
3446                        pi.sendIntent(null, code, null,
3447                                null, null);
3448                    } catch (SendIntentException e1) {
3449                        Slog.i(TAG, "Failed to send pending intent");
3450                    }
3451                }
3452            }
3453        });
3454    }
3455
3456    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3457        synchronized (mInstallLock) {
3458            try {
3459                mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3460            } catch (InstallerException e) {
3461                throw new IOException("Failed to free enough space", e);
3462            }
3463        }
3464    }
3465
3466    /**
3467     * Update given flags based on encryption status of current user.
3468     */
3469    private int updateFlags(int flags, int userId) {
3470        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3471                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3472            // Caller expressed an explicit opinion about what encryption
3473            // aware/unaware components they want to see, so fall through and
3474            // give them what they want
3475        } else {
3476            // Caller expressed no opinion, so match based on user state
3477            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3478                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3479            } else {
3480                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3481            }
3482        }
3483        return flags;
3484    }
3485
3486    private UserManagerInternal getUserManagerInternal() {
3487        if (mUserManagerInternal == null) {
3488            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3489        }
3490        return mUserManagerInternal;
3491    }
3492
3493    /**
3494     * Update given flags when being used to request {@link PackageInfo}.
3495     */
3496    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3497        boolean triaged = true;
3498        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3499                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3500            // Caller is asking for component details, so they'd better be
3501            // asking for specific encryption matching behavior, or be triaged
3502            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3503                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3504                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3505                triaged = false;
3506            }
3507        }
3508        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3509                | PackageManager.MATCH_SYSTEM_ONLY
3510                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3511            triaged = false;
3512        }
3513        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3514            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3515                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3516        }
3517        return updateFlags(flags, userId);
3518    }
3519
3520    /**
3521     * Update given flags when being used to request {@link ApplicationInfo}.
3522     */
3523    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3524        return updateFlagsForPackage(flags, userId, cookie);
3525    }
3526
3527    /**
3528     * Update given flags when being used to request {@link ComponentInfo}.
3529     */
3530    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3531        if (cookie instanceof Intent) {
3532            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3533                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3534            }
3535        }
3536
3537        boolean triaged = true;
3538        // Caller is asking for component details, so they'd better be
3539        // asking for specific encryption matching behavior, or be triaged
3540        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3541                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3542                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3543            triaged = false;
3544        }
3545        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3546            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3547                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3548        }
3549
3550        return updateFlags(flags, userId);
3551    }
3552
3553    /**
3554     * Update given flags when being used to request {@link ResolveInfo}.
3555     */
3556    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3557        // Safe mode means we shouldn't match any third-party components
3558        if (mSafeMode) {
3559            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3560        }
3561
3562        return updateFlagsForComponent(flags, userId, cookie);
3563    }
3564
3565    @Override
3566    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3567        if (!sUserManager.exists(userId)) return null;
3568        flags = updateFlagsForComponent(flags, userId, component);
3569        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3570                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3571        synchronized (mPackages) {
3572            PackageParser.Activity a = mActivities.mActivities.get(component);
3573
3574            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3575            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3576                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3577                if (ps == null) return null;
3578                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3579                        userId);
3580            }
3581            if (mResolveComponentName.equals(component)) {
3582                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3583                        new PackageUserState(), userId);
3584            }
3585        }
3586        return null;
3587    }
3588
3589    @Override
3590    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3591            String resolvedType) {
3592        synchronized (mPackages) {
3593            if (component.equals(mResolveComponentName)) {
3594                // The resolver supports EVERYTHING!
3595                return true;
3596            }
3597            PackageParser.Activity a = mActivities.mActivities.get(component);
3598            if (a == null) {
3599                return false;
3600            }
3601            for (int i=0; i<a.intents.size(); i++) {
3602                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3603                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3604                    return true;
3605                }
3606            }
3607            return false;
3608        }
3609    }
3610
3611    @Override
3612    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3613        if (!sUserManager.exists(userId)) return null;
3614        flags = updateFlagsForComponent(flags, userId, component);
3615        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3616                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3617        synchronized (mPackages) {
3618            PackageParser.Activity a = mReceivers.mActivities.get(component);
3619            if (DEBUG_PACKAGE_INFO) Log.v(
3620                TAG, "getReceiverInfo " + component + ": " + a);
3621            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3622                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3623                if (ps == null) return null;
3624                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3625                        userId);
3626            }
3627        }
3628        return null;
3629    }
3630
3631    @Override
3632    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3633        if (!sUserManager.exists(userId)) return null;
3634        flags = updateFlagsForComponent(flags, userId, component);
3635        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3636                false /* requireFullPermission */, false /* checkShell */, "get service info");
3637        synchronized (mPackages) {
3638            PackageParser.Service s = mServices.mServices.get(component);
3639            if (DEBUG_PACKAGE_INFO) Log.v(
3640                TAG, "getServiceInfo " + component + ": " + s);
3641            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3642                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3643                if (ps == null) return null;
3644                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3645                        userId);
3646            }
3647        }
3648        return null;
3649    }
3650
3651    @Override
3652    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3653        if (!sUserManager.exists(userId)) return null;
3654        flags = updateFlagsForComponent(flags, userId, component);
3655        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3656                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3657        synchronized (mPackages) {
3658            PackageParser.Provider p = mProviders.mProviders.get(component);
3659            if (DEBUG_PACKAGE_INFO) Log.v(
3660                TAG, "getProviderInfo " + component + ": " + p);
3661            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3662                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3663                if (ps == null) return null;
3664                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3665                        userId);
3666            }
3667        }
3668        return null;
3669    }
3670
3671    @Override
3672    public String[] getSystemSharedLibraryNames() {
3673        Set<String> libSet;
3674        synchronized (mPackages) {
3675            libSet = mSharedLibraries.keySet();
3676            int size = libSet.size();
3677            if (size > 0) {
3678                String[] libs = new String[size];
3679                libSet.toArray(libs);
3680                return libs;
3681            }
3682        }
3683        return null;
3684    }
3685
3686    @Override
3687    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3688        synchronized (mPackages) {
3689            return mServicesSystemSharedLibraryPackageName;
3690        }
3691    }
3692
3693    @Override
3694    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3695        synchronized (mPackages) {
3696            return mSharedSystemSharedLibraryPackageName;
3697        }
3698    }
3699
3700    @Override
3701    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3702        synchronized (mPackages) {
3703            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3704
3705            final FeatureInfo fi = new FeatureInfo();
3706            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3707                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3708            res.add(fi);
3709
3710            return new ParceledListSlice<>(res);
3711        }
3712    }
3713
3714    @Override
3715    public boolean hasSystemFeature(String name, int version) {
3716        synchronized (mPackages) {
3717            final FeatureInfo feat = mAvailableFeatures.get(name);
3718            if (feat == null) {
3719                return false;
3720            } else {
3721                return feat.version >= version;
3722            }
3723        }
3724    }
3725
3726    @Override
3727    public int checkPermission(String permName, String pkgName, int userId) {
3728        if (!sUserManager.exists(userId)) {
3729            return PackageManager.PERMISSION_DENIED;
3730        }
3731
3732        synchronized (mPackages) {
3733            final PackageParser.Package p = mPackages.get(pkgName);
3734            if (p != null && p.mExtras != null) {
3735                final PackageSetting ps = (PackageSetting) p.mExtras;
3736                final PermissionsState permissionsState = ps.getPermissionsState();
3737                if (permissionsState.hasPermission(permName, userId)) {
3738                    return PackageManager.PERMISSION_GRANTED;
3739                }
3740                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3741                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3742                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3743                    return PackageManager.PERMISSION_GRANTED;
3744                }
3745            }
3746        }
3747
3748        return PackageManager.PERMISSION_DENIED;
3749    }
3750
3751    @Override
3752    public int checkUidPermission(String permName, int uid) {
3753        final int userId = UserHandle.getUserId(uid);
3754
3755        if (!sUserManager.exists(userId)) {
3756            return PackageManager.PERMISSION_DENIED;
3757        }
3758
3759        synchronized (mPackages) {
3760            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3761            if (obj != null) {
3762                final SettingBase ps = (SettingBase) obj;
3763                final PermissionsState permissionsState = ps.getPermissionsState();
3764                if (permissionsState.hasPermission(permName, userId)) {
3765                    return PackageManager.PERMISSION_GRANTED;
3766                }
3767                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3768                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3769                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3770                    return PackageManager.PERMISSION_GRANTED;
3771                }
3772            } else {
3773                ArraySet<String> perms = mSystemPermissions.get(uid);
3774                if (perms != null) {
3775                    if (perms.contains(permName)) {
3776                        return PackageManager.PERMISSION_GRANTED;
3777                    }
3778                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3779                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3780                        return PackageManager.PERMISSION_GRANTED;
3781                    }
3782                }
3783            }
3784        }
3785
3786        return PackageManager.PERMISSION_DENIED;
3787    }
3788
3789    @Override
3790    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3791        if (UserHandle.getCallingUserId() != userId) {
3792            mContext.enforceCallingPermission(
3793                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3794                    "isPermissionRevokedByPolicy for user " + userId);
3795        }
3796
3797        if (checkPermission(permission, packageName, userId)
3798                == PackageManager.PERMISSION_GRANTED) {
3799            return false;
3800        }
3801
3802        final long identity = Binder.clearCallingIdentity();
3803        try {
3804            final int flags = getPermissionFlags(permission, packageName, userId);
3805            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3806        } finally {
3807            Binder.restoreCallingIdentity(identity);
3808        }
3809    }
3810
3811    @Override
3812    public String getPermissionControllerPackageName() {
3813        synchronized (mPackages) {
3814            return mRequiredInstallerPackage;
3815        }
3816    }
3817
3818    /**
3819     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3820     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3821     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3822     * @param message the message to log on security exception
3823     */
3824    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3825            boolean checkShell, String message) {
3826        if (userId < 0) {
3827            throw new IllegalArgumentException("Invalid userId " + userId);
3828        }
3829        if (checkShell) {
3830            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3831        }
3832        if (userId == UserHandle.getUserId(callingUid)) return;
3833        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3834            if (requireFullPermission) {
3835                mContext.enforceCallingOrSelfPermission(
3836                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3837            } else {
3838                try {
3839                    mContext.enforceCallingOrSelfPermission(
3840                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3841                } catch (SecurityException se) {
3842                    mContext.enforceCallingOrSelfPermission(
3843                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3844                }
3845            }
3846        }
3847    }
3848
3849    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3850        if (callingUid == Process.SHELL_UID) {
3851            if (userHandle >= 0
3852                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3853                throw new SecurityException("Shell does not have permission to access user "
3854                        + userHandle);
3855            } else if (userHandle < 0) {
3856                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3857                        + Debug.getCallers(3));
3858            }
3859        }
3860    }
3861
3862    private BasePermission findPermissionTreeLP(String permName) {
3863        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3864            if (permName.startsWith(bp.name) &&
3865                    permName.length() > bp.name.length() &&
3866                    permName.charAt(bp.name.length()) == '.') {
3867                return bp;
3868            }
3869        }
3870        return null;
3871    }
3872
3873    private BasePermission checkPermissionTreeLP(String permName) {
3874        if (permName != null) {
3875            BasePermission bp = findPermissionTreeLP(permName);
3876            if (bp != null) {
3877                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3878                    return bp;
3879                }
3880                throw new SecurityException("Calling uid "
3881                        + Binder.getCallingUid()
3882                        + " is not allowed to add to permission tree "
3883                        + bp.name + " owned by uid " + bp.uid);
3884            }
3885        }
3886        throw new SecurityException("No permission tree found for " + permName);
3887    }
3888
3889    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3890        if (s1 == null) {
3891            return s2 == null;
3892        }
3893        if (s2 == null) {
3894            return false;
3895        }
3896        if (s1.getClass() != s2.getClass()) {
3897            return false;
3898        }
3899        return s1.equals(s2);
3900    }
3901
3902    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3903        if (pi1.icon != pi2.icon) return false;
3904        if (pi1.logo != pi2.logo) return false;
3905        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3906        if (!compareStrings(pi1.name, pi2.name)) return false;
3907        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3908        // We'll take care of setting this one.
3909        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3910        // These are not currently stored in settings.
3911        //if (!compareStrings(pi1.group, pi2.group)) return false;
3912        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3913        //if (pi1.labelRes != pi2.labelRes) return false;
3914        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3915        return true;
3916    }
3917
3918    int permissionInfoFootprint(PermissionInfo info) {
3919        int size = info.name.length();
3920        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3921        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3922        return size;
3923    }
3924
3925    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3926        int size = 0;
3927        for (BasePermission perm : mSettings.mPermissions.values()) {
3928            if (perm.uid == tree.uid) {
3929                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3930            }
3931        }
3932        return size;
3933    }
3934
3935    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3936        // We calculate the max size of permissions defined by this uid and throw
3937        // if that plus the size of 'info' would exceed our stated maximum.
3938        if (tree.uid != Process.SYSTEM_UID) {
3939            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3940            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3941                throw new SecurityException("Permission tree size cap exceeded");
3942            }
3943        }
3944    }
3945
3946    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3947        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3948            throw new SecurityException("Label must be specified in permission");
3949        }
3950        BasePermission tree = checkPermissionTreeLP(info.name);
3951        BasePermission bp = mSettings.mPermissions.get(info.name);
3952        boolean added = bp == null;
3953        boolean changed = true;
3954        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3955        if (added) {
3956            enforcePermissionCapLocked(info, tree);
3957            bp = new BasePermission(info.name, tree.sourcePackage,
3958                    BasePermission.TYPE_DYNAMIC);
3959        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3960            throw new SecurityException(
3961                    "Not allowed to modify non-dynamic permission "
3962                    + info.name);
3963        } else {
3964            if (bp.protectionLevel == fixedLevel
3965                    && bp.perm.owner.equals(tree.perm.owner)
3966                    && bp.uid == tree.uid
3967                    && comparePermissionInfos(bp.perm.info, info)) {
3968                changed = false;
3969            }
3970        }
3971        bp.protectionLevel = fixedLevel;
3972        info = new PermissionInfo(info);
3973        info.protectionLevel = fixedLevel;
3974        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3975        bp.perm.info.packageName = tree.perm.info.packageName;
3976        bp.uid = tree.uid;
3977        if (added) {
3978            mSettings.mPermissions.put(info.name, bp);
3979        }
3980        if (changed) {
3981            if (!async) {
3982                mSettings.writeLPr();
3983            } else {
3984                scheduleWriteSettingsLocked();
3985            }
3986        }
3987        return added;
3988    }
3989
3990    @Override
3991    public boolean addPermission(PermissionInfo info) {
3992        synchronized (mPackages) {
3993            return addPermissionLocked(info, false);
3994        }
3995    }
3996
3997    @Override
3998    public boolean addPermissionAsync(PermissionInfo info) {
3999        synchronized (mPackages) {
4000            return addPermissionLocked(info, true);
4001        }
4002    }
4003
4004    @Override
4005    public void removePermission(String name) {
4006        synchronized (mPackages) {
4007            checkPermissionTreeLP(name);
4008            BasePermission bp = mSettings.mPermissions.get(name);
4009            if (bp != null) {
4010                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4011                    throw new SecurityException(
4012                            "Not allowed to modify non-dynamic permission "
4013                            + name);
4014                }
4015                mSettings.mPermissions.remove(name);
4016                mSettings.writeLPr();
4017            }
4018        }
4019    }
4020
4021    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4022            BasePermission bp) {
4023        int index = pkg.requestedPermissions.indexOf(bp.name);
4024        if (index == -1) {
4025            throw new SecurityException("Package " + pkg.packageName
4026                    + " has not requested permission " + bp.name);
4027        }
4028        if (!bp.isRuntime() && !bp.isDevelopment()) {
4029            throw new SecurityException("Permission " + bp.name
4030                    + " is not a changeable permission type");
4031        }
4032    }
4033
4034    @Override
4035    public void grantRuntimePermission(String packageName, String name, final int userId) {
4036        if (!sUserManager.exists(userId)) {
4037            Log.e(TAG, "No such user:" + userId);
4038            return;
4039        }
4040
4041        mContext.enforceCallingOrSelfPermission(
4042                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4043                "grantRuntimePermission");
4044
4045        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4046                true /* requireFullPermission */, true /* checkShell */,
4047                "grantRuntimePermission");
4048
4049        final int uid;
4050        final SettingBase sb;
4051
4052        synchronized (mPackages) {
4053            final PackageParser.Package pkg = mPackages.get(packageName);
4054            if (pkg == null) {
4055                throw new IllegalArgumentException("Unknown package: " + packageName);
4056            }
4057
4058            final BasePermission bp = mSettings.mPermissions.get(name);
4059            if (bp == null) {
4060                throw new IllegalArgumentException("Unknown permission: " + name);
4061            }
4062
4063            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4064
4065            // If a permission review is required for legacy apps we represent
4066            // their permissions as always granted runtime ones since we need
4067            // to keep the review required permission flag per user while an
4068            // install permission's state is shared across all users.
4069            if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4070                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4071                    && bp.isRuntime()) {
4072                return;
4073            }
4074
4075            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4076            sb = (SettingBase) pkg.mExtras;
4077            if (sb == null) {
4078                throw new IllegalArgumentException("Unknown package: " + packageName);
4079            }
4080
4081            final PermissionsState permissionsState = sb.getPermissionsState();
4082
4083            final int flags = permissionsState.getPermissionFlags(name, userId);
4084            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4085                throw new SecurityException("Cannot grant system fixed permission "
4086                        + name + " for package " + packageName);
4087            }
4088
4089            if (bp.isDevelopment()) {
4090                // Development permissions must be handled specially, since they are not
4091                // normal runtime permissions.  For now they apply to all users.
4092                if (permissionsState.grantInstallPermission(bp) !=
4093                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4094                    scheduleWriteSettingsLocked();
4095                }
4096                return;
4097            }
4098
4099            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4100                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4101                return;
4102            }
4103
4104            final int result = permissionsState.grantRuntimePermission(bp, userId);
4105            switch (result) {
4106                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4107                    return;
4108                }
4109
4110                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4111                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4112                    mHandler.post(new Runnable() {
4113                        @Override
4114                        public void run() {
4115                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4116                        }
4117                    });
4118                }
4119                break;
4120            }
4121
4122            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4123
4124            // Not critical if that is lost - app has to request again.
4125            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4126        }
4127
4128        // Only need to do this if user is initialized. Otherwise it's a new user
4129        // and there are no processes running as the user yet and there's no need
4130        // to make an expensive call to remount processes for the changed permissions.
4131        if (READ_EXTERNAL_STORAGE.equals(name)
4132                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4133            final long token = Binder.clearCallingIdentity();
4134            try {
4135                if (sUserManager.isInitialized(userId)) {
4136                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4137                            MountServiceInternal.class);
4138                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4139                }
4140            } finally {
4141                Binder.restoreCallingIdentity(token);
4142            }
4143        }
4144    }
4145
4146    @Override
4147    public void revokeRuntimePermission(String packageName, String name, int userId) {
4148        if (!sUserManager.exists(userId)) {
4149            Log.e(TAG, "No such user:" + userId);
4150            return;
4151        }
4152
4153        mContext.enforceCallingOrSelfPermission(
4154                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4155                "revokeRuntimePermission");
4156
4157        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4158                true /* requireFullPermission */, true /* checkShell */,
4159                "revokeRuntimePermission");
4160
4161        final int appId;
4162
4163        synchronized (mPackages) {
4164            final PackageParser.Package pkg = mPackages.get(packageName);
4165            if (pkg == null) {
4166                throw new IllegalArgumentException("Unknown package: " + packageName);
4167            }
4168
4169            final BasePermission bp = mSettings.mPermissions.get(name);
4170            if (bp == null) {
4171                throw new IllegalArgumentException("Unknown permission: " + name);
4172            }
4173
4174            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4175
4176            // If a permission review is required for legacy apps we represent
4177            // their permissions as always granted runtime ones since we need
4178            // to keep the review required permission flag per user while an
4179            // install permission's state is shared across all users.
4180            if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4181                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4182                    && bp.isRuntime()) {
4183                return;
4184            }
4185
4186            SettingBase sb = (SettingBase) pkg.mExtras;
4187            if (sb == null) {
4188                throw new IllegalArgumentException("Unknown package: " + packageName);
4189            }
4190
4191            final PermissionsState permissionsState = sb.getPermissionsState();
4192
4193            final int flags = permissionsState.getPermissionFlags(name, userId);
4194            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4195                throw new SecurityException("Cannot revoke system fixed permission "
4196                        + name + " for package " + packageName);
4197            }
4198
4199            if (bp.isDevelopment()) {
4200                // Development permissions must be handled specially, since they are not
4201                // normal runtime permissions.  For now they apply to all users.
4202                if (permissionsState.revokeInstallPermission(bp) !=
4203                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4204                    scheduleWriteSettingsLocked();
4205                }
4206                return;
4207            }
4208
4209            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4210                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4211                return;
4212            }
4213
4214            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4215
4216            // Critical, after this call app should never have the permission.
4217            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4218
4219            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4220        }
4221
4222        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4223    }
4224
4225    @Override
4226    public void resetRuntimePermissions() {
4227        mContext.enforceCallingOrSelfPermission(
4228                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4229                "revokeRuntimePermission");
4230
4231        int callingUid = Binder.getCallingUid();
4232        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4233            mContext.enforceCallingOrSelfPermission(
4234                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4235                    "resetRuntimePermissions");
4236        }
4237
4238        synchronized (mPackages) {
4239            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4240            for (int userId : UserManagerService.getInstance().getUserIds()) {
4241                final int packageCount = mPackages.size();
4242                for (int i = 0; i < packageCount; i++) {
4243                    PackageParser.Package pkg = mPackages.valueAt(i);
4244                    if (!(pkg.mExtras instanceof PackageSetting)) {
4245                        continue;
4246                    }
4247                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4248                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4249                }
4250            }
4251        }
4252    }
4253
4254    @Override
4255    public int getPermissionFlags(String name, String packageName, int userId) {
4256        if (!sUserManager.exists(userId)) {
4257            return 0;
4258        }
4259
4260        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4261
4262        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4263                true /* requireFullPermission */, false /* checkShell */,
4264                "getPermissionFlags");
4265
4266        synchronized (mPackages) {
4267            final PackageParser.Package pkg = mPackages.get(packageName);
4268            if (pkg == null) {
4269                return 0;
4270            }
4271
4272            final BasePermission bp = mSettings.mPermissions.get(name);
4273            if (bp == null) {
4274                return 0;
4275            }
4276
4277            SettingBase sb = (SettingBase) pkg.mExtras;
4278            if (sb == null) {
4279                return 0;
4280            }
4281
4282            PermissionsState permissionsState = sb.getPermissionsState();
4283            return permissionsState.getPermissionFlags(name, userId);
4284        }
4285    }
4286
4287    @Override
4288    public void updatePermissionFlags(String name, String packageName, int flagMask,
4289            int flagValues, int userId) {
4290        if (!sUserManager.exists(userId)) {
4291            return;
4292        }
4293
4294        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4295
4296        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4297                true /* requireFullPermission */, true /* checkShell */,
4298                "updatePermissionFlags");
4299
4300        // Only the system can change these flags and nothing else.
4301        if (getCallingUid() != Process.SYSTEM_UID) {
4302            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4303            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4304            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4305            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4306            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4307        }
4308
4309        synchronized (mPackages) {
4310            final PackageParser.Package pkg = mPackages.get(packageName);
4311            if (pkg == null) {
4312                throw new IllegalArgumentException("Unknown package: " + packageName);
4313            }
4314
4315            final BasePermission bp = mSettings.mPermissions.get(name);
4316            if (bp == null) {
4317                throw new IllegalArgumentException("Unknown permission: " + name);
4318            }
4319
4320            SettingBase sb = (SettingBase) pkg.mExtras;
4321            if (sb == null) {
4322                throw new IllegalArgumentException("Unknown package: " + packageName);
4323            }
4324
4325            PermissionsState permissionsState = sb.getPermissionsState();
4326
4327            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4328
4329            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4330                // Install and runtime permissions are stored in different places,
4331                // so figure out what permission changed and persist the change.
4332                if (permissionsState.getInstallPermissionState(name) != null) {
4333                    scheduleWriteSettingsLocked();
4334                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4335                        || hadState) {
4336                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4337                }
4338            }
4339        }
4340    }
4341
4342    /**
4343     * Update the permission flags for all packages and runtime permissions of a user in order
4344     * to allow device or profile owner to remove POLICY_FIXED.
4345     */
4346    @Override
4347    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4348        if (!sUserManager.exists(userId)) {
4349            return;
4350        }
4351
4352        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4353
4354        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4355                true /* requireFullPermission */, true /* checkShell */,
4356                "updatePermissionFlagsForAllApps");
4357
4358        // Only the system can change system fixed flags.
4359        if (getCallingUid() != Process.SYSTEM_UID) {
4360            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4361            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4362        }
4363
4364        synchronized (mPackages) {
4365            boolean changed = false;
4366            final int packageCount = mPackages.size();
4367            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4368                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4369                SettingBase sb = (SettingBase) pkg.mExtras;
4370                if (sb == null) {
4371                    continue;
4372                }
4373                PermissionsState permissionsState = sb.getPermissionsState();
4374                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4375                        userId, flagMask, flagValues);
4376            }
4377            if (changed) {
4378                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4379            }
4380        }
4381    }
4382
4383    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4384        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4385                != PackageManager.PERMISSION_GRANTED
4386            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4387                != PackageManager.PERMISSION_GRANTED) {
4388            throw new SecurityException(message + " requires "
4389                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4390                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4391        }
4392    }
4393
4394    @Override
4395    public boolean shouldShowRequestPermissionRationale(String permissionName,
4396            String packageName, int userId) {
4397        if (UserHandle.getCallingUserId() != userId) {
4398            mContext.enforceCallingPermission(
4399                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4400                    "canShowRequestPermissionRationale for user " + userId);
4401        }
4402
4403        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4404        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4405            return false;
4406        }
4407
4408        if (checkPermission(permissionName, packageName, userId)
4409                == PackageManager.PERMISSION_GRANTED) {
4410            return false;
4411        }
4412
4413        final int flags;
4414
4415        final long identity = Binder.clearCallingIdentity();
4416        try {
4417            flags = getPermissionFlags(permissionName,
4418                    packageName, userId);
4419        } finally {
4420            Binder.restoreCallingIdentity(identity);
4421        }
4422
4423        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4424                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4425                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4426
4427        if ((flags & fixedFlags) != 0) {
4428            return false;
4429        }
4430
4431        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4432    }
4433
4434    @Override
4435    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4436        mContext.enforceCallingOrSelfPermission(
4437                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4438                "addOnPermissionsChangeListener");
4439
4440        synchronized (mPackages) {
4441            mOnPermissionChangeListeners.addListenerLocked(listener);
4442        }
4443    }
4444
4445    @Override
4446    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4447        synchronized (mPackages) {
4448            mOnPermissionChangeListeners.removeListenerLocked(listener);
4449        }
4450    }
4451
4452    @Override
4453    public boolean isProtectedBroadcast(String actionName) {
4454        synchronized (mPackages) {
4455            if (mProtectedBroadcasts.contains(actionName)) {
4456                return true;
4457            } else if (actionName != null) {
4458                // TODO: remove these terrible hacks
4459                if (actionName.startsWith("android.net.netmon.lingerExpired")
4460                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4461                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4462                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4463                    return true;
4464                }
4465            }
4466        }
4467        return false;
4468    }
4469
4470    @Override
4471    public int checkSignatures(String pkg1, String pkg2) {
4472        synchronized (mPackages) {
4473            final PackageParser.Package p1 = mPackages.get(pkg1);
4474            final PackageParser.Package p2 = mPackages.get(pkg2);
4475            if (p1 == null || p1.mExtras == null
4476                    || p2 == null || p2.mExtras == null) {
4477                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4478            }
4479            return compareSignatures(p1.mSignatures, p2.mSignatures);
4480        }
4481    }
4482
4483    @Override
4484    public int checkUidSignatures(int uid1, int uid2) {
4485        // Map to base uids.
4486        uid1 = UserHandle.getAppId(uid1);
4487        uid2 = UserHandle.getAppId(uid2);
4488        // reader
4489        synchronized (mPackages) {
4490            Signature[] s1;
4491            Signature[] s2;
4492            Object obj = mSettings.getUserIdLPr(uid1);
4493            if (obj != null) {
4494                if (obj instanceof SharedUserSetting) {
4495                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4496                } else if (obj instanceof PackageSetting) {
4497                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4498                } else {
4499                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4500                }
4501            } else {
4502                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4503            }
4504            obj = mSettings.getUserIdLPr(uid2);
4505            if (obj != null) {
4506                if (obj instanceof SharedUserSetting) {
4507                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4508                } else if (obj instanceof PackageSetting) {
4509                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4510                } else {
4511                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4512                }
4513            } else {
4514                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4515            }
4516            return compareSignatures(s1, s2);
4517        }
4518    }
4519
4520    /**
4521     * This method should typically only be used when granting or revoking
4522     * permissions, since the app may immediately restart after this call.
4523     * <p>
4524     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4525     * guard your work against the app being relaunched.
4526     */
4527    private void killUid(int appId, int userId, String reason) {
4528        final long identity = Binder.clearCallingIdentity();
4529        try {
4530            IActivityManager am = ActivityManagerNative.getDefault();
4531            if (am != null) {
4532                try {
4533                    am.killUid(appId, userId, reason);
4534                } catch (RemoteException e) {
4535                    /* ignore - same process */
4536                }
4537            }
4538        } finally {
4539            Binder.restoreCallingIdentity(identity);
4540        }
4541    }
4542
4543    /**
4544     * Compares two sets of signatures. Returns:
4545     * <br />
4546     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4547     * <br />
4548     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4549     * <br />
4550     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4551     * <br />
4552     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4553     * <br />
4554     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4555     */
4556    static int compareSignatures(Signature[] s1, Signature[] s2) {
4557        if (s1 == null) {
4558            return s2 == null
4559                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4560                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4561        }
4562
4563        if (s2 == null) {
4564            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4565        }
4566
4567        if (s1.length != s2.length) {
4568            return PackageManager.SIGNATURE_NO_MATCH;
4569        }
4570
4571        // Since both signature sets are of size 1, we can compare without HashSets.
4572        if (s1.length == 1) {
4573            return s1[0].equals(s2[0]) ?
4574                    PackageManager.SIGNATURE_MATCH :
4575                    PackageManager.SIGNATURE_NO_MATCH;
4576        }
4577
4578        ArraySet<Signature> set1 = new ArraySet<Signature>();
4579        for (Signature sig : s1) {
4580            set1.add(sig);
4581        }
4582        ArraySet<Signature> set2 = new ArraySet<Signature>();
4583        for (Signature sig : s2) {
4584            set2.add(sig);
4585        }
4586        // Make sure s2 contains all signatures in s1.
4587        if (set1.equals(set2)) {
4588            return PackageManager.SIGNATURE_MATCH;
4589        }
4590        return PackageManager.SIGNATURE_NO_MATCH;
4591    }
4592
4593    /**
4594     * If the database version for this type of package (internal storage or
4595     * external storage) is less than the version where package signatures
4596     * were updated, return true.
4597     */
4598    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4599        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4600        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4601    }
4602
4603    /**
4604     * Used for backward compatibility to make sure any packages with
4605     * certificate chains get upgraded to the new style. {@code existingSigs}
4606     * will be in the old format (since they were stored on disk from before the
4607     * system upgrade) and {@code scannedSigs} will be in the newer format.
4608     */
4609    private int compareSignaturesCompat(PackageSignatures existingSigs,
4610            PackageParser.Package scannedPkg) {
4611        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4612            return PackageManager.SIGNATURE_NO_MATCH;
4613        }
4614
4615        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4616        for (Signature sig : existingSigs.mSignatures) {
4617            existingSet.add(sig);
4618        }
4619        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4620        for (Signature sig : scannedPkg.mSignatures) {
4621            try {
4622                Signature[] chainSignatures = sig.getChainSignatures();
4623                for (Signature chainSig : chainSignatures) {
4624                    scannedCompatSet.add(chainSig);
4625                }
4626            } catch (CertificateEncodingException e) {
4627                scannedCompatSet.add(sig);
4628            }
4629        }
4630        /*
4631         * Make sure the expanded scanned set contains all signatures in the
4632         * existing one.
4633         */
4634        if (scannedCompatSet.equals(existingSet)) {
4635            // Migrate the old signatures to the new scheme.
4636            existingSigs.assignSignatures(scannedPkg.mSignatures);
4637            // The new KeySets will be re-added later in the scanning process.
4638            synchronized (mPackages) {
4639                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4640            }
4641            return PackageManager.SIGNATURE_MATCH;
4642        }
4643        return PackageManager.SIGNATURE_NO_MATCH;
4644    }
4645
4646    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4647        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4648        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4649    }
4650
4651    private int compareSignaturesRecover(PackageSignatures existingSigs,
4652            PackageParser.Package scannedPkg) {
4653        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4654            return PackageManager.SIGNATURE_NO_MATCH;
4655        }
4656
4657        String msg = null;
4658        try {
4659            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4660                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4661                        + scannedPkg.packageName);
4662                return PackageManager.SIGNATURE_MATCH;
4663            }
4664        } catch (CertificateException e) {
4665            msg = e.getMessage();
4666        }
4667
4668        logCriticalInfo(Log.INFO,
4669                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4670        return PackageManager.SIGNATURE_NO_MATCH;
4671    }
4672
4673    @Override
4674    public List<String> getAllPackages() {
4675        synchronized (mPackages) {
4676            return new ArrayList<String>(mPackages.keySet());
4677        }
4678    }
4679
4680    @Override
4681    public String[] getPackagesForUid(int uid) {
4682        final int userId = UserHandle.getUserId(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 int N = sus.packages.size();
4690                String[] res = new String[N];
4691                final Iterator<PackageSetting> it = sus.packages.iterator();
4692                int i = 0;
4693                while (it.hasNext()) {
4694                    PackageSetting ps = it.next();
4695                    if (ps.getInstalled(userId)) {
4696                        res[i++] = ps.name;
4697                    } else {
4698                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4699                    }
4700                }
4701                return res;
4702            } else if (obj instanceof PackageSetting) {
4703                final PackageSetting ps = (PackageSetting) obj;
4704                return new String[] { ps.name };
4705            }
4706        }
4707        return null;
4708    }
4709
4710    @Override
4711    public String getNameForUid(int uid) {
4712        // reader
4713        synchronized (mPackages) {
4714            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4715            if (obj instanceof SharedUserSetting) {
4716                final SharedUserSetting sus = (SharedUserSetting) obj;
4717                return sus.name + ":" + sus.userId;
4718            } else if (obj instanceof PackageSetting) {
4719                final PackageSetting ps = (PackageSetting) obj;
4720                return ps.name;
4721            }
4722        }
4723        return null;
4724    }
4725
4726    @Override
4727    public int getUidForSharedUser(String sharedUserName) {
4728        if(sharedUserName == null) {
4729            return -1;
4730        }
4731        // reader
4732        synchronized (mPackages) {
4733            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4734            if (suid == null) {
4735                return -1;
4736            }
4737            return suid.userId;
4738        }
4739    }
4740
4741    @Override
4742    public int getFlagsForUid(int uid) {
4743        synchronized (mPackages) {
4744            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4745            if (obj instanceof SharedUserSetting) {
4746                final SharedUserSetting sus = (SharedUserSetting) obj;
4747                return sus.pkgFlags;
4748            } else if (obj instanceof PackageSetting) {
4749                final PackageSetting ps = (PackageSetting) obj;
4750                return ps.pkgFlags;
4751            }
4752        }
4753        return 0;
4754    }
4755
4756    @Override
4757    public int getPrivateFlagsForUid(int uid) {
4758        synchronized (mPackages) {
4759            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4760            if (obj instanceof SharedUserSetting) {
4761                final SharedUserSetting sus = (SharedUserSetting) obj;
4762                return sus.pkgPrivateFlags;
4763            } else if (obj instanceof PackageSetting) {
4764                final PackageSetting ps = (PackageSetting) obj;
4765                return ps.pkgPrivateFlags;
4766            }
4767        }
4768        return 0;
4769    }
4770
4771    @Override
4772    public boolean isUidPrivileged(int uid) {
4773        uid = UserHandle.getAppId(uid);
4774        // reader
4775        synchronized (mPackages) {
4776            Object obj = mSettings.getUserIdLPr(uid);
4777            if (obj instanceof SharedUserSetting) {
4778                final SharedUserSetting sus = (SharedUserSetting) obj;
4779                final Iterator<PackageSetting> it = sus.packages.iterator();
4780                while (it.hasNext()) {
4781                    if (it.next().isPrivileged()) {
4782                        return true;
4783                    }
4784                }
4785            } else if (obj instanceof PackageSetting) {
4786                final PackageSetting ps = (PackageSetting) obj;
4787                return ps.isPrivileged();
4788            }
4789        }
4790        return false;
4791    }
4792
4793    @Override
4794    public String[] getAppOpPermissionPackages(String permissionName) {
4795        synchronized (mPackages) {
4796            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4797            if (pkgs == null) {
4798                return null;
4799            }
4800            return pkgs.toArray(new String[pkgs.size()]);
4801        }
4802    }
4803
4804    @Override
4805    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4806            int flags, int userId) {
4807        try {
4808            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4809
4810            if (!sUserManager.exists(userId)) return null;
4811            flags = updateFlagsForResolve(flags, userId, intent);
4812            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4813                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4814
4815            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4816            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4817                    flags, userId);
4818            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4819
4820            final ResolveInfo bestChoice =
4821                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4822            return bestChoice;
4823        } finally {
4824            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4825        }
4826    }
4827
4828    @Override
4829    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4830            IntentFilter filter, int match, ComponentName activity) {
4831        final int userId = UserHandle.getCallingUserId();
4832        if (DEBUG_PREFERRED) {
4833            Log.v(TAG, "setLastChosenActivity intent=" + intent
4834                + " resolvedType=" + resolvedType
4835                + " flags=" + flags
4836                + " filter=" + filter
4837                + " match=" + match
4838                + " activity=" + activity);
4839            filter.dump(new PrintStreamPrinter(System.out), "    ");
4840        }
4841        intent.setComponent(null);
4842        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4843                userId);
4844        // Find any earlier preferred or last chosen entries and nuke them
4845        findPreferredActivity(intent, resolvedType,
4846                flags, query, 0, false, true, false, userId);
4847        // Add the new activity as the last chosen for this filter
4848        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4849                "Setting last chosen");
4850    }
4851
4852    @Override
4853    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4854        final int userId = UserHandle.getCallingUserId();
4855        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4856        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4857                userId);
4858        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4859                false, false, false, userId);
4860    }
4861
4862    private boolean isEphemeralDisabled() {
4863        // ephemeral apps have been disabled across the board
4864        if (DISABLE_EPHEMERAL_APPS) {
4865            return true;
4866        }
4867        // system isn't up yet; can't read settings, so, assume no ephemeral apps
4868        if (!mSystemReady) {
4869            return true;
4870        }
4871        // we can't get a content resolver until the system is ready; these checks must happen last
4872        final ContentResolver resolver = mContext.getContentResolver();
4873        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4874            return true;
4875        }
4876        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4877    }
4878
4879    private boolean isEphemeralAllowed(
4880            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4881            boolean skipPackageCheck) {
4882        // Short circuit and return early if possible.
4883        if (isEphemeralDisabled()) {
4884            return false;
4885        }
4886        final int callingUser = UserHandle.getCallingUserId();
4887        if (callingUser != UserHandle.USER_SYSTEM) {
4888            return false;
4889        }
4890        if (mEphemeralResolverConnection == null) {
4891            return false;
4892        }
4893        if (intent.getComponent() != null) {
4894            return false;
4895        }
4896        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4897            return false;
4898        }
4899        if (!skipPackageCheck && intent.getPackage() != null) {
4900            return false;
4901        }
4902        final boolean isWebUri = hasWebURI(intent);
4903        if (!isWebUri || intent.getData().getHost() == null) {
4904            return false;
4905        }
4906        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4907        synchronized (mPackages) {
4908            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4909            for (int n = 0; n < count; n++) {
4910                ResolveInfo info = resolvedActivities.get(n);
4911                String packageName = info.activityInfo.packageName;
4912                PackageSetting ps = mSettings.mPackages.get(packageName);
4913                if (ps != null) {
4914                    // Try to get the status from User settings first
4915                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4916                    int status = (int) (packedStatus >> 32);
4917                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4918                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4919                        if (DEBUG_EPHEMERAL) {
4920                            Slog.v(TAG, "DENY ephemeral apps;"
4921                                + " pkg: " + packageName + ", status: " + status);
4922                        }
4923                        return false;
4924                    }
4925                }
4926            }
4927        }
4928        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4929        return true;
4930    }
4931
4932    private static EphemeralResolveInfo getEphemeralResolveInfo(
4933            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4934            String resolvedType, int userId, String packageName) {
4935        final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4936                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4937        final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4938                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4939        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4940                ephemeralPrefixCount);
4941        final int[] shaPrefix = digest.getDigestPrefix();
4942        final byte[][] digestBytes = digest.getDigestBytes();
4943        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4944                resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4945        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4946            // No hash prefix match; there are no ephemeral apps for this domain.
4947            return null;
4948        }
4949
4950        // Go in reverse order so we match the narrowest scope first.
4951        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4952            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4953                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4954                    continue;
4955                }
4956                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4957                // No filters; this should never happen.
4958                if (filters.isEmpty()) {
4959                    continue;
4960                }
4961                if (packageName != null
4962                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4963                    continue;
4964                }
4965                // We have a domain match; resolve the filters to see if anything matches.
4966                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4967                for (int j = filters.size() - 1; j >= 0; --j) {
4968                    final EphemeralResolveIntentInfo intentInfo =
4969                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4970                    ephemeralResolver.addFilter(intentInfo);
4971                }
4972                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4973                        intent, resolvedType, false /*defaultOnly*/, userId);
4974                if (!matchedResolveInfoList.isEmpty()) {
4975                    return matchedResolveInfoList.get(0);
4976                }
4977            }
4978        }
4979        // Hash or filter mis-match; no ephemeral apps for this domain.
4980        return null;
4981    }
4982
4983    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4984            int flags, List<ResolveInfo> query, int userId) {
4985        if (query != null) {
4986            final int N = query.size();
4987            if (N == 1) {
4988                return query.get(0);
4989            } else if (N > 1) {
4990                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4991                // If there is more than one activity with the same priority,
4992                // then let the user decide between them.
4993                ResolveInfo r0 = query.get(0);
4994                ResolveInfo r1 = query.get(1);
4995                if (DEBUG_INTENT_MATCHING || debug) {
4996                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4997                            + r1.activityInfo.name + "=" + r1.priority);
4998                }
4999                // If the first activity has a higher priority, or a different
5000                // default, then it is always desirable to pick it.
5001                if (r0.priority != r1.priority
5002                        || r0.preferredOrder != r1.preferredOrder
5003                        || r0.isDefault != r1.isDefault) {
5004                    return query.get(0);
5005                }
5006                // If we have saved a preference for a preferred activity for
5007                // this Intent, use that.
5008                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5009                        flags, query, r0.priority, true, false, debug, userId);
5010                if (ri != null) {
5011                    return ri;
5012                }
5013                ri = new ResolveInfo(mResolveInfo);
5014                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5015                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5016                // If all of the options come from the same package, show the application's
5017                // label and icon instead of the generic resolver's.
5018                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5019                // and then throw away the ResolveInfo itself, meaning that the caller loses
5020                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5021                // a fallback for this case; we only set the target package's resources on
5022                // the ResolveInfo, not the ActivityInfo.
5023                final String intentPackage = intent.getPackage();
5024                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5025                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5026                    ri.resolvePackageName = intentPackage;
5027                    if (userNeedsBadging(userId)) {
5028                        ri.noResourceId = true;
5029                    } else {
5030                        ri.icon = appi.icon;
5031                    }
5032                    ri.iconResourceId = appi.icon;
5033                    ri.labelRes = appi.labelRes;
5034                }
5035                ri.activityInfo.applicationInfo = new ApplicationInfo(
5036                        ri.activityInfo.applicationInfo);
5037                if (userId != 0) {
5038                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5039                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5040                }
5041                // Make sure that the resolver is displayable in car mode
5042                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5043                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5044                return ri;
5045            }
5046        }
5047        return null;
5048    }
5049
5050    /**
5051     * Return true if the given list is not empty and all of its contents have
5052     * an activityInfo with the given package name.
5053     */
5054    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5055        if (ArrayUtils.isEmpty(list)) {
5056            return false;
5057        }
5058        for (int i = 0, N = list.size(); i < N; i++) {
5059            final ResolveInfo ri = list.get(i);
5060            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5061            if (ai == null || !packageName.equals(ai.packageName)) {
5062                return false;
5063            }
5064        }
5065        return true;
5066    }
5067
5068    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5069            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5070        final int N = query.size();
5071        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5072                .get(userId);
5073        // Get the list of persistent preferred activities that handle the intent
5074        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5075        List<PersistentPreferredActivity> pprefs = ppir != null
5076                ? ppir.queryIntent(intent, resolvedType,
5077                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5078                : null;
5079        if (pprefs != null && pprefs.size() > 0) {
5080            final int M = pprefs.size();
5081            for (int i=0; i<M; i++) {
5082                final PersistentPreferredActivity ppa = pprefs.get(i);
5083                if (DEBUG_PREFERRED || debug) {
5084                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5085                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5086                            + "\n  component=" + ppa.mComponent);
5087                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5088                }
5089                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5090                        flags | MATCH_DISABLED_COMPONENTS, userId);
5091                if (DEBUG_PREFERRED || debug) {
5092                    Slog.v(TAG, "Found persistent preferred activity:");
5093                    if (ai != null) {
5094                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5095                    } else {
5096                        Slog.v(TAG, "  null");
5097                    }
5098                }
5099                if (ai == null) {
5100                    // This previously registered persistent preferred activity
5101                    // component is no longer known. Ignore it and do NOT remove it.
5102                    continue;
5103                }
5104                for (int j=0; j<N; j++) {
5105                    final ResolveInfo ri = query.get(j);
5106                    if (!ri.activityInfo.applicationInfo.packageName
5107                            .equals(ai.applicationInfo.packageName)) {
5108                        continue;
5109                    }
5110                    if (!ri.activityInfo.name.equals(ai.name)) {
5111                        continue;
5112                    }
5113                    //  Found a persistent preference that can handle the intent.
5114                    if (DEBUG_PREFERRED || debug) {
5115                        Slog.v(TAG, "Returning persistent preferred activity: " +
5116                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5117                    }
5118                    return ri;
5119                }
5120            }
5121        }
5122        return null;
5123    }
5124
5125    // TODO: handle preferred activities missing while user has amnesia
5126    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5127            List<ResolveInfo> query, int priority, boolean always,
5128            boolean removeMatches, boolean debug, int userId) {
5129        if (!sUserManager.exists(userId)) return null;
5130        flags = updateFlagsForResolve(flags, userId, intent);
5131        // writer
5132        synchronized (mPackages) {
5133            if (intent.getSelector() != null) {
5134                intent = intent.getSelector();
5135            }
5136            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5137
5138            // Try to find a matching persistent preferred activity.
5139            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5140                    debug, userId);
5141
5142            // If a persistent preferred activity matched, use it.
5143            if (pri != null) {
5144                return pri;
5145            }
5146
5147            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5148            // Get the list of preferred activities that handle the intent
5149            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5150            List<PreferredActivity> prefs = pir != null
5151                    ? pir.queryIntent(intent, resolvedType,
5152                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5153                    : null;
5154            if (prefs != null && prefs.size() > 0) {
5155                boolean changed = false;
5156                try {
5157                    // First figure out how good the original match set is.
5158                    // We will only allow preferred activities that came
5159                    // from the same match quality.
5160                    int match = 0;
5161
5162                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5163
5164                    final int N = query.size();
5165                    for (int j=0; j<N; j++) {
5166                        final ResolveInfo ri = query.get(j);
5167                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5168                                + ": 0x" + Integer.toHexString(match));
5169                        if (ri.match > match) {
5170                            match = ri.match;
5171                        }
5172                    }
5173
5174                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5175                            + Integer.toHexString(match));
5176
5177                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5178                    final int M = prefs.size();
5179                    for (int i=0; i<M; i++) {
5180                        final PreferredActivity pa = prefs.get(i);
5181                        if (DEBUG_PREFERRED || debug) {
5182                            Slog.v(TAG, "Checking PreferredActivity ds="
5183                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5184                                    + "\n  component=" + pa.mPref.mComponent);
5185                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5186                        }
5187                        if (pa.mPref.mMatch != match) {
5188                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5189                                    + Integer.toHexString(pa.mPref.mMatch));
5190                            continue;
5191                        }
5192                        // If it's not an "always" type preferred activity and that's what we're
5193                        // looking for, skip it.
5194                        if (always && !pa.mPref.mAlways) {
5195                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5196                            continue;
5197                        }
5198                        final ActivityInfo ai = getActivityInfo(
5199                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5200                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5201                                userId);
5202                        if (DEBUG_PREFERRED || debug) {
5203                            Slog.v(TAG, "Found preferred activity:");
5204                            if (ai != null) {
5205                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5206                            } else {
5207                                Slog.v(TAG, "  null");
5208                            }
5209                        }
5210                        if (ai == null) {
5211                            // This previously registered preferred activity
5212                            // component is no longer known.  Most likely an update
5213                            // to the app was installed and in the new version this
5214                            // component no longer exists.  Clean it up by removing
5215                            // it from the preferred activities list, and skip it.
5216                            Slog.w(TAG, "Removing dangling preferred activity: "
5217                                    + pa.mPref.mComponent);
5218                            pir.removeFilter(pa);
5219                            changed = true;
5220                            continue;
5221                        }
5222                        for (int j=0; j<N; j++) {
5223                            final ResolveInfo ri = query.get(j);
5224                            if (!ri.activityInfo.applicationInfo.packageName
5225                                    .equals(ai.applicationInfo.packageName)) {
5226                                continue;
5227                            }
5228                            if (!ri.activityInfo.name.equals(ai.name)) {
5229                                continue;
5230                            }
5231
5232                            if (removeMatches) {
5233                                pir.removeFilter(pa);
5234                                changed = true;
5235                                if (DEBUG_PREFERRED) {
5236                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5237                                }
5238                                break;
5239                            }
5240
5241                            // Okay we found a previously set preferred or last chosen app.
5242                            // If the result set is different from when this
5243                            // was created, we need to clear it and re-ask the
5244                            // user their preference, if we're looking for an "always" type entry.
5245                            if (always && !pa.mPref.sameSet(query)) {
5246                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5247                                        + intent + " type " + resolvedType);
5248                                if (DEBUG_PREFERRED) {
5249                                    Slog.v(TAG, "Removing preferred activity since set changed "
5250                                            + pa.mPref.mComponent);
5251                                }
5252                                pir.removeFilter(pa);
5253                                // Re-add the filter as a "last chosen" entry (!always)
5254                                PreferredActivity lastChosen = new PreferredActivity(
5255                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5256                                pir.addFilter(lastChosen);
5257                                changed = true;
5258                                return null;
5259                            }
5260
5261                            // Yay! Either the set matched or we're looking for the last chosen
5262                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5263                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5264                            return ri;
5265                        }
5266                    }
5267                } finally {
5268                    if (changed) {
5269                        if (DEBUG_PREFERRED) {
5270                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5271                        }
5272                        scheduleWritePackageRestrictionsLocked(userId);
5273                    }
5274                }
5275            }
5276        }
5277        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5278        return null;
5279    }
5280
5281    /*
5282     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5283     */
5284    @Override
5285    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5286            int targetUserId) {
5287        mContext.enforceCallingOrSelfPermission(
5288                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5289        List<CrossProfileIntentFilter> matches =
5290                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5291        if (matches != null) {
5292            int size = matches.size();
5293            for (int i = 0; i < size; i++) {
5294                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5295            }
5296        }
5297        if (hasWebURI(intent)) {
5298            // cross-profile app linking works only towards the parent.
5299            final UserInfo parent = getProfileParent(sourceUserId);
5300            synchronized(mPackages) {
5301                int flags = updateFlagsForResolve(0, parent.id, intent);
5302                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5303                        intent, resolvedType, flags, sourceUserId, parent.id);
5304                return xpDomainInfo != null;
5305            }
5306        }
5307        return false;
5308    }
5309
5310    private UserInfo getProfileParent(int userId) {
5311        final long identity = Binder.clearCallingIdentity();
5312        try {
5313            return sUserManager.getProfileParent(userId);
5314        } finally {
5315            Binder.restoreCallingIdentity(identity);
5316        }
5317    }
5318
5319    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5320            String resolvedType, int userId) {
5321        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5322        if (resolver != null) {
5323            return resolver.queryIntent(intent, resolvedType, false, userId);
5324        }
5325        return null;
5326    }
5327
5328    @Override
5329    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5330            String resolvedType, int flags, int userId) {
5331        try {
5332            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5333
5334            return new ParceledListSlice<>(
5335                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5336        } finally {
5337            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5338        }
5339    }
5340
5341    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5342            String resolvedType, int flags, int userId) {
5343        if (!sUserManager.exists(userId)) return Collections.emptyList();
5344        flags = updateFlagsForResolve(flags, userId, intent);
5345        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5346                false /* requireFullPermission */, false /* checkShell */,
5347                "query intent activities");
5348        ComponentName comp = intent.getComponent();
5349        if (comp == null) {
5350            if (intent.getSelector() != null) {
5351                intent = intent.getSelector();
5352                comp = intent.getComponent();
5353            }
5354        }
5355
5356        if (comp != null) {
5357            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5358            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5359            if (ai != null) {
5360                final ResolveInfo ri = new ResolveInfo();
5361                ri.activityInfo = ai;
5362                list.add(ri);
5363            }
5364            return list;
5365        }
5366
5367        // reader
5368        boolean sortResult = false;
5369        boolean addEphemeral = false;
5370        boolean matchEphemeralPackage = false;
5371        List<ResolveInfo> result;
5372        final String pkgName = intent.getPackage();
5373        synchronized (mPackages) {
5374            if (pkgName == null) {
5375                List<CrossProfileIntentFilter> matchingFilters =
5376                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5377                // Check for results that need to skip the current profile.
5378                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5379                        resolvedType, flags, userId);
5380                if (xpResolveInfo != null) {
5381                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5382                    xpResult.add(xpResolveInfo);
5383                    return filterIfNotSystemUser(xpResult, userId);
5384                }
5385
5386                // Check for results in the current profile.
5387                result = filterIfNotSystemUser(mActivities.queryIntent(
5388                        intent, resolvedType, flags, userId), userId);
5389                addEphemeral =
5390                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5391
5392                // Check for cross profile results.
5393                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5394                xpResolveInfo = queryCrossProfileIntents(
5395                        matchingFilters, intent, resolvedType, flags, userId,
5396                        hasNonNegativePriorityResult);
5397                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5398                    boolean isVisibleToUser = filterIfNotSystemUser(
5399                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5400                    if (isVisibleToUser) {
5401                        result.add(xpResolveInfo);
5402                        sortResult = true;
5403                    }
5404                }
5405                if (hasWebURI(intent)) {
5406                    CrossProfileDomainInfo xpDomainInfo = null;
5407                    final UserInfo parent = getProfileParent(userId);
5408                    if (parent != null) {
5409                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5410                                flags, userId, parent.id);
5411                    }
5412                    if (xpDomainInfo != null) {
5413                        if (xpResolveInfo != null) {
5414                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5415                            // in the result.
5416                            result.remove(xpResolveInfo);
5417                        }
5418                        if (result.size() == 0 && !addEphemeral) {
5419                            result.add(xpDomainInfo.resolveInfo);
5420                            return result;
5421                        }
5422                    }
5423                    if (result.size() > 1 || addEphemeral) {
5424                        result = filterCandidatesWithDomainPreferredActivitiesLPr(
5425                                intent, flags, result, xpDomainInfo, userId);
5426                        sortResult = true;
5427                    }
5428                }
5429            } else {
5430                final PackageParser.Package pkg = mPackages.get(pkgName);
5431                if (pkg != null) {
5432                    result = filterIfNotSystemUser(
5433                            mActivities.queryIntentForPackage(
5434                                    intent, resolvedType, flags, pkg.activities, userId),
5435                            userId);
5436                } else {
5437                    // the caller wants to resolve for a particular package; however, there
5438                    // were no installed results, so, try to find an ephemeral result
5439                    addEphemeral = isEphemeralAllowed(
5440                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5441                    matchEphemeralPackage = true;
5442                    result = new ArrayList<ResolveInfo>();
5443                }
5444            }
5445        }
5446        if (addEphemeral) {
5447            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5448            final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5449                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5450                    matchEphemeralPackage ? pkgName : null);
5451            if (ai != null) {
5452                if (DEBUG_EPHEMERAL) {
5453                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5454                }
5455                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5456                ephemeralInstaller.ephemeralResolveInfo = ai;
5457                // make sure this resolver is the default
5458                ephemeralInstaller.isDefault = true;
5459                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5460                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5461                // add a non-generic filter
5462                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5463                ephemeralInstaller.filter.addDataPath(
5464                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5465                result.add(ephemeralInstaller);
5466            }
5467            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5468        }
5469        if (sortResult) {
5470            Collections.sort(result, mResolvePrioritySorter);
5471        }
5472        return result;
5473    }
5474
5475    private static class CrossProfileDomainInfo {
5476        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5477        ResolveInfo resolveInfo;
5478        /* Best domain verification status of the activities found in the other profile */
5479        int bestDomainVerificationStatus;
5480    }
5481
5482    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5483            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5484        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5485                sourceUserId)) {
5486            return null;
5487        }
5488        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5489                resolvedType, flags, parentUserId);
5490
5491        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5492            return null;
5493        }
5494        CrossProfileDomainInfo result = null;
5495        int size = resultTargetUser.size();
5496        for (int i = 0; i < size; i++) {
5497            ResolveInfo riTargetUser = resultTargetUser.get(i);
5498            // Intent filter verification is only for filters that specify a host. So don't return
5499            // those that handle all web uris.
5500            if (riTargetUser.handleAllWebDataURI) {
5501                continue;
5502            }
5503            String packageName = riTargetUser.activityInfo.packageName;
5504            PackageSetting ps = mSettings.mPackages.get(packageName);
5505            if (ps == null) {
5506                continue;
5507            }
5508            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5509            int status = (int)(verificationState >> 32);
5510            if (result == null) {
5511                result = new CrossProfileDomainInfo();
5512                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5513                        sourceUserId, parentUserId);
5514                result.bestDomainVerificationStatus = status;
5515            } else {
5516                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5517                        result.bestDomainVerificationStatus);
5518            }
5519        }
5520        // Don't consider matches with status NEVER across profiles.
5521        if (result != null && result.bestDomainVerificationStatus
5522                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5523            return null;
5524        }
5525        return result;
5526    }
5527
5528    /**
5529     * Verification statuses are ordered from the worse to the best, except for
5530     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5531     */
5532    private int bestDomainVerificationStatus(int status1, int status2) {
5533        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5534            return status2;
5535        }
5536        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5537            return status1;
5538        }
5539        return (int) MathUtils.max(status1, status2);
5540    }
5541
5542    private boolean isUserEnabled(int userId) {
5543        long callingId = Binder.clearCallingIdentity();
5544        try {
5545            UserInfo userInfo = sUserManager.getUserInfo(userId);
5546            return userInfo != null && userInfo.isEnabled();
5547        } finally {
5548            Binder.restoreCallingIdentity(callingId);
5549        }
5550    }
5551
5552    /**
5553     * Filter out activities with systemUserOnly flag set, when current user is not System.
5554     *
5555     * @return filtered list
5556     */
5557    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5558        if (userId == UserHandle.USER_SYSTEM) {
5559            return resolveInfos;
5560        }
5561        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5562            ResolveInfo info = resolveInfos.get(i);
5563            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5564                resolveInfos.remove(i);
5565            }
5566        }
5567        return resolveInfos;
5568    }
5569
5570    /**
5571     * @param resolveInfos list of resolve infos in descending priority order
5572     * @return if the list contains a resolve info with non-negative priority
5573     */
5574    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5575        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5576    }
5577
5578    private static boolean hasWebURI(Intent intent) {
5579        if (intent.getData() == null) {
5580            return false;
5581        }
5582        final String scheme = intent.getScheme();
5583        if (TextUtils.isEmpty(scheme)) {
5584            return false;
5585        }
5586        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5587    }
5588
5589    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5590            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5591            int userId) {
5592        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5593
5594        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5595            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5596                    candidates.size());
5597        }
5598
5599        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5600        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5601        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5602        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5603        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5604        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5605
5606        synchronized (mPackages) {
5607            final int count = candidates.size();
5608            // First, try to use linked apps. Partition the candidates into four lists:
5609            // one for the final results, one for the "do not use ever", one for "undefined status"
5610            // and finally one for "browser app type".
5611            for (int n=0; n<count; n++) {
5612                ResolveInfo info = candidates.get(n);
5613                String packageName = info.activityInfo.packageName;
5614                PackageSetting ps = mSettings.mPackages.get(packageName);
5615                if (ps != null) {
5616                    // Add to the special match all list (Browser use case)
5617                    if (info.handleAllWebDataURI) {
5618                        matchAllList.add(info);
5619                        continue;
5620                    }
5621                    // Try to get the status from User settings first
5622                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5623                    int status = (int)(packedStatus >> 32);
5624                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5625                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5626                        if (DEBUG_DOMAIN_VERIFICATION) {
5627                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5628                                    + " : linkgen=" + linkGeneration);
5629                        }
5630                        // Use link-enabled generation as preferredOrder, i.e.
5631                        // prefer newly-enabled over earlier-enabled.
5632                        info.preferredOrder = linkGeneration;
5633                        alwaysList.add(info);
5634                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5635                        if (DEBUG_DOMAIN_VERIFICATION) {
5636                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5637                        }
5638                        neverList.add(info);
5639                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5640                        if (DEBUG_DOMAIN_VERIFICATION) {
5641                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5642                        }
5643                        alwaysAskList.add(info);
5644                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5645                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5646                        if (DEBUG_DOMAIN_VERIFICATION) {
5647                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5648                        }
5649                        undefinedList.add(info);
5650                    }
5651                }
5652            }
5653
5654            // We'll want to include browser possibilities in a few cases
5655            boolean includeBrowser = false;
5656
5657            // First try to add the "always" resolution(s) for the current user, if any
5658            if (alwaysList.size() > 0) {
5659                result.addAll(alwaysList);
5660            } else {
5661                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5662                result.addAll(undefinedList);
5663                // Maybe add one for the other profile.
5664                if (xpDomainInfo != null && (
5665                        xpDomainInfo.bestDomainVerificationStatus
5666                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5667                    result.add(xpDomainInfo.resolveInfo);
5668                }
5669                includeBrowser = true;
5670            }
5671
5672            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5673            // If there were 'always' entries their preferred order has been set, so we also
5674            // back that off to make the alternatives equivalent
5675            if (alwaysAskList.size() > 0) {
5676                for (ResolveInfo i : result) {
5677                    i.preferredOrder = 0;
5678                }
5679                result.addAll(alwaysAskList);
5680                includeBrowser = true;
5681            }
5682
5683            if (includeBrowser) {
5684                // Also add browsers (all of them or only the default one)
5685                if (DEBUG_DOMAIN_VERIFICATION) {
5686                    Slog.v(TAG, "   ...including browsers in candidate set");
5687                }
5688                if ((matchFlags & MATCH_ALL) != 0) {
5689                    result.addAll(matchAllList);
5690                } else {
5691                    // Browser/generic handling case.  If there's a default browser, go straight
5692                    // to that (but only if there is no other higher-priority match).
5693                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5694                    int maxMatchPrio = 0;
5695                    ResolveInfo defaultBrowserMatch = null;
5696                    final int numCandidates = matchAllList.size();
5697                    for (int n = 0; n < numCandidates; n++) {
5698                        ResolveInfo info = matchAllList.get(n);
5699                        // track the highest overall match priority...
5700                        if (info.priority > maxMatchPrio) {
5701                            maxMatchPrio = info.priority;
5702                        }
5703                        // ...and the highest-priority default browser match
5704                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5705                            if (defaultBrowserMatch == null
5706                                    || (defaultBrowserMatch.priority < info.priority)) {
5707                                if (debug) {
5708                                    Slog.v(TAG, "Considering default browser match " + info);
5709                                }
5710                                defaultBrowserMatch = info;
5711                            }
5712                        }
5713                    }
5714                    if (defaultBrowserMatch != null
5715                            && defaultBrowserMatch.priority >= maxMatchPrio
5716                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5717                    {
5718                        if (debug) {
5719                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5720                        }
5721                        result.add(defaultBrowserMatch);
5722                    } else {
5723                        result.addAll(matchAllList);
5724                    }
5725                }
5726
5727                // If there is nothing selected, add all candidates and remove the ones that the user
5728                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5729                if (result.size() == 0) {
5730                    result.addAll(candidates);
5731                    result.removeAll(neverList);
5732                }
5733            }
5734        }
5735        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5736            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5737                    result.size());
5738            for (ResolveInfo info : result) {
5739                Slog.v(TAG, "  + " + info.activityInfo);
5740            }
5741        }
5742        return result;
5743    }
5744
5745    // Returns a packed value as a long:
5746    //
5747    // high 'int'-sized word: link status: undefined/ask/never/always.
5748    // low 'int'-sized word: relative priority among 'always' results.
5749    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5750        long result = ps.getDomainVerificationStatusForUser(userId);
5751        // if none available, get the master status
5752        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5753            if (ps.getIntentFilterVerificationInfo() != null) {
5754                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5755            }
5756        }
5757        return result;
5758    }
5759
5760    private ResolveInfo querySkipCurrentProfileIntents(
5761            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5762            int flags, int sourceUserId) {
5763        if (matchingFilters != null) {
5764            int size = matchingFilters.size();
5765            for (int i = 0; i < size; i ++) {
5766                CrossProfileIntentFilter filter = matchingFilters.get(i);
5767                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5768                    // Checking if there are activities in the target user that can handle the
5769                    // intent.
5770                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5771                            resolvedType, flags, sourceUserId);
5772                    if (resolveInfo != null) {
5773                        return resolveInfo;
5774                    }
5775                }
5776            }
5777        }
5778        return null;
5779    }
5780
5781    // Return matching ResolveInfo in target user if any.
5782    private ResolveInfo queryCrossProfileIntents(
5783            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5784            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5785        if (matchingFilters != null) {
5786            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5787            // match the same intent. For performance reasons, it is better not to
5788            // run queryIntent twice for the same userId
5789            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5790            int size = matchingFilters.size();
5791            for (int i = 0; i < size; i++) {
5792                CrossProfileIntentFilter filter = matchingFilters.get(i);
5793                int targetUserId = filter.getTargetUserId();
5794                boolean skipCurrentProfile =
5795                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5796                boolean skipCurrentProfileIfNoMatchFound =
5797                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5798                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5799                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5800                    // Checking if there are activities in the target user that can handle the
5801                    // intent.
5802                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5803                            resolvedType, flags, sourceUserId);
5804                    if (resolveInfo != null) return resolveInfo;
5805                    alreadyTriedUserIds.put(targetUserId, true);
5806                }
5807            }
5808        }
5809        return null;
5810    }
5811
5812    /**
5813     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5814     * will forward the intent to the filter's target user.
5815     * Otherwise, returns null.
5816     */
5817    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5818            String resolvedType, int flags, int sourceUserId) {
5819        int targetUserId = filter.getTargetUserId();
5820        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5821                resolvedType, flags, targetUserId);
5822        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5823            // If all the matches in the target profile are suspended, return null.
5824            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5825                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5826                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5827                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5828                            targetUserId);
5829                }
5830            }
5831        }
5832        return null;
5833    }
5834
5835    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5836            int sourceUserId, int targetUserId) {
5837        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5838        long ident = Binder.clearCallingIdentity();
5839        boolean targetIsProfile;
5840        try {
5841            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5842        } finally {
5843            Binder.restoreCallingIdentity(ident);
5844        }
5845        String className;
5846        if (targetIsProfile) {
5847            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5848        } else {
5849            className = FORWARD_INTENT_TO_PARENT;
5850        }
5851        ComponentName forwardingActivityComponentName = new ComponentName(
5852                mAndroidApplication.packageName, className);
5853        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5854                sourceUserId);
5855        if (!targetIsProfile) {
5856            forwardingActivityInfo.showUserIcon = targetUserId;
5857            forwardingResolveInfo.noResourceId = true;
5858        }
5859        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5860        forwardingResolveInfo.priority = 0;
5861        forwardingResolveInfo.preferredOrder = 0;
5862        forwardingResolveInfo.match = 0;
5863        forwardingResolveInfo.isDefault = true;
5864        forwardingResolveInfo.filter = filter;
5865        forwardingResolveInfo.targetUserId = targetUserId;
5866        return forwardingResolveInfo;
5867    }
5868
5869    @Override
5870    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5871            Intent[] specifics, String[] specificTypes, Intent intent,
5872            String resolvedType, int flags, int userId) {
5873        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5874                specificTypes, intent, resolvedType, flags, userId));
5875    }
5876
5877    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5878            Intent[] specifics, String[] specificTypes, Intent intent,
5879            String resolvedType, int flags, int userId) {
5880        if (!sUserManager.exists(userId)) return Collections.emptyList();
5881        flags = updateFlagsForResolve(flags, userId, intent);
5882        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5883                false /* requireFullPermission */, false /* checkShell */,
5884                "query intent activity options");
5885        final String resultsAction = intent.getAction();
5886
5887        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5888                | PackageManager.GET_RESOLVED_FILTER, userId);
5889
5890        if (DEBUG_INTENT_MATCHING) {
5891            Log.v(TAG, "Query " + intent + ": " + results);
5892        }
5893
5894        int specificsPos = 0;
5895        int N;
5896
5897        // todo: note that the algorithm used here is O(N^2).  This
5898        // isn't a problem in our current environment, but if we start running
5899        // into situations where we have more than 5 or 10 matches then this
5900        // should probably be changed to something smarter...
5901
5902        // First we go through and resolve each of the specific items
5903        // that were supplied, taking care of removing any corresponding
5904        // duplicate items in the generic resolve list.
5905        if (specifics != null) {
5906            for (int i=0; i<specifics.length; i++) {
5907                final Intent sintent = specifics[i];
5908                if (sintent == null) {
5909                    continue;
5910                }
5911
5912                if (DEBUG_INTENT_MATCHING) {
5913                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5914                }
5915
5916                String action = sintent.getAction();
5917                if (resultsAction != null && resultsAction.equals(action)) {
5918                    // If this action was explicitly requested, then don't
5919                    // remove things that have it.
5920                    action = null;
5921                }
5922
5923                ResolveInfo ri = null;
5924                ActivityInfo ai = null;
5925
5926                ComponentName comp = sintent.getComponent();
5927                if (comp == null) {
5928                    ri = resolveIntent(
5929                        sintent,
5930                        specificTypes != null ? specificTypes[i] : null,
5931                            flags, userId);
5932                    if (ri == null) {
5933                        continue;
5934                    }
5935                    if (ri == mResolveInfo) {
5936                        // ACK!  Must do something better with this.
5937                    }
5938                    ai = ri.activityInfo;
5939                    comp = new ComponentName(ai.applicationInfo.packageName,
5940                            ai.name);
5941                } else {
5942                    ai = getActivityInfo(comp, flags, userId);
5943                    if (ai == null) {
5944                        continue;
5945                    }
5946                }
5947
5948                // Look for any generic query activities that are duplicates
5949                // of this specific one, and remove them from the results.
5950                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5951                N = results.size();
5952                int j;
5953                for (j=specificsPos; j<N; j++) {
5954                    ResolveInfo sri = results.get(j);
5955                    if ((sri.activityInfo.name.equals(comp.getClassName())
5956                            && sri.activityInfo.applicationInfo.packageName.equals(
5957                                    comp.getPackageName()))
5958                        || (action != null && sri.filter.matchAction(action))) {
5959                        results.remove(j);
5960                        if (DEBUG_INTENT_MATCHING) Log.v(
5961                            TAG, "Removing duplicate item from " + j
5962                            + " due to specific " + specificsPos);
5963                        if (ri == null) {
5964                            ri = sri;
5965                        }
5966                        j--;
5967                        N--;
5968                    }
5969                }
5970
5971                // Add this specific item to its proper place.
5972                if (ri == null) {
5973                    ri = new ResolveInfo();
5974                    ri.activityInfo = ai;
5975                }
5976                results.add(specificsPos, ri);
5977                ri.specificIndex = i;
5978                specificsPos++;
5979            }
5980        }
5981
5982        // Now we go through the remaining generic results and remove any
5983        // duplicate actions that are found here.
5984        N = results.size();
5985        for (int i=specificsPos; i<N-1; i++) {
5986            final ResolveInfo rii = results.get(i);
5987            if (rii.filter == null) {
5988                continue;
5989            }
5990
5991            // Iterate over all of the actions of this result's intent
5992            // filter...  typically this should be just one.
5993            final Iterator<String> it = rii.filter.actionsIterator();
5994            if (it == null) {
5995                continue;
5996            }
5997            while (it.hasNext()) {
5998                final String action = it.next();
5999                if (resultsAction != null && resultsAction.equals(action)) {
6000                    // If this action was explicitly requested, then don't
6001                    // remove things that have it.
6002                    continue;
6003                }
6004                for (int j=i+1; j<N; j++) {
6005                    final ResolveInfo rij = results.get(j);
6006                    if (rij.filter != null && rij.filter.hasAction(action)) {
6007                        results.remove(j);
6008                        if (DEBUG_INTENT_MATCHING) Log.v(
6009                            TAG, "Removing duplicate item from " + j
6010                            + " due to action " + action + " at " + i);
6011                        j--;
6012                        N--;
6013                    }
6014                }
6015            }
6016
6017            // If the caller didn't request filter information, drop it now
6018            // so we don't have to marshall/unmarshall it.
6019            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6020                rii.filter = null;
6021            }
6022        }
6023
6024        // Filter out the caller activity if so requested.
6025        if (caller != null) {
6026            N = results.size();
6027            for (int i=0; i<N; i++) {
6028                ActivityInfo ainfo = results.get(i).activityInfo;
6029                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6030                        && caller.getClassName().equals(ainfo.name)) {
6031                    results.remove(i);
6032                    break;
6033                }
6034            }
6035        }
6036
6037        // If the caller didn't request filter information,
6038        // drop them now so we don't have to
6039        // marshall/unmarshall it.
6040        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6041            N = results.size();
6042            for (int i=0; i<N; i++) {
6043                results.get(i).filter = null;
6044            }
6045        }
6046
6047        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6048        return results;
6049    }
6050
6051    @Override
6052    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6053            String resolvedType, int flags, int userId) {
6054        return new ParceledListSlice<>(
6055                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6056    }
6057
6058    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6059            String resolvedType, int flags, int userId) {
6060        if (!sUserManager.exists(userId)) return Collections.emptyList();
6061        flags = updateFlagsForResolve(flags, userId, intent);
6062        ComponentName comp = intent.getComponent();
6063        if (comp == null) {
6064            if (intent.getSelector() != null) {
6065                intent = intent.getSelector();
6066                comp = intent.getComponent();
6067            }
6068        }
6069        if (comp != null) {
6070            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6071            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6072            if (ai != null) {
6073                ResolveInfo ri = new ResolveInfo();
6074                ri.activityInfo = ai;
6075                list.add(ri);
6076            }
6077            return list;
6078        }
6079
6080        // reader
6081        synchronized (mPackages) {
6082            String pkgName = intent.getPackage();
6083            if (pkgName == null) {
6084                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6085            }
6086            final PackageParser.Package pkg = mPackages.get(pkgName);
6087            if (pkg != null) {
6088                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6089                        userId);
6090            }
6091            return Collections.emptyList();
6092        }
6093    }
6094
6095    @Override
6096    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6097        if (!sUserManager.exists(userId)) return null;
6098        flags = updateFlagsForResolve(flags, userId, intent);
6099        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6100        if (query != null) {
6101            if (query.size() >= 1) {
6102                // If there is more than one service with the same priority,
6103                // just arbitrarily pick the first one.
6104                return query.get(0);
6105            }
6106        }
6107        return null;
6108    }
6109
6110    @Override
6111    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6112            String resolvedType, int flags, int userId) {
6113        return new ParceledListSlice<>(
6114                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6115    }
6116
6117    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6118            String resolvedType, int flags, int userId) {
6119        if (!sUserManager.exists(userId)) return Collections.emptyList();
6120        flags = updateFlagsForResolve(flags, userId, intent);
6121        ComponentName comp = intent.getComponent();
6122        if (comp == null) {
6123            if (intent.getSelector() != null) {
6124                intent = intent.getSelector();
6125                comp = intent.getComponent();
6126            }
6127        }
6128        if (comp != null) {
6129            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6130            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6131            if (si != null) {
6132                final ResolveInfo ri = new ResolveInfo();
6133                ri.serviceInfo = si;
6134                list.add(ri);
6135            }
6136            return list;
6137        }
6138
6139        // reader
6140        synchronized (mPackages) {
6141            String pkgName = intent.getPackage();
6142            if (pkgName == null) {
6143                return mServices.queryIntent(intent, resolvedType, flags, userId);
6144            }
6145            final PackageParser.Package pkg = mPackages.get(pkgName);
6146            if (pkg != null) {
6147                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6148                        userId);
6149            }
6150            return Collections.emptyList();
6151        }
6152    }
6153
6154    @Override
6155    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6156            String resolvedType, int flags, int userId) {
6157        return new ParceledListSlice<>(
6158                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6159    }
6160
6161    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6162            Intent intent, String resolvedType, int flags, int userId) {
6163        if (!sUserManager.exists(userId)) return Collections.emptyList();
6164        flags = updateFlagsForResolve(flags, userId, intent);
6165        ComponentName comp = intent.getComponent();
6166        if (comp == null) {
6167            if (intent.getSelector() != null) {
6168                intent = intent.getSelector();
6169                comp = intent.getComponent();
6170            }
6171        }
6172        if (comp != null) {
6173            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6174            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6175            if (pi != null) {
6176                final ResolveInfo ri = new ResolveInfo();
6177                ri.providerInfo = pi;
6178                list.add(ri);
6179            }
6180            return list;
6181        }
6182
6183        // reader
6184        synchronized (mPackages) {
6185            String pkgName = intent.getPackage();
6186            if (pkgName == null) {
6187                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6188            }
6189            final PackageParser.Package pkg = mPackages.get(pkgName);
6190            if (pkg != null) {
6191                return mProviders.queryIntentForPackage(
6192                        intent, resolvedType, flags, pkg.providers, userId);
6193            }
6194            return Collections.emptyList();
6195        }
6196    }
6197
6198    @Override
6199    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6200        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6201        flags = updateFlagsForPackage(flags, userId, null);
6202        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6203        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6204                true /* requireFullPermission */, false /* checkShell */,
6205                "get installed packages");
6206
6207        // writer
6208        synchronized (mPackages) {
6209            ArrayList<PackageInfo> list;
6210            if (listUninstalled) {
6211                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6212                for (PackageSetting ps : mSettings.mPackages.values()) {
6213                    final PackageInfo pi;
6214                    if (ps.pkg != null) {
6215                        pi = generatePackageInfo(ps, flags, userId);
6216                    } else {
6217                        pi = generatePackageInfo(ps, flags, userId);
6218                    }
6219                    if (pi != null) {
6220                        list.add(pi);
6221                    }
6222                }
6223            } else {
6224                list = new ArrayList<PackageInfo>(mPackages.size());
6225                for (PackageParser.Package p : mPackages.values()) {
6226                    final PackageInfo pi =
6227                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6228                    if (pi != null) {
6229                        list.add(pi);
6230                    }
6231                }
6232            }
6233
6234            return new ParceledListSlice<PackageInfo>(list);
6235        }
6236    }
6237
6238    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6239            String[] permissions, boolean[] tmp, int flags, int userId) {
6240        int numMatch = 0;
6241        final PermissionsState permissionsState = ps.getPermissionsState();
6242        for (int i=0; i<permissions.length; i++) {
6243            final String permission = permissions[i];
6244            if (permissionsState.hasPermission(permission, userId)) {
6245                tmp[i] = true;
6246                numMatch++;
6247            } else {
6248                tmp[i] = false;
6249            }
6250        }
6251        if (numMatch == 0) {
6252            return;
6253        }
6254        final PackageInfo pi;
6255        if (ps.pkg != null) {
6256            pi = generatePackageInfo(ps, flags, userId);
6257        } else {
6258            pi = generatePackageInfo(ps, flags, userId);
6259        }
6260        // The above might return null in cases of uninstalled apps or install-state
6261        // skew across users/profiles.
6262        if (pi != null) {
6263            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6264                if (numMatch == permissions.length) {
6265                    pi.requestedPermissions = permissions;
6266                } else {
6267                    pi.requestedPermissions = new String[numMatch];
6268                    numMatch = 0;
6269                    for (int i=0; i<permissions.length; i++) {
6270                        if (tmp[i]) {
6271                            pi.requestedPermissions[numMatch] = permissions[i];
6272                            numMatch++;
6273                        }
6274                    }
6275                }
6276            }
6277            list.add(pi);
6278        }
6279    }
6280
6281    @Override
6282    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6283            String[] permissions, int flags, int userId) {
6284        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6285        flags = updateFlagsForPackage(flags, userId, permissions);
6286        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6287
6288        // writer
6289        synchronized (mPackages) {
6290            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6291            boolean[] tmpBools = new boolean[permissions.length];
6292            if (listUninstalled) {
6293                for (PackageSetting ps : mSettings.mPackages.values()) {
6294                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6295                }
6296            } else {
6297                for (PackageParser.Package pkg : mPackages.values()) {
6298                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6299                    if (ps != null) {
6300                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6301                                userId);
6302                    }
6303                }
6304            }
6305
6306            return new ParceledListSlice<PackageInfo>(list);
6307        }
6308    }
6309
6310    @Override
6311    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6312        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6313        flags = updateFlagsForApplication(flags, userId, null);
6314        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6315
6316        // writer
6317        synchronized (mPackages) {
6318            ArrayList<ApplicationInfo> list;
6319            if (listUninstalled) {
6320                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6321                for (PackageSetting ps : mSettings.mPackages.values()) {
6322                    ApplicationInfo ai;
6323                    if (ps.pkg != null) {
6324                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6325                                ps.readUserState(userId), userId);
6326                    } else {
6327                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6328                    }
6329                    if (ai != null) {
6330                        list.add(ai);
6331                    }
6332                }
6333            } else {
6334                list = new ArrayList<ApplicationInfo>(mPackages.size());
6335                for (PackageParser.Package p : mPackages.values()) {
6336                    if (p.mExtras != null) {
6337                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6338                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6339                        if (ai != null) {
6340                            list.add(ai);
6341                        }
6342                    }
6343                }
6344            }
6345
6346            return new ParceledListSlice<ApplicationInfo>(list);
6347        }
6348    }
6349
6350    @Override
6351    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6352        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6353            return null;
6354        }
6355
6356        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6357                "getEphemeralApplications");
6358        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6359                true /* requireFullPermission */, false /* checkShell */,
6360                "getEphemeralApplications");
6361        synchronized (mPackages) {
6362            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6363                    .getEphemeralApplicationsLPw(userId);
6364            if (ephemeralApps != null) {
6365                return new ParceledListSlice<>(ephemeralApps);
6366            }
6367        }
6368        return null;
6369    }
6370
6371    @Override
6372    public boolean isEphemeralApplication(String packageName, int userId) {
6373        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6374                true /* requireFullPermission */, false /* checkShell */,
6375                "isEphemeral");
6376        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6377            return false;
6378        }
6379
6380        if (!isCallerSameApp(packageName)) {
6381            return false;
6382        }
6383        synchronized (mPackages) {
6384            PackageParser.Package pkg = mPackages.get(packageName);
6385            if (pkg != null) {
6386                return pkg.applicationInfo.isEphemeralApp();
6387            }
6388        }
6389        return false;
6390    }
6391
6392    @Override
6393    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6394        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6395            return null;
6396        }
6397
6398        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6399                true /* requireFullPermission */, false /* checkShell */,
6400                "getCookie");
6401        if (!isCallerSameApp(packageName)) {
6402            return null;
6403        }
6404        synchronized (mPackages) {
6405            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6406                    packageName, userId);
6407        }
6408    }
6409
6410    @Override
6411    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6412        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6413            return true;
6414        }
6415
6416        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6417                true /* requireFullPermission */, true /* checkShell */,
6418                "setCookie");
6419        if (!isCallerSameApp(packageName)) {
6420            return false;
6421        }
6422        synchronized (mPackages) {
6423            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6424                    packageName, cookie, userId);
6425        }
6426    }
6427
6428    @Override
6429    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6430        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6431            return null;
6432        }
6433
6434        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6435                "getEphemeralApplicationIcon");
6436        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6437                true /* requireFullPermission */, false /* checkShell */,
6438                "getEphemeralApplicationIcon");
6439        synchronized (mPackages) {
6440            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6441                    packageName, userId);
6442        }
6443    }
6444
6445    private boolean isCallerSameApp(String packageName) {
6446        PackageParser.Package pkg = mPackages.get(packageName);
6447        return pkg != null
6448                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6449    }
6450
6451    @Override
6452    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6453        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6454    }
6455
6456    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6457        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6458
6459        // reader
6460        synchronized (mPackages) {
6461            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6462            final int userId = UserHandle.getCallingUserId();
6463            while (i.hasNext()) {
6464                final PackageParser.Package p = i.next();
6465                if (p.applicationInfo == null) continue;
6466
6467                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6468                        && !p.applicationInfo.isDirectBootAware();
6469                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6470                        && p.applicationInfo.isDirectBootAware();
6471
6472                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6473                        && (!mSafeMode || isSystemApp(p))
6474                        && (matchesUnaware || matchesAware)) {
6475                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6476                    if (ps != null) {
6477                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6478                                ps.readUserState(userId), userId);
6479                        if (ai != null) {
6480                            finalList.add(ai);
6481                        }
6482                    }
6483                }
6484            }
6485        }
6486
6487        return finalList;
6488    }
6489
6490    @Override
6491    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6492        if (!sUserManager.exists(userId)) return null;
6493        flags = updateFlagsForComponent(flags, userId, name);
6494        // reader
6495        synchronized (mPackages) {
6496            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6497            PackageSetting ps = provider != null
6498                    ? mSettings.mPackages.get(provider.owner.packageName)
6499                    : null;
6500            return ps != null
6501                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6502                    ? PackageParser.generateProviderInfo(provider, flags,
6503                            ps.readUserState(userId), userId)
6504                    : null;
6505        }
6506    }
6507
6508    /**
6509     * @deprecated
6510     */
6511    @Deprecated
6512    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6513        // reader
6514        synchronized (mPackages) {
6515            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6516                    .entrySet().iterator();
6517            final int userId = UserHandle.getCallingUserId();
6518            while (i.hasNext()) {
6519                Map.Entry<String, PackageParser.Provider> entry = i.next();
6520                PackageParser.Provider p = entry.getValue();
6521                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6522
6523                if (ps != null && p.syncable
6524                        && (!mSafeMode || (p.info.applicationInfo.flags
6525                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6526                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6527                            ps.readUserState(userId), userId);
6528                    if (info != null) {
6529                        outNames.add(entry.getKey());
6530                        outInfo.add(info);
6531                    }
6532                }
6533            }
6534        }
6535    }
6536
6537    @Override
6538    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6539            int uid, int flags) {
6540        final int userId = processName != null ? UserHandle.getUserId(uid)
6541                : UserHandle.getCallingUserId();
6542        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6543        flags = updateFlagsForComponent(flags, userId, processName);
6544
6545        ArrayList<ProviderInfo> finalList = null;
6546        // reader
6547        synchronized (mPackages) {
6548            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6549            while (i.hasNext()) {
6550                final PackageParser.Provider p = i.next();
6551                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6552                if (ps != null && p.info.authority != null
6553                        && (processName == null
6554                                || (p.info.processName.equals(processName)
6555                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6556                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6557                    if (finalList == null) {
6558                        finalList = new ArrayList<ProviderInfo>(3);
6559                    }
6560                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6561                            ps.readUserState(userId), userId);
6562                    if (info != null) {
6563                        finalList.add(info);
6564                    }
6565                }
6566            }
6567        }
6568
6569        if (finalList != null) {
6570            Collections.sort(finalList, mProviderInitOrderSorter);
6571            return new ParceledListSlice<ProviderInfo>(finalList);
6572        }
6573
6574        return ParceledListSlice.emptyList();
6575    }
6576
6577    @Override
6578    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6579        // reader
6580        synchronized (mPackages) {
6581            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6582            return PackageParser.generateInstrumentationInfo(i, flags);
6583        }
6584    }
6585
6586    @Override
6587    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6588            String targetPackage, int flags) {
6589        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6590    }
6591
6592    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6593            int flags) {
6594        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6595
6596        // reader
6597        synchronized (mPackages) {
6598            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6599            while (i.hasNext()) {
6600                final PackageParser.Instrumentation p = i.next();
6601                if (targetPackage == null
6602                        || targetPackage.equals(p.info.targetPackage)) {
6603                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6604                            flags);
6605                    if (ii != null) {
6606                        finalList.add(ii);
6607                    }
6608                }
6609            }
6610        }
6611
6612        return finalList;
6613    }
6614
6615    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6616        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6617        if (overlays == null) {
6618            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6619            return;
6620        }
6621        for (PackageParser.Package opkg : overlays.values()) {
6622            // Not much to do if idmap fails: we already logged the error
6623            // and we certainly don't want to abort installation of pkg simply
6624            // because an overlay didn't fit properly. For these reasons,
6625            // ignore the return value of createIdmapForPackagePairLI.
6626            createIdmapForPackagePairLI(pkg, opkg);
6627        }
6628    }
6629
6630    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6631            PackageParser.Package opkg) {
6632        if (!opkg.mTrustedOverlay) {
6633            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6634                    opkg.baseCodePath + ": overlay not trusted");
6635            return false;
6636        }
6637        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6638        if (overlaySet == null) {
6639            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6640                    opkg.baseCodePath + " but target package has no known overlays");
6641            return false;
6642        }
6643        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6644        // TODO: generate idmap for split APKs
6645        try {
6646            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6647        } catch (InstallerException e) {
6648            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6649                    + opkg.baseCodePath);
6650            return false;
6651        }
6652        PackageParser.Package[] overlayArray =
6653            overlaySet.values().toArray(new PackageParser.Package[0]);
6654        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6655            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6656                return p1.mOverlayPriority - p2.mOverlayPriority;
6657            }
6658        };
6659        Arrays.sort(overlayArray, cmp);
6660
6661        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6662        int i = 0;
6663        for (PackageParser.Package p : overlayArray) {
6664            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6665        }
6666        return true;
6667    }
6668
6669    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6670        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6671        try {
6672            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6673        } finally {
6674            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6675        }
6676    }
6677
6678    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6679        final File[] files = dir.listFiles();
6680        if (ArrayUtils.isEmpty(files)) {
6681            Log.d(TAG, "No files in app dir " + dir);
6682            return;
6683        }
6684
6685        if (DEBUG_PACKAGE_SCANNING) {
6686            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6687                    + " flags=0x" + Integer.toHexString(parseFlags));
6688        }
6689
6690        for (File file : files) {
6691            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6692                    && !PackageInstallerService.isStageName(file.getName());
6693            if (!isPackage) {
6694                // Ignore entries which are not packages
6695                continue;
6696            }
6697            try {
6698                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6699                        scanFlags, currentTime, null);
6700            } catch (PackageManagerException e) {
6701                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6702
6703                // Delete invalid userdata apps
6704                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6705                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6706                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6707                    removeCodePathLI(file);
6708                }
6709            }
6710        }
6711    }
6712
6713    private static File getSettingsProblemFile() {
6714        File dataDir = Environment.getDataDirectory();
6715        File systemDir = new File(dataDir, "system");
6716        File fname = new File(systemDir, "uiderrors.txt");
6717        return fname;
6718    }
6719
6720    static void reportSettingsProblem(int priority, String msg) {
6721        logCriticalInfo(priority, msg);
6722    }
6723
6724    static void logCriticalInfo(int priority, String msg) {
6725        Slog.println(priority, TAG, msg);
6726        EventLogTags.writePmCriticalInfo(msg);
6727        try {
6728            File fname = getSettingsProblemFile();
6729            FileOutputStream out = new FileOutputStream(fname, true);
6730            PrintWriter pw = new FastPrintWriter(out);
6731            SimpleDateFormat formatter = new SimpleDateFormat();
6732            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6733            pw.println(dateString + ": " + msg);
6734            pw.close();
6735            FileUtils.setPermissions(
6736                    fname.toString(),
6737                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6738                    -1, -1);
6739        } catch (java.io.IOException e) {
6740        }
6741    }
6742
6743    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6744        if (srcFile.isDirectory()) {
6745            final File baseFile = new File(pkg.baseCodePath);
6746            long maxModifiedTime = baseFile.lastModified();
6747            if (pkg.splitCodePaths != null) {
6748                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6749                    final File splitFile = new File(pkg.splitCodePaths[i]);
6750                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6751                }
6752            }
6753            return maxModifiedTime;
6754        }
6755        return srcFile.lastModified();
6756    }
6757
6758    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6759            final int policyFlags) throws PackageManagerException {
6760        // When upgrading from pre-N MR1, verify the package time stamp using the package
6761        // directory and not the APK file.
6762        final long lastModifiedTime = mIsPreNMR1Upgrade
6763                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6764        if (ps != null
6765                && ps.codePath.equals(srcFile)
6766                && ps.timeStamp == lastModifiedTime
6767                && !isCompatSignatureUpdateNeeded(pkg)
6768                && !isRecoverSignatureUpdateNeeded(pkg)) {
6769            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6770            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6771            ArraySet<PublicKey> signingKs;
6772            synchronized (mPackages) {
6773                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6774            }
6775            if (ps.signatures.mSignatures != null
6776                    && ps.signatures.mSignatures.length != 0
6777                    && signingKs != null) {
6778                // Optimization: reuse the existing cached certificates
6779                // if the package appears to be unchanged.
6780                pkg.mSignatures = ps.signatures.mSignatures;
6781                pkg.mSigningKeys = signingKs;
6782                return;
6783            }
6784
6785            Slog.w(TAG, "PackageSetting for " + ps.name
6786                    + " is missing signatures.  Collecting certs again to recover them.");
6787        } else {
6788            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6789        }
6790
6791        try {
6792            PackageParser.collectCertificates(pkg, policyFlags);
6793        } catch (PackageParserException e) {
6794            throw PackageManagerException.from(e);
6795        }
6796    }
6797
6798    /**
6799     *  Traces a package scan.
6800     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6801     */
6802    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6803            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6804        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6805        try {
6806            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6807        } finally {
6808            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6809        }
6810    }
6811
6812    /**
6813     *  Scans a package and returns the newly parsed package.
6814     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6815     */
6816    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6817            long currentTime, UserHandle user) throws PackageManagerException {
6818        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6819        PackageParser pp = new PackageParser();
6820        pp.setSeparateProcesses(mSeparateProcesses);
6821        pp.setOnlyCoreApps(mOnlyCore);
6822        pp.setDisplayMetrics(mMetrics);
6823
6824        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6825            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6826        }
6827
6828        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6829        final PackageParser.Package pkg;
6830        try {
6831            pkg = pp.parsePackage(scanFile, parseFlags);
6832        } catch (PackageParserException e) {
6833            throw PackageManagerException.from(e);
6834        } finally {
6835            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6836        }
6837
6838        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6839    }
6840
6841    /**
6842     *  Scans a package and returns the newly parsed package.
6843     *  @throws PackageManagerException on a parse error.
6844     */
6845    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6846            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6847            throws PackageManagerException {
6848        // If the package has children and this is the first dive in the function
6849        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6850        // packages (parent and children) would be successfully scanned before the
6851        // actual scan since scanning mutates internal state and we want to atomically
6852        // install the package and its children.
6853        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6854            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6855                scanFlags |= SCAN_CHECK_ONLY;
6856            }
6857        } else {
6858            scanFlags &= ~SCAN_CHECK_ONLY;
6859        }
6860
6861        // Scan the parent
6862        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6863                scanFlags, currentTime, user);
6864
6865        // Scan the children
6866        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6867        for (int i = 0; i < childCount; i++) {
6868            PackageParser.Package childPackage = pkg.childPackages.get(i);
6869            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6870                    currentTime, user);
6871        }
6872
6873
6874        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6875            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6876        }
6877
6878        return scannedPkg;
6879    }
6880
6881    /**
6882     *  Scans a package and returns the newly parsed package.
6883     *  @throws PackageManagerException on a parse error.
6884     */
6885    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6886            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6887            throws PackageManagerException {
6888        PackageSetting ps = null;
6889        PackageSetting updatedPkg;
6890        // reader
6891        synchronized (mPackages) {
6892            // Look to see if we already know about this package.
6893            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6894            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6895                // This package has been renamed to its original name.  Let's
6896                // use that.
6897                ps = mSettings.peekPackageLPr(oldName);
6898            }
6899            // If there was no original package, see one for the real package name.
6900            if (ps == null) {
6901                ps = mSettings.peekPackageLPr(pkg.packageName);
6902            }
6903            // Check to see if this package could be hiding/updating a system
6904            // package.  Must look for it either under the original or real
6905            // package name depending on our state.
6906            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6907            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6908
6909            // If this is a package we don't know about on the system partition, we
6910            // may need to remove disabled child packages on the system partition
6911            // or may need to not add child packages if the parent apk is updated
6912            // on the data partition and no longer defines this child package.
6913            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6914                // If this is a parent package for an updated system app and this system
6915                // app got an OTA update which no longer defines some of the child packages
6916                // we have to prune them from the disabled system packages.
6917                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6918                if (disabledPs != null) {
6919                    final int scannedChildCount = (pkg.childPackages != null)
6920                            ? pkg.childPackages.size() : 0;
6921                    final int disabledChildCount = disabledPs.childPackageNames != null
6922                            ? disabledPs.childPackageNames.size() : 0;
6923                    for (int i = 0; i < disabledChildCount; i++) {
6924                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6925                        boolean disabledPackageAvailable = false;
6926                        for (int j = 0; j < scannedChildCount; j++) {
6927                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6928                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6929                                disabledPackageAvailable = true;
6930                                break;
6931                            }
6932                         }
6933                         if (!disabledPackageAvailable) {
6934                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6935                         }
6936                    }
6937                }
6938            }
6939        }
6940
6941        boolean updatedPkgBetter = false;
6942        // First check if this is a system package that may involve an update
6943        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6944            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6945            // it needs to drop FLAG_PRIVILEGED.
6946            if (locationIsPrivileged(scanFile)) {
6947                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6948            } else {
6949                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6950            }
6951
6952            if (ps != null && !ps.codePath.equals(scanFile)) {
6953                // The path has changed from what was last scanned...  check the
6954                // version of the new path against what we have stored to determine
6955                // what to do.
6956                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6957                if (pkg.mVersionCode <= ps.versionCode) {
6958                    // The system package has been updated and the code path does not match
6959                    // Ignore entry. Skip it.
6960                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6961                            + " ignored: updated version " + ps.versionCode
6962                            + " better than this " + pkg.mVersionCode);
6963                    if (!updatedPkg.codePath.equals(scanFile)) {
6964                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6965                                + ps.name + " changing from " + updatedPkg.codePathString
6966                                + " to " + scanFile);
6967                        updatedPkg.codePath = scanFile;
6968                        updatedPkg.codePathString = scanFile.toString();
6969                        updatedPkg.resourcePath = scanFile;
6970                        updatedPkg.resourcePathString = scanFile.toString();
6971                    }
6972                    updatedPkg.pkg = pkg;
6973                    updatedPkg.versionCode = pkg.mVersionCode;
6974
6975                    // Update the disabled system child packages to point to the package too.
6976                    final int childCount = updatedPkg.childPackageNames != null
6977                            ? updatedPkg.childPackageNames.size() : 0;
6978                    for (int i = 0; i < childCount; i++) {
6979                        String childPackageName = updatedPkg.childPackageNames.get(i);
6980                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6981                                childPackageName);
6982                        if (updatedChildPkg != null) {
6983                            updatedChildPkg.pkg = pkg;
6984                            updatedChildPkg.versionCode = pkg.mVersionCode;
6985                        }
6986                    }
6987
6988                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6989                            + scanFile + " ignored: updated version " + ps.versionCode
6990                            + " better than this " + pkg.mVersionCode);
6991                } else {
6992                    // The current app on the system partition is better than
6993                    // what we have updated to on the data partition; switch
6994                    // back to the system partition version.
6995                    // At this point, its safely assumed that package installation for
6996                    // apps in system partition will go through. If not there won't be a working
6997                    // version of the app
6998                    // writer
6999                    synchronized (mPackages) {
7000                        // Just remove the loaded entries from package lists.
7001                        mPackages.remove(ps.name);
7002                    }
7003
7004                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7005                            + " reverting from " + ps.codePathString
7006                            + ": new version " + pkg.mVersionCode
7007                            + " better than installed " + ps.versionCode);
7008
7009                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7010                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7011                    synchronized (mInstallLock) {
7012                        args.cleanUpResourcesLI();
7013                    }
7014                    synchronized (mPackages) {
7015                        mSettings.enableSystemPackageLPw(ps.name);
7016                    }
7017                    updatedPkgBetter = true;
7018                }
7019            }
7020        }
7021
7022        if (updatedPkg != null) {
7023            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7024            // initially
7025            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7026
7027            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7028            // flag set initially
7029            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7030                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7031            }
7032        }
7033
7034        // Verify certificates against what was last scanned
7035        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7036
7037        /*
7038         * A new system app appeared, but we already had a non-system one of the
7039         * same name installed earlier.
7040         */
7041        boolean shouldHideSystemApp = false;
7042        if (updatedPkg == null && ps != null
7043                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7044            /*
7045             * Check to make sure the signatures match first. If they don't,
7046             * wipe the installed application and its data.
7047             */
7048            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7049                    != PackageManager.SIGNATURE_MATCH) {
7050                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7051                        + " signatures don't match existing userdata copy; removing");
7052                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7053                        "scanPackageInternalLI")) {
7054                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7055                }
7056                ps = null;
7057            } else {
7058                /*
7059                 * If the newly-added system app is an older version than the
7060                 * already installed version, hide it. It will be scanned later
7061                 * and re-added like an update.
7062                 */
7063                if (pkg.mVersionCode <= ps.versionCode) {
7064                    shouldHideSystemApp = true;
7065                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7066                            + " but new version " + pkg.mVersionCode + " better than installed "
7067                            + ps.versionCode + "; hiding system");
7068                } else {
7069                    /*
7070                     * The newly found system app is a newer version that the
7071                     * one previously installed. Simply remove the
7072                     * already-installed application and replace it with our own
7073                     * while keeping the application data.
7074                     */
7075                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7076                            + " reverting from " + ps.codePathString + ": new version "
7077                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7078                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7079                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7080                    synchronized (mInstallLock) {
7081                        args.cleanUpResourcesLI();
7082                    }
7083                }
7084            }
7085        }
7086
7087        // The apk is forward locked (not public) if its code and resources
7088        // are kept in different files. (except for app in either system or
7089        // vendor path).
7090        // TODO grab this value from PackageSettings
7091        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7092            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7093                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7094            }
7095        }
7096
7097        // TODO: extend to support forward-locked splits
7098        String resourcePath = null;
7099        String baseResourcePath = null;
7100        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7101            if (ps != null && ps.resourcePathString != null) {
7102                resourcePath = ps.resourcePathString;
7103                baseResourcePath = ps.resourcePathString;
7104            } else {
7105                // Should not happen at all. Just log an error.
7106                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7107            }
7108        } else {
7109            resourcePath = pkg.codePath;
7110            baseResourcePath = pkg.baseCodePath;
7111        }
7112
7113        // Set application objects path explicitly.
7114        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7115        pkg.setApplicationInfoCodePath(pkg.codePath);
7116        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7117        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7118        pkg.setApplicationInfoResourcePath(resourcePath);
7119        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7120        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7121
7122        // Note that we invoke the following method only if we are about to unpack an application
7123        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7124                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7125
7126        /*
7127         * If the system app should be overridden by a previously installed
7128         * data, hide the system app now and let the /data/app scan pick it up
7129         * again.
7130         */
7131        if (shouldHideSystemApp) {
7132            synchronized (mPackages) {
7133                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7134            }
7135        }
7136
7137        return scannedPkg;
7138    }
7139
7140    private static String fixProcessName(String defProcessName,
7141            String processName, int uid) {
7142        if (processName == null) {
7143            return defProcessName;
7144        }
7145        return processName;
7146    }
7147
7148    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7149            throws PackageManagerException {
7150        if (pkgSetting.signatures.mSignatures != null) {
7151            // Already existing package. Make sure signatures match
7152            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7153                    == PackageManager.SIGNATURE_MATCH;
7154            if (!match) {
7155                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7156                        == PackageManager.SIGNATURE_MATCH;
7157            }
7158            if (!match) {
7159                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7160                        == PackageManager.SIGNATURE_MATCH;
7161            }
7162            if (!match) {
7163                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7164                        + pkg.packageName + " signatures do not match the "
7165                        + "previously installed version; ignoring!");
7166            }
7167        }
7168
7169        // Check for shared user signatures
7170        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7171            // Already existing package. Make sure signatures match
7172            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7173                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7174            if (!match) {
7175                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7176                        == PackageManager.SIGNATURE_MATCH;
7177            }
7178            if (!match) {
7179                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7180                        == PackageManager.SIGNATURE_MATCH;
7181            }
7182            if (!match) {
7183                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7184                        "Package " + pkg.packageName
7185                        + " has no signatures that match those in shared user "
7186                        + pkgSetting.sharedUser.name + "; ignoring!");
7187            }
7188        }
7189    }
7190
7191    /**
7192     * Enforces that only the system UID or root's UID can call a method exposed
7193     * via Binder.
7194     *
7195     * @param message used as message if SecurityException is thrown
7196     * @throws SecurityException if the caller is not system or root
7197     */
7198    private static final void enforceSystemOrRoot(String message) {
7199        final int uid = Binder.getCallingUid();
7200        if (uid != Process.SYSTEM_UID && uid != 0) {
7201            throw new SecurityException(message);
7202        }
7203    }
7204
7205    @Override
7206    public void performFstrimIfNeeded() {
7207        enforceSystemOrRoot("Only the system can request fstrim");
7208
7209        // Before everything else, see whether we need to fstrim.
7210        try {
7211            IMountService ms = PackageHelper.getMountService();
7212            if (ms != null) {
7213                boolean doTrim = false;
7214                final long interval = android.provider.Settings.Global.getLong(
7215                        mContext.getContentResolver(),
7216                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7217                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7218                if (interval > 0) {
7219                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7220                    if (timeSinceLast > interval) {
7221                        doTrim = true;
7222                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7223                                + "; running immediately");
7224                    }
7225                }
7226                if (doTrim) {
7227                    final boolean dexOptDialogShown;
7228                    synchronized (mPackages) {
7229                        dexOptDialogShown = mDexOptDialogShown;
7230                    }
7231                    if (!isFirstBoot() && dexOptDialogShown) {
7232                        try {
7233                            ActivityManagerNative.getDefault().showBootMessage(
7234                                    mContext.getResources().getString(
7235                                            R.string.android_upgrading_fstrim), true);
7236                        } catch (RemoteException e) {
7237                        }
7238                    }
7239                    ms.runMaintenance();
7240                }
7241            } else {
7242                Slog.e(TAG, "Mount service unavailable!");
7243            }
7244        } catch (RemoteException e) {
7245            // Can't happen; MountService is local
7246        }
7247    }
7248
7249    @Override
7250    public void updatePackagesIfNeeded() {
7251        enforceSystemOrRoot("Only the system can request package update");
7252
7253        // We need to re-extract after an OTA.
7254        boolean causeUpgrade = isUpgrade();
7255
7256        // First boot or factory reset.
7257        // Note: we also handle devices that are upgrading to N right now as if it is their
7258        //       first boot, as they do not have profile data.
7259        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7260
7261        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7262        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7263
7264        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7265            return;
7266        }
7267
7268        List<PackageParser.Package> pkgs;
7269        synchronized (mPackages) {
7270            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7271        }
7272
7273        final long startTime = System.nanoTime();
7274        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7275                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7276
7277        final int elapsedTimeSeconds =
7278                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7279
7280        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7281        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7282        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7283        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7284        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7285    }
7286
7287    /**
7288     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7289     * containing statistics about the invocation. The array consists of three elements,
7290     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7291     * and {@code numberOfPackagesFailed}.
7292     */
7293    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7294            String compilerFilter) {
7295
7296        int numberOfPackagesVisited = 0;
7297        int numberOfPackagesOptimized = 0;
7298        int numberOfPackagesSkipped = 0;
7299        int numberOfPackagesFailed = 0;
7300        final int numberOfPackagesToDexopt = pkgs.size();
7301
7302        for (PackageParser.Package pkg : pkgs) {
7303            numberOfPackagesVisited++;
7304
7305            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7306                if (DEBUG_DEXOPT) {
7307                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7308                }
7309                numberOfPackagesSkipped++;
7310                continue;
7311            }
7312
7313            if (DEBUG_DEXOPT) {
7314                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7315                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7316            }
7317
7318            if (showDialog) {
7319                try {
7320                    ActivityManagerNative.getDefault().showBootMessage(
7321                            mContext.getResources().getString(R.string.android_upgrading_apk,
7322                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7323                } catch (RemoteException e) {
7324                }
7325                synchronized (mPackages) {
7326                    mDexOptDialogShown = true;
7327                }
7328            }
7329
7330            // If the OTA updates a system app which was previously preopted to a non-preopted state
7331            // the app might end up being verified at runtime. That's because by default the apps
7332            // are verify-profile but for preopted apps there's no profile.
7333            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7334            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7335            // filter (by default interpret-only).
7336            // Note that at this stage unused apps are already filtered.
7337            if (isSystemApp(pkg) &&
7338                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7339                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7340                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7341            }
7342
7343            // If the OTA updates a system app which was previously preopted to a non-preopted state
7344            // the app might end up being verified at runtime. That's because by default the apps
7345            // are verify-profile but for preopted apps there's no profile.
7346            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7347            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7348            // filter (by default interpret-only).
7349            // Note that at this stage unused apps are already filtered.
7350            if (isSystemApp(pkg) &&
7351                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7352                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7353                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7354            }
7355
7356            // checkProfiles is false to avoid merging profiles during boot which
7357            // might interfere with background compilation (b/28612421).
7358            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7359            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7360            // trade-off worth doing to save boot time work.
7361            int dexOptStatus = performDexOptTraced(pkg.packageName,
7362                    false /* checkProfiles */,
7363                    compilerFilter,
7364                    false /* force */);
7365            switch (dexOptStatus) {
7366                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7367                    numberOfPackagesOptimized++;
7368                    break;
7369                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7370                    numberOfPackagesSkipped++;
7371                    break;
7372                case PackageDexOptimizer.DEX_OPT_FAILED:
7373                    numberOfPackagesFailed++;
7374                    break;
7375                default:
7376                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7377                    break;
7378            }
7379        }
7380
7381        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7382                numberOfPackagesFailed };
7383    }
7384
7385    @Override
7386    public void notifyPackageUse(String packageName, int reason) {
7387        synchronized (mPackages) {
7388            PackageParser.Package p = mPackages.get(packageName);
7389            if (p == null) {
7390                return;
7391            }
7392            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7393        }
7394    }
7395
7396    @Override
7397    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
7398        int userId = UserHandle.getCallingUserId();
7399        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
7400        if (ai == null) {
7401            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
7402                + loadingPackageName + ", user=" + userId);
7403            return;
7404        }
7405        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
7406    }
7407
7408    // TODO: this is not used nor needed. Delete it.
7409    @Override
7410    public boolean performDexOptIfNeeded(String packageName) {
7411        int dexOptStatus = performDexOptTraced(packageName,
7412                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7413        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7414    }
7415
7416    @Override
7417    public boolean performDexOpt(String packageName,
7418            boolean checkProfiles, int compileReason, boolean force) {
7419        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7420                getCompilerFilterForReason(compileReason), force);
7421        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7422    }
7423
7424    @Override
7425    public boolean performDexOptMode(String packageName,
7426            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7427        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7428                targetCompilerFilter, force);
7429        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7430    }
7431
7432    private int performDexOptTraced(String packageName,
7433                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7434        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7435        try {
7436            return performDexOptInternal(packageName, checkProfiles,
7437                    targetCompilerFilter, force);
7438        } finally {
7439            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7440        }
7441    }
7442
7443    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7444    // if the package can now be considered up to date for the given filter.
7445    private int performDexOptInternal(String packageName,
7446                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7447        PackageParser.Package p;
7448        synchronized (mPackages) {
7449            p = mPackages.get(packageName);
7450            if (p == null) {
7451                // Package could not be found. Report failure.
7452                return PackageDexOptimizer.DEX_OPT_FAILED;
7453            }
7454            mPackageUsage.maybeWriteAsync(mPackages);
7455            mCompilerStats.maybeWriteAsync();
7456        }
7457        long callingId = Binder.clearCallingIdentity();
7458        try {
7459            synchronized (mInstallLock) {
7460                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7461                        targetCompilerFilter, force);
7462            }
7463        } finally {
7464            Binder.restoreCallingIdentity(callingId);
7465        }
7466    }
7467
7468    public ArraySet<String> getOptimizablePackages() {
7469        ArraySet<String> pkgs = new ArraySet<String>();
7470        synchronized (mPackages) {
7471            for (PackageParser.Package p : mPackages.values()) {
7472                if (PackageDexOptimizer.canOptimizePackage(p)) {
7473                    pkgs.add(p.packageName);
7474                }
7475            }
7476        }
7477        return pkgs;
7478    }
7479
7480    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7481            boolean checkProfiles, String targetCompilerFilter,
7482            boolean force) {
7483        // Select the dex optimizer based on the force parameter.
7484        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7485        //       allocate an object here.
7486        PackageDexOptimizer pdo = force
7487                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7488                : mPackageDexOptimizer;
7489
7490        // Optimize all dependencies first. Note: we ignore the return value and march on
7491        // on errors.
7492        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7493        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7494        if (!deps.isEmpty()) {
7495            for (PackageParser.Package depPackage : deps) {
7496                // TODO: Analyze and investigate if we (should) profile libraries.
7497                // Currently this will do a full compilation of the library by default.
7498                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7499                        false /* checkProfiles */,
7500                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7501                        getOrCreateCompilerPackageStats(depPackage),
7502                        mDexManager.isUsedByOtherApps(p.packageName));
7503            }
7504        }
7505        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7506                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
7507                mDexManager.isUsedByOtherApps(p.packageName));
7508    }
7509
7510    // Performs dexopt on the used secondary dex files belonging to the given package.
7511    // Returns true if all dex files were process successfully (which could mean either dexopt or
7512    // skip). Returns false if any of the files caused errors.
7513    @Override
7514    public boolean performDexOptSecondary(String packageName, String compilerFilter,
7515            boolean force) {
7516        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
7517    }
7518
7519    /**
7520     * Reconcile the information we have about the secondary dex files belonging to
7521     * {@code packagName} and the actual dex files. For all dex files that were
7522     * deleted, update the internal records and delete the generated oat files.
7523     */
7524    @Override
7525    public void reconcileSecondaryDexFiles(String packageName) {
7526        mDexManager.reconcileSecondaryDexFiles(packageName);
7527    }
7528
7529    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
7530    // a reference there.
7531    /*package*/ DexManager getDexManager() {
7532        return mDexManager;
7533    }
7534
7535    /**
7536     * Execute the background dexopt job immediately.
7537     */
7538    @Override
7539    public boolean runBackgroundDexoptJob() {
7540        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
7541    }
7542
7543    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7544        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7545            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7546            Set<String> collectedNames = new HashSet<>();
7547            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7548
7549            retValue.remove(p);
7550
7551            return retValue;
7552        } else {
7553            return Collections.emptyList();
7554        }
7555    }
7556
7557    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7558            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7559        if (!collectedNames.contains(p.packageName)) {
7560            collectedNames.add(p.packageName);
7561            collected.add(p);
7562
7563            if (p.usesLibraries != null) {
7564                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7565            }
7566            if (p.usesOptionalLibraries != null) {
7567                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7568                        collectedNames);
7569            }
7570        }
7571    }
7572
7573    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7574            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7575        for (String libName : libs) {
7576            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7577            if (libPkg != null) {
7578                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7579            }
7580        }
7581    }
7582
7583    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7584        synchronized (mPackages) {
7585            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7586            if (lib != null && lib.apk != null) {
7587                return mPackages.get(lib.apk);
7588            }
7589        }
7590        return null;
7591    }
7592
7593    public void shutdown() {
7594        mPackageUsage.writeNow(mPackages);
7595        mCompilerStats.writeNow();
7596    }
7597
7598    @Override
7599    public void dumpProfiles(String packageName) {
7600        PackageParser.Package pkg;
7601        synchronized (mPackages) {
7602            pkg = mPackages.get(packageName);
7603            if (pkg == null) {
7604                throw new IllegalArgumentException("Unknown package: " + packageName);
7605            }
7606        }
7607        /* Only the shell, root, or the app user should be able to dump profiles. */
7608        int callingUid = Binder.getCallingUid();
7609        if (callingUid != Process.SHELL_UID &&
7610            callingUid != Process.ROOT_UID &&
7611            callingUid != pkg.applicationInfo.uid) {
7612            throw new SecurityException("dumpProfiles");
7613        }
7614
7615        synchronized (mInstallLock) {
7616            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7617            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7618            try {
7619                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7620                String codePaths = TextUtils.join(";", allCodePaths);
7621                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
7622            } catch (InstallerException e) {
7623                Slog.w(TAG, "Failed to dump profiles", e);
7624            }
7625            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7626        }
7627    }
7628
7629    @Override
7630    public void forceDexOpt(String packageName) {
7631        enforceSystemOrRoot("forceDexOpt");
7632
7633        PackageParser.Package pkg;
7634        synchronized (mPackages) {
7635            pkg = mPackages.get(packageName);
7636            if (pkg == null) {
7637                throw new IllegalArgumentException("Unknown package: " + packageName);
7638            }
7639        }
7640
7641        synchronized (mInstallLock) {
7642            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7643
7644            // Whoever is calling forceDexOpt wants a fully compiled package.
7645            // Don't use profiles since that may cause compilation to be skipped.
7646            final int res = performDexOptInternalWithDependenciesLI(pkg,
7647                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7648                    true /* force */);
7649
7650            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7651            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7652                throw new IllegalStateException("Failed to dexopt: " + res);
7653            }
7654        }
7655    }
7656
7657    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7658        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7659            Slog.w(TAG, "Unable to update from " + oldPkg.name
7660                    + " to " + newPkg.packageName
7661                    + ": old package not in system partition");
7662            return false;
7663        } else if (mPackages.get(oldPkg.name) != null) {
7664            Slog.w(TAG, "Unable to update from " + oldPkg.name
7665                    + " to " + newPkg.packageName
7666                    + ": old package still exists");
7667            return false;
7668        }
7669        return true;
7670    }
7671
7672    void removeCodePathLI(File codePath) {
7673        if (codePath.isDirectory()) {
7674            try {
7675                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7676            } catch (InstallerException e) {
7677                Slog.w(TAG, "Failed to remove code path", e);
7678            }
7679        } else {
7680            codePath.delete();
7681        }
7682    }
7683
7684    private int[] resolveUserIds(int userId) {
7685        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7686    }
7687
7688    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7689        if (pkg == null) {
7690            Slog.wtf(TAG, "Package was null!", new Throwable());
7691            return;
7692        }
7693        clearAppDataLeafLIF(pkg, userId, flags);
7694        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7695        for (int i = 0; i < childCount; i++) {
7696            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7697        }
7698    }
7699
7700    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7701        final PackageSetting ps;
7702        synchronized (mPackages) {
7703            ps = mSettings.mPackages.get(pkg.packageName);
7704        }
7705        for (int realUserId : resolveUserIds(userId)) {
7706            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7707            try {
7708                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7709                        ceDataInode);
7710            } catch (InstallerException e) {
7711                Slog.w(TAG, String.valueOf(e));
7712            }
7713        }
7714    }
7715
7716    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7717        if (pkg == null) {
7718            Slog.wtf(TAG, "Package was null!", new Throwable());
7719            return;
7720        }
7721        destroyAppDataLeafLIF(pkg, userId, flags);
7722        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7723        for (int i = 0; i < childCount; i++) {
7724            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7725        }
7726    }
7727
7728    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7729        final PackageSetting ps;
7730        synchronized (mPackages) {
7731            ps = mSettings.mPackages.get(pkg.packageName);
7732        }
7733        for (int realUserId : resolveUserIds(userId)) {
7734            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7735            try {
7736                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7737                        ceDataInode);
7738            } catch (InstallerException e) {
7739                Slog.w(TAG, String.valueOf(e));
7740            }
7741        }
7742    }
7743
7744    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7745        if (pkg == null) {
7746            Slog.wtf(TAG, "Package was null!", new Throwable());
7747            return;
7748        }
7749        destroyAppProfilesLeafLIF(pkg);
7750        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7751        for (int i = 0; i < childCount; i++) {
7752            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7753        }
7754    }
7755
7756    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7757        try {
7758            mInstaller.destroyAppProfiles(pkg.packageName);
7759        } catch (InstallerException e) {
7760            Slog.w(TAG, String.valueOf(e));
7761        }
7762    }
7763
7764    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7765        if (pkg == null) {
7766            Slog.wtf(TAG, "Package was null!", new Throwable());
7767            return;
7768        }
7769        clearAppProfilesLeafLIF(pkg);
7770        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7771        for (int i = 0; i < childCount; i++) {
7772            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7773        }
7774    }
7775
7776    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7777        try {
7778            mInstaller.clearAppProfiles(pkg.packageName);
7779        } catch (InstallerException e) {
7780            Slog.w(TAG, String.valueOf(e));
7781        }
7782    }
7783
7784    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7785            long lastUpdateTime) {
7786        // Set parent install/update time
7787        PackageSetting ps = (PackageSetting) pkg.mExtras;
7788        if (ps != null) {
7789            ps.firstInstallTime = firstInstallTime;
7790            ps.lastUpdateTime = lastUpdateTime;
7791        }
7792        // Set children install/update time
7793        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7794        for (int i = 0; i < childCount; i++) {
7795            PackageParser.Package childPkg = pkg.childPackages.get(i);
7796            ps = (PackageSetting) childPkg.mExtras;
7797            if (ps != null) {
7798                ps.firstInstallTime = firstInstallTime;
7799                ps.lastUpdateTime = lastUpdateTime;
7800            }
7801        }
7802    }
7803
7804    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7805            PackageParser.Package changingLib) {
7806        if (file.path != null) {
7807            usesLibraryFiles.add(file.path);
7808            return;
7809        }
7810        PackageParser.Package p = mPackages.get(file.apk);
7811        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7812            // If we are doing this while in the middle of updating a library apk,
7813            // then we need to make sure to use that new apk for determining the
7814            // dependencies here.  (We haven't yet finished committing the new apk
7815            // to the package manager state.)
7816            if (p == null || p.packageName.equals(changingLib.packageName)) {
7817                p = changingLib;
7818            }
7819        }
7820        if (p != null) {
7821            usesLibraryFiles.addAll(p.getAllCodePaths());
7822        }
7823    }
7824
7825    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7826            PackageParser.Package changingLib) throws PackageManagerException {
7827        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7828            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7829            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7830            for (int i=0; i<N; i++) {
7831                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7832                if (file == null) {
7833                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7834                            "Package " + pkg.packageName + " requires unavailable shared library "
7835                            + pkg.usesLibraries.get(i) + "; failing!");
7836                }
7837                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7838            }
7839            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7840            for (int i=0; i<N; i++) {
7841                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7842                if (file == null) {
7843                    Slog.w(TAG, "Package " + pkg.packageName
7844                            + " desires unavailable shared library "
7845                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7846                } else {
7847                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7848                }
7849            }
7850            N = usesLibraryFiles.size();
7851            if (N > 0) {
7852                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7853            } else {
7854                pkg.usesLibraryFiles = null;
7855            }
7856        }
7857    }
7858
7859    private static boolean hasString(List<String> list, List<String> which) {
7860        if (list == null) {
7861            return false;
7862        }
7863        for (int i=list.size()-1; i>=0; i--) {
7864            for (int j=which.size()-1; j>=0; j--) {
7865                if (which.get(j).equals(list.get(i))) {
7866                    return true;
7867                }
7868            }
7869        }
7870        return false;
7871    }
7872
7873    private void updateAllSharedLibrariesLPw() {
7874        for (PackageParser.Package pkg : mPackages.values()) {
7875            try {
7876                updateSharedLibrariesLPw(pkg, null);
7877            } catch (PackageManagerException e) {
7878                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7879            }
7880        }
7881    }
7882
7883    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7884            PackageParser.Package changingPkg) {
7885        ArrayList<PackageParser.Package> res = null;
7886        for (PackageParser.Package pkg : mPackages.values()) {
7887            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7888                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7889                if (res == null) {
7890                    res = new ArrayList<PackageParser.Package>();
7891                }
7892                res.add(pkg);
7893                try {
7894                    updateSharedLibrariesLPw(pkg, changingPkg);
7895                } catch (PackageManagerException e) {
7896                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7897                }
7898            }
7899        }
7900        return res;
7901    }
7902
7903    /**
7904     * Derive the value of the {@code cpuAbiOverride} based on the provided
7905     * value and an optional stored value from the package settings.
7906     */
7907    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7908        String cpuAbiOverride = null;
7909
7910        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7911            cpuAbiOverride = null;
7912        } else if (abiOverride != null) {
7913            cpuAbiOverride = abiOverride;
7914        } else if (settings != null) {
7915            cpuAbiOverride = settings.cpuAbiOverrideString;
7916        }
7917
7918        return cpuAbiOverride;
7919    }
7920
7921    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7922            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7923                    throws PackageManagerException {
7924        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7925        // If the package has children and this is the first dive in the function
7926        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7927        // whether all packages (parent and children) would be successfully scanned
7928        // before the actual scan since scanning mutates internal state and we want
7929        // to atomically install the package and its children.
7930        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7931            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7932                scanFlags |= SCAN_CHECK_ONLY;
7933            }
7934        } else {
7935            scanFlags &= ~SCAN_CHECK_ONLY;
7936        }
7937
7938        final PackageParser.Package scannedPkg;
7939        try {
7940            // Scan the parent
7941            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7942            // Scan the children
7943            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7944            for (int i = 0; i < childCount; i++) {
7945                PackageParser.Package childPkg = pkg.childPackages.get(i);
7946                scanPackageLI(childPkg, policyFlags,
7947                        scanFlags, currentTime, user);
7948            }
7949        } finally {
7950            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7951        }
7952
7953        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7954            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7955        }
7956
7957        return scannedPkg;
7958    }
7959
7960    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7961            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7962        boolean success = false;
7963        try {
7964            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7965                    currentTime, user);
7966            success = true;
7967            return res;
7968        } finally {
7969            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7970                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7971                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7972                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7973                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7974            }
7975        }
7976    }
7977
7978    /**
7979     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7980     */
7981    private static boolean apkHasCode(String fileName) {
7982        StrictJarFile jarFile = null;
7983        try {
7984            jarFile = new StrictJarFile(fileName,
7985                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7986            return jarFile.findEntry("classes.dex") != null;
7987        } catch (IOException ignore) {
7988        } finally {
7989            try {
7990                if (jarFile != null) {
7991                    jarFile.close();
7992                }
7993            } catch (IOException ignore) {}
7994        }
7995        return false;
7996    }
7997
7998    /**
7999     * Enforces code policy for the package. This ensures that if an APK has
8000     * declared hasCode="true" in its manifest that the APK actually contains
8001     * code.
8002     *
8003     * @throws PackageManagerException If bytecode could not be found when it should exist
8004     */
8005    private static void enforceCodePolicy(PackageParser.Package pkg)
8006            throws PackageManagerException {
8007        final boolean shouldHaveCode =
8008                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8009        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8010            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8011                    "Package " + pkg.baseCodePath + " code is missing");
8012        }
8013
8014        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8015            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8016                final boolean splitShouldHaveCode =
8017                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8018                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8019                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8020                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8021                }
8022            }
8023        }
8024    }
8025
8026    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8027            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8028            throws PackageManagerException {
8029        final File scanFile = new File(pkg.codePath);
8030        if (pkg.applicationInfo.getCodePath() == null ||
8031                pkg.applicationInfo.getResourcePath() == null) {
8032            // Bail out. The resource and code paths haven't been set.
8033            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8034                    "Code and resource paths haven't been set correctly");
8035        }
8036
8037        // Apply policy
8038        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8039            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8040            if (pkg.applicationInfo.isDirectBootAware()) {
8041                // we're direct boot aware; set for all components
8042                for (PackageParser.Service s : pkg.services) {
8043                    s.info.encryptionAware = s.info.directBootAware = true;
8044                }
8045                for (PackageParser.Provider p : pkg.providers) {
8046                    p.info.encryptionAware = p.info.directBootAware = true;
8047                }
8048                for (PackageParser.Activity a : pkg.activities) {
8049                    a.info.encryptionAware = a.info.directBootAware = true;
8050                }
8051                for (PackageParser.Activity r : pkg.receivers) {
8052                    r.info.encryptionAware = r.info.directBootAware = true;
8053                }
8054            }
8055        } else {
8056            // Only allow system apps to be flagged as core apps.
8057            pkg.coreApp = false;
8058            // clear flags not applicable to regular apps
8059            pkg.applicationInfo.privateFlags &=
8060                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8061            pkg.applicationInfo.privateFlags &=
8062                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8063        }
8064        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8065
8066        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8067            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8068        }
8069
8070        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8071            enforceCodePolicy(pkg);
8072        }
8073
8074        if (mCustomResolverComponentName != null &&
8075                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8076            setUpCustomResolverActivity(pkg);
8077        }
8078
8079        if (pkg.packageName.equals("android")) {
8080            synchronized (mPackages) {
8081                if (mAndroidApplication != null) {
8082                    Slog.w(TAG, "*************************************************");
8083                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8084                    Slog.w(TAG, " file=" + scanFile);
8085                    Slog.w(TAG, "*************************************************");
8086                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8087                            "Core android package being redefined.  Skipping.");
8088                }
8089
8090                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8091                    // Set up information for our fall-back user intent resolution activity.
8092                    mPlatformPackage = pkg;
8093                    pkg.mVersionCode = mSdkVersion;
8094                    mAndroidApplication = pkg.applicationInfo;
8095
8096                    if (!mResolverReplaced) {
8097                        mResolveActivity.applicationInfo = mAndroidApplication;
8098                        mResolveActivity.name = ResolverActivity.class.getName();
8099                        mResolveActivity.packageName = mAndroidApplication.packageName;
8100                        mResolveActivity.processName = "system:ui";
8101                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8102                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8103                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8104                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8105                        mResolveActivity.exported = true;
8106                        mResolveActivity.enabled = true;
8107                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8108                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8109                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8110                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8111                                | ActivityInfo.CONFIG_ORIENTATION
8112                                | ActivityInfo.CONFIG_KEYBOARD
8113                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8114                        mResolveInfo.activityInfo = mResolveActivity;
8115                        mResolveInfo.priority = 0;
8116                        mResolveInfo.preferredOrder = 0;
8117                        mResolveInfo.match = 0;
8118                        mResolveComponentName = new ComponentName(
8119                                mAndroidApplication.packageName, mResolveActivity.name);
8120                    }
8121                }
8122            }
8123        }
8124
8125        if (DEBUG_PACKAGE_SCANNING) {
8126            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8127                Log.d(TAG, "Scanning package " + pkg.packageName);
8128        }
8129
8130        synchronized (mPackages) {
8131            if (mPackages.containsKey(pkg.packageName)
8132                    || mSharedLibraries.containsKey(pkg.packageName)) {
8133                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8134                        "Application package " + pkg.packageName
8135                                + " already installed.  Skipping duplicate.");
8136            }
8137
8138            // If we're only installing presumed-existing packages, require that the
8139            // scanned APK is both already known and at the path previously established
8140            // for it.  Previously unknown packages we pick up normally, but if we have an
8141            // a priori expectation about this package's install presence, enforce it.
8142            // With a singular exception for new system packages. When an OTA contains
8143            // a new system package, we allow the codepath to change from a system location
8144            // to the user-installed location. If we don't allow this change, any newer,
8145            // user-installed version of the application will be ignored.
8146            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8147                if (mExpectingBetter.containsKey(pkg.packageName)) {
8148                    logCriticalInfo(Log.WARN,
8149                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8150                } else {
8151                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8152                    if (known != null) {
8153                        if (DEBUG_PACKAGE_SCANNING) {
8154                            Log.d(TAG, "Examining " + pkg.codePath
8155                                    + " and requiring known paths " + known.codePathString
8156                                    + " & " + known.resourcePathString);
8157                        }
8158                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8159                                || !pkg.applicationInfo.getResourcePath().equals(
8160                                known.resourcePathString)) {
8161                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8162                                    "Application package " + pkg.packageName
8163                                            + " found at " + pkg.applicationInfo.getCodePath()
8164                                            + " but expected at " + known.codePathString
8165                                            + "; ignoring.");
8166                        }
8167                    }
8168                }
8169            }
8170        }
8171
8172        // Initialize package source and resource directories
8173        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8174        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8175
8176        SharedUserSetting suid = null;
8177        PackageSetting pkgSetting = null;
8178
8179        if (!isSystemApp(pkg)) {
8180            // Only system apps can use these features.
8181            pkg.mOriginalPackages = null;
8182            pkg.mRealPackage = null;
8183            pkg.mAdoptPermissions = null;
8184        }
8185
8186        // Getting the package setting may have a side-effect, so if we
8187        // are only checking if scan would succeed, stash a copy of the
8188        // old setting to restore at the end.
8189        PackageSetting nonMutatedPs = null;
8190
8191        // writer
8192        synchronized (mPackages) {
8193            if (pkg.mSharedUserId != null) {
8194                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8195                if (suid == null) {
8196                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8197                            "Creating application package " + pkg.packageName
8198                            + " for shared user failed");
8199                }
8200                if (DEBUG_PACKAGE_SCANNING) {
8201                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8202                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8203                                + "): packages=" + suid.packages);
8204                }
8205            }
8206
8207            // Check if we are renaming from an original package name.
8208            PackageSetting origPackage = null;
8209            String realName = null;
8210            if (pkg.mOriginalPackages != null) {
8211                // This package may need to be renamed to a previously
8212                // installed name.  Let's check on that...
8213                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8214                if (pkg.mOriginalPackages.contains(renamed)) {
8215                    // This package had originally been installed as the
8216                    // original name, and we have already taken care of
8217                    // transitioning to the new one.  Just update the new
8218                    // one to continue using the old name.
8219                    realName = pkg.mRealPackage;
8220                    if (!pkg.packageName.equals(renamed)) {
8221                        // Callers into this function may have already taken
8222                        // care of renaming the package; only do it here if
8223                        // it is not already done.
8224                        pkg.setPackageName(renamed);
8225                    }
8226
8227                } else {
8228                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8229                        if ((origPackage = mSettings.peekPackageLPr(
8230                                pkg.mOriginalPackages.get(i))) != null) {
8231                            // We do have the package already installed under its
8232                            // original name...  should we use it?
8233                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8234                                // New package is not compatible with original.
8235                                origPackage = null;
8236                                continue;
8237                            } else if (origPackage.sharedUser != null) {
8238                                // Make sure uid is compatible between packages.
8239                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8240                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8241                                            + " to " + pkg.packageName + ": old uid "
8242                                            + origPackage.sharedUser.name
8243                                            + " differs from " + pkg.mSharedUserId);
8244                                    origPackage = null;
8245                                    continue;
8246                                }
8247                                // TODO: Add case when shared user id is added [b/28144775]
8248                            } else {
8249                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8250                                        + pkg.packageName + " to old name " + origPackage.name);
8251                            }
8252                            break;
8253                        }
8254                    }
8255                }
8256            }
8257
8258            if (mTransferedPackages.contains(pkg.packageName)) {
8259                Slog.w(TAG, "Package " + pkg.packageName
8260                        + " was transferred to another, but its .apk remains");
8261            }
8262
8263            // See comments in nonMutatedPs declaration
8264            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8265                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8266                if (foundPs != null) {
8267                    nonMutatedPs = new PackageSetting(foundPs);
8268                }
8269            }
8270
8271            // Just create the setting, don't add it yet. For already existing packages
8272            // the PkgSetting exists already and doesn't have to be created.
8273            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8274                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8275                    pkg.applicationInfo.primaryCpuAbi,
8276                    pkg.applicationInfo.secondaryCpuAbi,
8277                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8278                    user, false);
8279            if (pkgSetting == null) {
8280                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8281                        "Creating application package " + pkg.packageName + " failed");
8282            }
8283
8284            if (pkgSetting.origPackage != null) {
8285                // If we are first transitioning from an original package,
8286                // fix up the new package's name now.  We need to do this after
8287                // looking up the package under its new name, so getPackageLP
8288                // can take care of fiddling things correctly.
8289                pkg.setPackageName(origPackage.name);
8290
8291                // File a report about this.
8292                String msg = "New package " + pkgSetting.realName
8293                        + " renamed to replace old package " + pkgSetting.name;
8294                reportSettingsProblem(Log.WARN, msg);
8295
8296                // Make a note of it.
8297                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8298                    mTransferedPackages.add(origPackage.name);
8299                }
8300
8301                // No longer need to retain this.
8302                pkgSetting.origPackage = null;
8303            }
8304
8305            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8306                // Make a note of it.
8307                mTransferedPackages.add(pkg.packageName);
8308            }
8309
8310            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8311                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8312            }
8313
8314            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8315                // Check all shared libraries and map to their actual file path.
8316                // We only do this here for apps not on a system dir, because those
8317                // are the only ones that can fail an install due to this.  We
8318                // will take care of the system apps by updating all of their
8319                // library paths after the scan is done.
8320                updateSharedLibrariesLPw(pkg, null);
8321            }
8322
8323            if (mFoundPolicyFile) {
8324                SELinuxMMAC.assignSeinfoValue(pkg);
8325            }
8326
8327            pkg.applicationInfo.uid = pkgSetting.appId;
8328            pkg.mExtras = pkgSetting;
8329            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8330                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8331                    // We just determined the app is signed correctly, so bring
8332                    // over the latest parsed certs.
8333                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8334                } else {
8335                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8336                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8337                                "Package " + pkg.packageName + " upgrade keys do not match the "
8338                                + "previously installed version");
8339                    } else {
8340                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8341                        String msg = "System package " + pkg.packageName
8342                            + " signature changed; retaining data.";
8343                        reportSettingsProblem(Log.WARN, msg);
8344                    }
8345                }
8346            } else {
8347                try {
8348                    verifySignaturesLP(pkgSetting, pkg);
8349                    // We just determined the app is signed correctly, so bring
8350                    // over the latest parsed certs.
8351                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8352                } catch (PackageManagerException e) {
8353                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8354                        throw e;
8355                    }
8356                    // The signature has changed, but this package is in the system
8357                    // image...  let's recover!
8358                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8359                    // However...  if this package is part of a shared user, but it
8360                    // doesn't match the signature of the shared user, let's fail.
8361                    // What this means is that you can't change the signatures
8362                    // associated with an overall shared user, which doesn't seem all
8363                    // that unreasonable.
8364                    if (pkgSetting.sharedUser != null) {
8365                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8366                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8367                            throw new PackageManagerException(
8368                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8369                                            "Signature mismatch for shared user: "
8370                                            + pkgSetting.sharedUser);
8371                        }
8372                    }
8373                    // File a report about this.
8374                    String msg = "System package " + pkg.packageName
8375                        + " signature changed; retaining data.";
8376                    reportSettingsProblem(Log.WARN, msg);
8377                }
8378            }
8379            // Verify that this new package doesn't have any content providers
8380            // that conflict with existing packages.  Only do this if the
8381            // package isn't already installed, since we don't want to break
8382            // things that are installed.
8383            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8384                final int N = pkg.providers.size();
8385                int i;
8386                for (i=0; i<N; i++) {
8387                    PackageParser.Provider p = pkg.providers.get(i);
8388                    if (p.info.authority != null) {
8389                        String names[] = p.info.authority.split(";");
8390                        for (int j = 0; j < names.length; j++) {
8391                            if (mProvidersByAuthority.containsKey(names[j])) {
8392                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8393                                final String otherPackageName =
8394                                        ((other != null && other.getComponentName() != null) ?
8395                                                other.getComponentName().getPackageName() : "?");
8396                                throw new PackageManagerException(
8397                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8398                                                "Can't install because provider name " + names[j]
8399                                                + " (in package " + pkg.applicationInfo.packageName
8400                                                + ") is already used by " + otherPackageName);
8401                            }
8402                        }
8403                    }
8404                }
8405            }
8406
8407            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8408                // This package wants to adopt ownership of permissions from
8409                // another package.
8410                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8411                    final String origName = pkg.mAdoptPermissions.get(i);
8412                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8413                    if (orig != null) {
8414                        if (verifyPackageUpdateLPr(orig, pkg)) {
8415                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8416                                    + pkg.packageName);
8417                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8418                        }
8419                    }
8420                }
8421            }
8422        }
8423
8424        final String pkgName = pkg.packageName;
8425
8426        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8427        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8428        pkg.applicationInfo.processName = fixProcessName(
8429                pkg.applicationInfo.packageName,
8430                pkg.applicationInfo.processName,
8431                pkg.applicationInfo.uid);
8432
8433        if (pkg != mPlatformPackage) {
8434            // Get all of our default paths setup
8435            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8436        }
8437
8438        final String path = scanFile.getPath();
8439        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8440
8441        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8442            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8443
8444            // Some system apps still use directory structure for native libraries
8445            // in which case we might end up not detecting abi solely based on apk
8446            // structure. Try to detect abi based on directory structure.
8447            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8448                    pkg.applicationInfo.primaryCpuAbi == null) {
8449                setBundledAppAbisAndRoots(pkg, pkgSetting);
8450                setNativeLibraryPaths(pkg);
8451            }
8452
8453        } else {
8454            if ((scanFlags & SCAN_MOVE) != 0) {
8455                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8456                // but we already have this packages package info in the PackageSetting. We just
8457                // use that and derive the native library path based on the new codepath.
8458                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8459                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8460            }
8461
8462            // Set native library paths again. For moves, the path will be updated based on the
8463            // ABIs we've determined above. For non-moves, the path will be updated based on the
8464            // ABIs we determined during compilation, but the path will depend on the final
8465            // package path (after the rename away from the stage path).
8466            setNativeLibraryPaths(pkg);
8467        }
8468
8469        // This is a special case for the "system" package, where the ABI is
8470        // dictated by the zygote configuration (and init.rc). We should keep track
8471        // of this ABI so that we can deal with "normal" applications that run under
8472        // the same UID correctly.
8473        if (mPlatformPackage == pkg) {
8474            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8475                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8476        }
8477
8478        // If there's a mismatch between the abi-override in the package setting
8479        // and the abiOverride specified for the install. Warn about this because we
8480        // would've already compiled the app without taking the package setting into
8481        // account.
8482        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8483            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8484                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8485                        " for package " + pkg.packageName);
8486            }
8487        }
8488
8489        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8490        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8491        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8492
8493        // Copy the derived override back to the parsed package, so that we can
8494        // update the package settings accordingly.
8495        pkg.cpuAbiOverride = cpuAbiOverride;
8496
8497        if (DEBUG_ABI_SELECTION) {
8498            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8499                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8500                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8501        }
8502
8503        // Push the derived path down into PackageSettings so we know what to
8504        // clean up at uninstall time.
8505        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8506
8507        if (DEBUG_ABI_SELECTION) {
8508            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8509                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8510                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8511        }
8512
8513        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8514            // We don't do this here during boot because we can do it all
8515            // at once after scanning all existing packages.
8516            //
8517            // We also do this *before* we perform dexopt on this package, so that
8518            // we can avoid redundant dexopts, and also to make sure we've got the
8519            // code and package path correct.
8520            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8521                    pkg, true /* boot complete */);
8522        }
8523
8524        if (mFactoryTest && pkg.requestedPermissions.contains(
8525                android.Manifest.permission.FACTORY_TEST)) {
8526            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8527        }
8528
8529        if (isSystemApp(pkg)) {
8530            pkgSetting.isOrphaned = true;
8531        }
8532
8533        ArrayList<PackageParser.Package> clientLibPkgs = null;
8534
8535        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8536            if (nonMutatedPs != null) {
8537                synchronized (mPackages) {
8538                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8539                }
8540            }
8541            return pkg;
8542        }
8543
8544        // Only privileged apps and updated privileged apps can add child packages.
8545        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8546            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8547                throw new PackageManagerException("Only privileged apps and updated "
8548                        + "privileged apps can add child packages. Ignoring package "
8549                        + pkg.packageName);
8550            }
8551            final int childCount = pkg.childPackages.size();
8552            for (int i = 0; i < childCount; i++) {
8553                PackageParser.Package childPkg = pkg.childPackages.get(i);
8554                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8555                        childPkg.packageName)) {
8556                    throw new PackageManagerException("Cannot override a child package of "
8557                            + "another disabled system app. Ignoring package " + pkg.packageName);
8558                }
8559            }
8560        }
8561
8562        // writer
8563        synchronized (mPackages) {
8564            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8565                // Only system apps can add new shared libraries.
8566                if (pkg.libraryNames != null) {
8567                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8568                        String name = pkg.libraryNames.get(i);
8569                        boolean allowed = false;
8570                        if (pkg.isUpdatedSystemApp()) {
8571                            // New library entries can only be added through the
8572                            // system image.  This is important to get rid of a lot
8573                            // of nasty edge cases: for example if we allowed a non-
8574                            // system update of the app to add a library, then uninstalling
8575                            // the update would make the library go away, and assumptions
8576                            // we made such as through app install filtering would now
8577                            // have allowed apps on the device which aren't compatible
8578                            // with it.  Better to just have the restriction here, be
8579                            // conservative, and create many fewer cases that can negatively
8580                            // impact the user experience.
8581                            final PackageSetting sysPs = mSettings
8582                                    .getDisabledSystemPkgLPr(pkg.packageName);
8583                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8584                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8585                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8586                                        allowed = true;
8587                                        break;
8588                                    }
8589                                }
8590                            }
8591                        } else {
8592                            allowed = true;
8593                        }
8594                        if (allowed) {
8595                            if (!mSharedLibraries.containsKey(name)) {
8596                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8597                            } else if (!name.equals(pkg.packageName)) {
8598                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8599                                        + name + " already exists; skipping");
8600                            }
8601                        } else {
8602                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8603                                    + name + " that is not declared on system image; skipping");
8604                        }
8605                    }
8606                    if ((scanFlags & SCAN_BOOTING) == 0) {
8607                        // If we are not booting, we need to update any applications
8608                        // that are clients of our shared library.  If we are booting,
8609                        // this will all be done once the scan is complete.
8610                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8611                    }
8612                }
8613            }
8614        }
8615
8616        if ((scanFlags & SCAN_BOOTING) != 0) {
8617            // No apps can run during boot scan, so they don't need to be frozen
8618        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8619            // Caller asked to not kill app, so it's probably not frozen
8620        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8621            // Caller asked us to ignore frozen check for some reason; they
8622            // probably didn't know the package name
8623        } else {
8624            // We're doing major surgery on this package, so it better be frozen
8625            // right now to keep it from launching
8626            checkPackageFrozen(pkgName);
8627        }
8628
8629        // Also need to kill any apps that are dependent on the library.
8630        if (clientLibPkgs != null) {
8631            for (int i=0; i<clientLibPkgs.size(); i++) {
8632                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8633                killApplication(clientPkg.applicationInfo.packageName,
8634                        clientPkg.applicationInfo.uid, "update lib");
8635            }
8636        }
8637
8638        // Make sure we're not adding any bogus keyset info
8639        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8640        ksms.assertScannedPackageValid(pkg);
8641
8642        // writer
8643        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8644
8645        boolean createIdmapFailed = false;
8646        synchronized (mPackages) {
8647            // We don't expect installation to fail beyond this point
8648
8649            // Add the new setting to mSettings
8650            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8651            // Add the new setting to mPackages
8652            mPackages.put(pkg.applicationInfo.packageName, pkg);
8653            // Make sure we don't accidentally delete its data.
8654            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8655            while (iter.hasNext()) {
8656                PackageCleanItem item = iter.next();
8657                if (pkgName.equals(item.packageName)) {
8658                    iter.remove();
8659                }
8660            }
8661
8662            // Take care of first install / last update times.
8663            if (currentTime != 0) {
8664                if (pkgSetting.firstInstallTime == 0) {
8665                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8666                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8667                    pkgSetting.lastUpdateTime = currentTime;
8668                }
8669            } else if (pkgSetting.firstInstallTime == 0) {
8670                // We need *something*.  Take time time stamp of the file.
8671                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8672            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8673                if (scanFileTime != pkgSetting.timeStamp) {
8674                    // A package on the system image has changed; consider this
8675                    // to be an update.
8676                    pkgSetting.lastUpdateTime = scanFileTime;
8677                }
8678            }
8679
8680            // Add the package's KeySets to the global KeySetManagerService
8681            ksms.addScannedPackageLPw(pkg);
8682
8683            int N = pkg.providers.size();
8684            StringBuilder r = null;
8685            int i;
8686            for (i=0; i<N; i++) {
8687                PackageParser.Provider p = pkg.providers.get(i);
8688                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8689                        p.info.processName, pkg.applicationInfo.uid);
8690                mProviders.addProvider(p);
8691                p.syncable = p.info.isSyncable;
8692                if (p.info.authority != null) {
8693                    String names[] = p.info.authority.split(";");
8694                    p.info.authority = null;
8695                    for (int j = 0; j < names.length; j++) {
8696                        if (j == 1 && p.syncable) {
8697                            // We only want the first authority for a provider to possibly be
8698                            // syncable, so if we already added this provider using a different
8699                            // authority clear the syncable flag. We copy the provider before
8700                            // changing it because the mProviders object contains a reference
8701                            // to a provider that we don't want to change.
8702                            // Only do this for the second authority since the resulting provider
8703                            // object can be the same for all future authorities for this provider.
8704                            p = new PackageParser.Provider(p);
8705                            p.syncable = false;
8706                        }
8707                        if (!mProvidersByAuthority.containsKey(names[j])) {
8708                            mProvidersByAuthority.put(names[j], p);
8709                            if (p.info.authority == null) {
8710                                p.info.authority = names[j];
8711                            } else {
8712                                p.info.authority = p.info.authority + ";" + names[j];
8713                            }
8714                            if (DEBUG_PACKAGE_SCANNING) {
8715                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8716                                    Log.d(TAG, "Registered content provider: " + names[j]
8717                                            + ", className = " + p.info.name + ", isSyncable = "
8718                                            + p.info.isSyncable);
8719                            }
8720                        } else {
8721                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8722                            Slog.w(TAG, "Skipping provider name " + names[j] +
8723                                    " (in package " + pkg.applicationInfo.packageName +
8724                                    "): name already used by "
8725                                    + ((other != null && other.getComponentName() != null)
8726                                            ? other.getComponentName().getPackageName() : "?"));
8727                        }
8728                    }
8729                }
8730                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8731                    if (r == null) {
8732                        r = new StringBuilder(256);
8733                    } else {
8734                        r.append(' ');
8735                    }
8736                    r.append(p.info.name);
8737                }
8738            }
8739            if (r != null) {
8740                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8741            }
8742
8743            N = pkg.services.size();
8744            r = null;
8745            for (i=0; i<N; i++) {
8746                PackageParser.Service s = pkg.services.get(i);
8747                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8748                        s.info.processName, pkg.applicationInfo.uid);
8749                mServices.addService(s);
8750                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8751                    if (r == null) {
8752                        r = new StringBuilder(256);
8753                    } else {
8754                        r.append(' ');
8755                    }
8756                    r.append(s.info.name);
8757                }
8758            }
8759            if (r != null) {
8760                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8761            }
8762
8763            N = pkg.receivers.size();
8764            r = null;
8765            for (i=0; i<N; i++) {
8766                PackageParser.Activity a = pkg.receivers.get(i);
8767                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8768                        a.info.processName, pkg.applicationInfo.uid);
8769                mReceivers.addActivity(a, "receiver");
8770                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8771                    if (r == null) {
8772                        r = new StringBuilder(256);
8773                    } else {
8774                        r.append(' ');
8775                    }
8776                    r.append(a.info.name);
8777                }
8778            }
8779            if (r != null) {
8780                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8781            }
8782
8783            N = pkg.activities.size();
8784            r = null;
8785            for (i=0; i<N; i++) {
8786                PackageParser.Activity a = pkg.activities.get(i);
8787                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8788                        a.info.processName, pkg.applicationInfo.uid);
8789                mActivities.addActivity(a, "activity");
8790                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8791                    if (r == null) {
8792                        r = new StringBuilder(256);
8793                    } else {
8794                        r.append(' ');
8795                    }
8796                    r.append(a.info.name);
8797                }
8798            }
8799            if (r != null) {
8800                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8801            }
8802
8803            N = pkg.permissionGroups.size();
8804            r = null;
8805            for (i=0; i<N; i++) {
8806                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8807                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8808                final String curPackageName = cur == null ? null : cur.info.packageName;
8809                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8810                if (cur == null || isPackageUpdate) {
8811                    mPermissionGroups.put(pg.info.name, pg);
8812                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8813                        if (r == null) {
8814                            r = new StringBuilder(256);
8815                        } else {
8816                            r.append(' ');
8817                        }
8818                        if (isPackageUpdate) {
8819                            r.append("UPD:");
8820                        }
8821                        r.append(pg.info.name);
8822                    }
8823                } else {
8824                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8825                            + pg.info.packageName + " ignored: original from "
8826                            + cur.info.packageName);
8827                    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(pg.info.name);
8835                    }
8836                }
8837            }
8838            if (r != null) {
8839                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8840            }
8841
8842            N = pkg.permissions.size();
8843            r = null;
8844            for (i=0; i<N; i++) {
8845                PackageParser.Permission p = pkg.permissions.get(i);
8846
8847                // Assume by default that we did not install this permission into the system.
8848                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8849
8850                // Now that permission groups have a special meaning, we ignore permission
8851                // groups for legacy apps to prevent unexpected behavior. In particular,
8852                // permissions for one app being granted to someone just becase they happen
8853                // to be in a group defined by another app (before this had no implications).
8854                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8855                    p.group = mPermissionGroups.get(p.info.group);
8856                    // Warn for a permission in an unknown group.
8857                    if (p.info.group != null && p.group == null) {
8858                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8859                                + p.info.packageName + " in an unknown group " + p.info.group);
8860                    }
8861                }
8862
8863                ArrayMap<String, BasePermission> permissionMap =
8864                        p.tree ? mSettings.mPermissionTrees
8865                                : mSettings.mPermissions;
8866                BasePermission bp = permissionMap.get(p.info.name);
8867
8868                // Allow system apps to redefine non-system permissions
8869                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8870                    final boolean currentOwnerIsSystem = (bp.perm != null
8871                            && isSystemApp(bp.perm.owner));
8872                    if (isSystemApp(p.owner)) {
8873                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8874                            // It's a built-in permission and no owner, take ownership now
8875                            bp.packageSetting = pkgSetting;
8876                            bp.perm = p;
8877                            bp.uid = pkg.applicationInfo.uid;
8878                            bp.sourcePackage = p.info.packageName;
8879                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8880                        } else if (!currentOwnerIsSystem) {
8881                            String msg = "New decl " + p.owner + " of permission  "
8882                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8883                            reportSettingsProblem(Log.WARN, msg);
8884                            bp = null;
8885                        }
8886                    }
8887                }
8888
8889                if (bp == null) {
8890                    bp = new BasePermission(p.info.name, p.info.packageName,
8891                            BasePermission.TYPE_NORMAL);
8892                    permissionMap.put(p.info.name, bp);
8893                }
8894
8895                if (bp.perm == null) {
8896                    if (bp.sourcePackage == null
8897                            || bp.sourcePackage.equals(p.info.packageName)) {
8898                        BasePermission tree = findPermissionTreeLP(p.info.name);
8899                        if (tree == null
8900                                || tree.sourcePackage.equals(p.info.packageName)) {
8901                            bp.packageSetting = pkgSetting;
8902                            bp.perm = p;
8903                            bp.uid = pkg.applicationInfo.uid;
8904                            bp.sourcePackage = p.info.packageName;
8905                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8906                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8907                                if (r == null) {
8908                                    r = new StringBuilder(256);
8909                                } else {
8910                                    r.append(' ');
8911                                }
8912                                r.append(p.info.name);
8913                            }
8914                        } else {
8915                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8916                                    + p.info.packageName + " ignored: base tree "
8917                                    + tree.name + " is from package "
8918                                    + tree.sourcePackage);
8919                        }
8920                    } else {
8921                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8922                                + p.info.packageName + " ignored: original from "
8923                                + bp.sourcePackage);
8924                    }
8925                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8926                    if (r == null) {
8927                        r = new StringBuilder(256);
8928                    } else {
8929                        r.append(' ');
8930                    }
8931                    r.append("DUP:");
8932                    r.append(p.info.name);
8933                }
8934                if (bp.perm == p) {
8935                    bp.protectionLevel = p.info.protectionLevel;
8936                }
8937            }
8938
8939            if (r != null) {
8940                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8941            }
8942
8943            N = pkg.instrumentation.size();
8944            r = null;
8945            for (i=0; i<N; i++) {
8946                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8947                a.info.packageName = pkg.applicationInfo.packageName;
8948                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8949                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8950                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8951                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8952                a.info.dataDir = pkg.applicationInfo.dataDir;
8953                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8954                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8955
8956                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8957                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8958                mInstrumentation.put(a.getComponentName(), a);
8959                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8960                    if (r == null) {
8961                        r = new StringBuilder(256);
8962                    } else {
8963                        r.append(' ');
8964                    }
8965                    r.append(a.info.name);
8966                }
8967            }
8968            if (r != null) {
8969                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8970            }
8971
8972            if (pkg.protectedBroadcasts != null) {
8973                N = pkg.protectedBroadcasts.size();
8974                for (i=0; i<N; i++) {
8975                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8976                }
8977            }
8978
8979            pkgSetting.setTimeStamp(scanFileTime);
8980
8981            // Create idmap files for pairs of (packages, overlay packages).
8982            // Note: "android", ie framework-res.apk, is handled by native layers.
8983            if (pkg.mOverlayTarget != null) {
8984                // This is an overlay package.
8985                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8986                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8987                        mOverlays.put(pkg.mOverlayTarget,
8988                                new ArrayMap<String, PackageParser.Package>());
8989                    }
8990                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8991                    map.put(pkg.packageName, pkg);
8992                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8993                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8994                        createIdmapFailed = true;
8995                    }
8996                }
8997            } else if (mOverlays.containsKey(pkg.packageName) &&
8998                    !pkg.packageName.equals("android")) {
8999                // This is a regular package, with one or more known overlay packages.
9000                createIdmapsForPackageLI(pkg);
9001            }
9002        }
9003
9004        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9005
9006        if (createIdmapFailed) {
9007            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9008                    "scanPackageLI failed to createIdmap");
9009        }
9010        return pkg;
9011    }
9012
9013    /**
9014     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9015     * is derived purely on the basis of the contents of {@code scanFile} and
9016     * {@code cpuAbiOverride}.
9017     *
9018     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9019     */
9020    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9021                                 String cpuAbiOverride, boolean extractLibs)
9022            throws PackageManagerException {
9023        // TODO: We can probably be smarter about this stuff. For installed apps,
9024        // we can calculate this information at install time once and for all. For
9025        // system apps, we can probably assume that this information doesn't change
9026        // after the first boot scan. As things stand, we do lots of unnecessary work.
9027
9028        // Give ourselves some initial paths; we'll come back for another
9029        // pass once we've determined ABI below.
9030        setNativeLibraryPaths(pkg);
9031
9032        // We would never need to extract libs for forward-locked and external packages,
9033        // since the container service will do it for us. We shouldn't attempt to
9034        // extract libs from system app when it was not updated.
9035        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9036                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9037            extractLibs = false;
9038        }
9039
9040        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9041        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9042
9043        NativeLibraryHelper.Handle handle = null;
9044        try {
9045            handle = NativeLibraryHelper.Handle.create(pkg);
9046            // TODO(multiArch): This can be null for apps that didn't go through the
9047            // usual installation process. We can calculate it again, like we
9048            // do during install time.
9049            //
9050            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9051            // unnecessary.
9052            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9053
9054            // Null out the abis so that they can be recalculated.
9055            pkg.applicationInfo.primaryCpuAbi = null;
9056            pkg.applicationInfo.secondaryCpuAbi = null;
9057            if (isMultiArch(pkg.applicationInfo)) {
9058                // Warn if we've set an abiOverride for multi-lib packages..
9059                // By definition, we need to copy both 32 and 64 bit libraries for
9060                // such packages.
9061                if (pkg.cpuAbiOverride != null
9062                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9063                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9064                }
9065
9066                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9067                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9068                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9069                    if (extractLibs) {
9070                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9071                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9072                                useIsaSpecificSubdirs);
9073                    } else {
9074                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9075                    }
9076                }
9077
9078                maybeThrowExceptionForMultiArchCopy(
9079                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9080
9081                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9082                    if (extractLibs) {
9083                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9084                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9085                                useIsaSpecificSubdirs);
9086                    } else {
9087                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9088                    }
9089                }
9090
9091                maybeThrowExceptionForMultiArchCopy(
9092                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9093
9094                if (abi64 >= 0) {
9095                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9096                }
9097
9098                if (abi32 >= 0) {
9099                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9100                    if (abi64 >= 0) {
9101                        if (pkg.use32bitAbi) {
9102                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9103                            pkg.applicationInfo.primaryCpuAbi = abi;
9104                        } else {
9105                            pkg.applicationInfo.secondaryCpuAbi = abi;
9106                        }
9107                    } else {
9108                        pkg.applicationInfo.primaryCpuAbi = abi;
9109                    }
9110                }
9111
9112            } else {
9113                String[] abiList = (cpuAbiOverride != null) ?
9114                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9115
9116                // Enable gross and lame hacks for apps that are built with old
9117                // SDK tools. We must scan their APKs for renderscript bitcode and
9118                // not launch them if it's present. Don't bother checking on devices
9119                // that don't have 64 bit support.
9120                boolean needsRenderScriptOverride = false;
9121                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9122                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9123                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9124                    needsRenderScriptOverride = true;
9125                }
9126
9127                final int copyRet;
9128                if (extractLibs) {
9129                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9130                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9131                } else {
9132                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9133                }
9134
9135                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9136                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9137                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9138                }
9139
9140                if (copyRet >= 0) {
9141                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9142                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9143                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9144                } else if (needsRenderScriptOverride) {
9145                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9146                }
9147            }
9148        } catch (IOException ioe) {
9149            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9150        } finally {
9151            IoUtils.closeQuietly(handle);
9152        }
9153
9154        // Now that we've calculated the ABIs and determined if it's an internal app,
9155        // we will go ahead and populate the nativeLibraryPath.
9156        setNativeLibraryPaths(pkg);
9157    }
9158
9159    /**
9160     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9161     * i.e, so that all packages can be run inside a single process if required.
9162     *
9163     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9164     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9165     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9166     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9167     * updating a package that belongs to a shared user.
9168     *
9169     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9170     * adds unnecessary complexity.
9171     */
9172    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9173            PackageParser.Package scannedPackage, boolean bootComplete) {
9174        String requiredInstructionSet = null;
9175        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9176            requiredInstructionSet = VMRuntime.getInstructionSet(
9177                     scannedPackage.applicationInfo.primaryCpuAbi);
9178        }
9179
9180        PackageSetting requirer = null;
9181        for (PackageSetting ps : packagesForUser) {
9182            // If packagesForUser contains scannedPackage, we skip it. This will happen
9183            // when scannedPackage is an update of an existing package. Without this check,
9184            // we will never be able to change the ABI of any package belonging to a shared
9185            // user, even if it's compatible with other packages.
9186            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9187                if (ps.primaryCpuAbiString == null) {
9188                    continue;
9189                }
9190
9191                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9192                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9193                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9194                    // this but there's not much we can do.
9195                    String errorMessage = "Instruction set mismatch, "
9196                            + ((requirer == null) ? "[caller]" : requirer)
9197                            + " requires " + requiredInstructionSet + " whereas " + ps
9198                            + " requires " + instructionSet;
9199                    Slog.w(TAG, errorMessage);
9200                }
9201
9202                if (requiredInstructionSet == null) {
9203                    requiredInstructionSet = instructionSet;
9204                    requirer = ps;
9205                }
9206            }
9207        }
9208
9209        if (requiredInstructionSet != null) {
9210            String adjustedAbi;
9211            if (requirer != null) {
9212                // requirer != null implies that either scannedPackage was null or that scannedPackage
9213                // did not require an ABI, in which case we have to adjust scannedPackage to match
9214                // the ABI of the set (which is the same as requirer's ABI)
9215                adjustedAbi = requirer.primaryCpuAbiString;
9216                if (scannedPackage != null) {
9217                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9218                }
9219            } else {
9220                // requirer == null implies that we're updating all ABIs in the set to
9221                // match scannedPackage.
9222                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9223            }
9224
9225            for (PackageSetting ps : packagesForUser) {
9226                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9227                    if (ps.primaryCpuAbiString != null) {
9228                        continue;
9229                    }
9230
9231                    ps.primaryCpuAbiString = adjustedAbi;
9232                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9233                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9234                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9235                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9236                                + " (requirer="
9237                                + (requirer == null ? "null" : requirer.pkg.packageName)
9238                                + ", scannedPackage="
9239                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9240                                + ")");
9241                        try {
9242                            mInstaller.rmdex(ps.codePathString,
9243                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9244                        } catch (InstallerException ignored) {
9245                        }
9246                    }
9247                }
9248            }
9249        }
9250    }
9251
9252    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9253        synchronized (mPackages) {
9254            mResolverReplaced = true;
9255            // Set up information for custom user intent resolution activity.
9256            mResolveActivity.applicationInfo = pkg.applicationInfo;
9257            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9258            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9259            mResolveActivity.processName = pkg.applicationInfo.packageName;
9260            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9261            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9262                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9263            mResolveActivity.theme = 0;
9264            mResolveActivity.exported = true;
9265            mResolveActivity.enabled = true;
9266            mResolveInfo.activityInfo = mResolveActivity;
9267            mResolveInfo.priority = 0;
9268            mResolveInfo.preferredOrder = 0;
9269            mResolveInfo.match = 0;
9270            mResolveComponentName = mCustomResolverComponentName;
9271            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9272                    mResolveComponentName);
9273        }
9274    }
9275
9276    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9277        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9278
9279        // Set up information for ephemeral installer activity
9280        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9281        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9282        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9283        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9284        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9285        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9286                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9287        mEphemeralInstallerActivity.theme = 0;
9288        mEphemeralInstallerActivity.exported = true;
9289        mEphemeralInstallerActivity.enabled = true;
9290        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9291        mEphemeralInstallerInfo.priority = 0;
9292        mEphemeralInstallerInfo.preferredOrder = 1;
9293        mEphemeralInstallerInfo.isDefault = true;
9294        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9295                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9296
9297        if (DEBUG_EPHEMERAL) {
9298            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9299        }
9300    }
9301
9302    private static String calculateBundledApkRoot(final String codePathString) {
9303        final File codePath = new File(codePathString);
9304        final File codeRoot;
9305        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9306            codeRoot = Environment.getRootDirectory();
9307        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9308            codeRoot = Environment.getOemDirectory();
9309        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9310            codeRoot = Environment.getVendorDirectory();
9311        } else {
9312            // Unrecognized code path; take its top real segment as the apk root:
9313            // e.g. /something/app/blah.apk => /something
9314            try {
9315                File f = codePath.getCanonicalFile();
9316                File parent = f.getParentFile();    // non-null because codePath is a file
9317                File tmp;
9318                while ((tmp = parent.getParentFile()) != null) {
9319                    f = parent;
9320                    parent = tmp;
9321                }
9322                codeRoot = f;
9323                Slog.w(TAG, "Unrecognized code path "
9324                        + codePath + " - using " + codeRoot);
9325            } catch (IOException e) {
9326                // Can't canonicalize the code path -- shenanigans?
9327                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9328                return Environment.getRootDirectory().getPath();
9329            }
9330        }
9331        return codeRoot.getPath();
9332    }
9333
9334    /**
9335     * Derive and set the location of native libraries for the given package,
9336     * which varies depending on where and how the package was installed.
9337     */
9338    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9339        final ApplicationInfo info = pkg.applicationInfo;
9340        final String codePath = pkg.codePath;
9341        final File codeFile = new File(codePath);
9342        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9343        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9344
9345        info.nativeLibraryRootDir = null;
9346        info.nativeLibraryRootRequiresIsa = false;
9347        info.nativeLibraryDir = null;
9348        info.secondaryNativeLibraryDir = null;
9349
9350        if (isApkFile(codeFile)) {
9351            // Monolithic install
9352            if (bundledApp) {
9353                // If "/system/lib64/apkname" exists, assume that is the per-package
9354                // native library directory to use; otherwise use "/system/lib/apkname".
9355                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9356                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9357                        getPrimaryInstructionSet(info));
9358
9359                // This is a bundled system app so choose the path based on the ABI.
9360                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9361                // is just the default path.
9362                final String apkName = deriveCodePathName(codePath);
9363                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9364                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9365                        apkName).getAbsolutePath();
9366
9367                if (info.secondaryCpuAbi != null) {
9368                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9369                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9370                            secondaryLibDir, apkName).getAbsolutePath();
9371                }
9372            } else if (asecApp) {
9373                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9374                        .getAbsolutePath();
9375            } else {
9376                final String apkName = deriveCodePathName(codePath);
9377                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9378                        .getAbsolutePath();
9379            }
9380
9381            info.nativeLibraryRootRequiresIsa = false;
9382            info.nativeLibraryDir = info.nativeLibraryRootDir;
9383        } else {
9384            // Cluster install
9385            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9386            info.nativeLibraryRootRequiresIsa = true;
9387
9388            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9389                    getPrimaryInstructionSet(info)).getAbsolutePath();
9390
9391            if (info.secondaryCpuAbi != null) {
9392                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9393                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9394            }
9395        }
9396    }
9397
9398    /**
9399     * Calculate the abis and roots for a bundled app. These can uniquely
9400     * be determined from the contents of the system partition, i.e whether
9401     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9402     * of this information, and instead assume that the system was built
9403     * sensibly.
9404     */
9405    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9406                                           PackageSetting pkgSetting) {
9407        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9408
9409        // If "/system/lib64/apkname" exists, assume that is the per-package
9410        // native library directory to use; otherwise use "/system/lib/apkname".
9411        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9412        setBundledAppAbi(pkg, apkRoot, apkName);
9413        // pkgSetting might be null during rescan following uninstall of updates
9414        // to a bundled app, so accommodate that possibility.  The settings in
9415        // that case will be established later from the parsed package.
9416        //
9417        // If the settings aren't null, sync them up with what we've just derived.
9418        // note that apkRoot isn't stored in the package settings.
9419        if (pkgSetting != null) {
9420            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9421            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9422        }
9423    }
9424
9425    /**
9426     * Deduces the ABI of a bundled app and sets the relevant fields on the
9427     * parsed pkg object.
9428     *
9429     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9430     *        under which system libraries are installed.
9431     * @param apkName the name of the installed package.
9432     */
9433    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9434        final File codeFile = new File(pkg.codePath);
9435
9436        final boolean has64BitLibs;
9437        final boolean has32BitLibs;
9438        if (isApkFile(codeFile)) {
9439            // Monolithic install
9440            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9441            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9442        } else {
9443            // Cluster install
9444            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9445            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9446                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9447                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9448                has64BitLibs = (new File(rootDir, isa)).exists();
9449            } else {
9450                has64BitLibs = false;
9451            }
9452            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9453                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9454                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9455                has32BitLibs = (new File(rootDir, isa)).exists();
9456            } else {
9457                has32BitLibs = false;
9458            }
9459        }
9460
9461        if (has64BitLibs && !has32BitLibs) {
9462            // The package has 64 bit libs, but not 32 bit libs. Its primary
9463            // ABI should be 64 bit. We can safely assume here that the bundled
9464            // native libraries correspond to the most preferred ABI in the list.
9465
9466            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9467            pkg.applicationInfo.secondaryCpuAbi = null;
9468        } else if (has32BitLibs && !has64BitLibs) {
9469            // The package has 32 bit libs but not 64 bit libs. Its primary
9470            // ABI should be 32 bit.
9471
9472            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9473            pkg.applicationInfo.secondaryCpuAbi = null;
9474        } else if (has32BitLibs && has64BitLibs) {
9475            // The application has both 64 and 32 bit bundled libraries. We check
9476            // here that the app declares multiArch support, and warn if it doesn't.
9477            //
9478            // We will be lenient here and record both ABIs. The primary will be the
9479            // ABI that's higher on the list, i.e, a device that's configured to prefer
9480            // 64 bit apps will see a 64 bit primary ABI,
9481
9482            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9483                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9484            }
9485
9486            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9487                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9488                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9489            } else {
9490                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9491                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9492            }
9493        } else {
9494            pkg.applicationInfo.primaryCpuAbi = null;
9495            pkg.applicationInfo.secondaryCpuAbi = null;
9496        }
9497    }
9498
9499    private void killApplication(String pkgName, int appId, String reason) {
9500        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9501    }
9502
9503    private void killApplication(String pkgName, int appId, int userId, String reason) {
9504        // Request the ActivityManager to kill the process(only for existing packages)
9505        // so that we do not end up in a confused state while the user is still using the older
9506        // version of the application while the new one gets installed.
9507        final long token = Binder.clearCallingIdentity();
9508        try {
9509            IActivityManager am = ActivityManagerNative.getDefault();
9510            if (am != null) {
9511                try {
9512                    am.killApplication(pkgName, appId, userId, reason);
9513                } catch (RemoteException e) {
9514                }
9515            }
9516        } finally {
9517            Binder.restoreCallingIdentity(token);
9518        }
9519    }
9520
9521    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9522        // Remove the parent package setting
9523        PackageSetting ps = (PackageSetting) pkg.mExtras;
9524        if (ps != null) {
9525            removePackageLI(ps, chatty);
9526        }
9527        // Remove the child package setting
9528        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9529        for (int i = 0; i < childCount; i++) {
9530            PackageParser.Package childPkg = pkg.childPackages.get(i);
9531            ps = (PackageSetting) childPkg.mExtras;
9532            if (ps != null) {
9533                removePackageLI(ps, chatty);
9534            }
9535        }
9536    }
9537
9538    void removePackageLI(PackageSetting ps, boolean chatty) {
9539        if (DEBUG_INSTALL) {
9540            if (chatty)
9541                Log.d(TAG, "Removing package " + ps.name);
9542        }
9543
9544        // writer
9545        synchronized (mPackages) {
9546            mPackages.remove(ps.name);
9547            final PackageParser.Package pkg = ps.pkg;
9548            if (pkg != null) {
9549                cleanPackageDataStructuresLILPw(pkg, chatty);
9550            }
9551        }
9552    }
9553
9554    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9555        if (DEBUG_INSTALL) {
9556            if (chatty)
9557                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9558        }
9559
9560        // writer
9561        synchronized (mPackages) {
9562            // Remove the parent package
9563            mPackages.remove(pkg.applicationInfo.packageName);
9564            cleanPackageDataStructuresLILPw(pkg, chatty);
9565
9566            // Remove the child packages
9567            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9568            for (int i = 0; i < childCount; i++) {
9569                PackageParser.Package childPkg = pkg.childPackages.get(i);
9570                mPackages.remove(childPkg.applicationInfo.packageName);
9571                cleanPackageDataStructuresLILPw(childPkg, chatty);
9572            }
9573        }
9574    }
9575
9576    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9577        int N = pkg.providers.size();
9578        StringBuilder r = null;
9579        int i;
9580        for (i=0; i<N; i++) {
9581            PackageParser.Provider p = pkg.providers.get(i);
9582            mProviders.removeProvider(p);
9583            if (p.info.authority == null) {
9584
9585                /* There was another ContentProvider with this authority when
9586                 * this app was installed so this authority is null,
9587                 * Ignore it as we don't have to unregister the provider.
9588                 */
9589                continue;
9590            }
9591            String names[] = p.info.authority.split(";");
9592            for (int j = 0; j < names.length; j++) {
9593                if (mProvidersByAuthority.get(names[j]) == p) {
9594                    mProvidersByAuthority.remove(names[j]);
9595                    if (DEBUG_REMOVE) {
9596                        if (chatty)
9597                            Log.d(TAG, "Unregistered content provider: " + names[j]
9598                                    + ", className = " + p.info.name + ", isSyncable = "
9599                                    + p.info.isSyncable);
9600                    }
9601                }
9602            }
9603            if (DEBUG_REMOVE && chatty) {
9604                if (r == null) {
9605                    r = new StringBuilder(256);
9606                } else {
9607                    r.append(' ');
9608                }
9609                r.append(p.info.name);
9610            }
9611        }
9612        if (r != null) {
9613            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9614        }
9615
9616        N = pkg.services.size();
9617        r = null;
9618        for (i=0; i<N; i++) {
9619            PackageParser.Service s = pkg.services.get(i);
9620            mServices.removeService(s);
9621            if (chatty) {
9622                if (r == null) {
9623                    r = new StringBuilder(256);
9624                } else {
9625                    r.append(' ');
9626                }
9627                r.append(s.info.name);
9628            }
9629        }
9630        if (r != null) {
9631            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9632        }
9633
9634        N = pkg.receivers.size();
9635        r = null;
9636        for (i=0; i<N; i++) {
9637            PackageParser.Activity a = pkg.receivers.get(i);
9638            mReceivers.removeActivity(a, "receiver");
9639            if (DEBUG_REMOVE && chatty) {
9640                if (r == null) {
9641                    r = new StringBuilder(256);
9642                } else {
9643                    r.append(' ');
9644                }
9645                r.append(a.info.name);
9646            }
9647        }
9648        if (r != null) {
9649            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9650        }
9651
9652        N = pkg.activities.size();
9653        r = null;
9654        for (i=0; i<N; i++) {
9655            PackageParser.Activity a = pkg.activities.get(i);
9656            mActivities.removeActivity(a, "activity");
9657            if (DEBUG_REMOVE && chatty) {
9658                if (r == null) {
9659                    r = new StringBuilder(256);
9660                } else {
9661                    r.append(' ');
9662                }
9663                r.append(a.info.name);
9664            }
9665        }
9666        if (r != null) {
9667            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9668        }
9669
9670        N = pkg.permissions.size();
9671        r = null;
9672        for (i=0; i<N; i++) {
9673            PackageParser.Permission p = pkg.permissions.get(i);
9674            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9675            if (bp == null) {
9676                bp = mSettings.mPermissionTrees.get(p.info.name);
9677            }
9678            if (bp != null && bp.perm == p) {
9679                bp.perm = null;
9680                if (DEBUG_REMOVE && chatty) {
9681                    if (r == null) {
9682                        r = new StringBuilder(256);
9683                    } else {
9684                        r.append(' ');
9685                    }
9686                    r.append(p.info.name);
9687                }
9688            }
9689            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9690                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9691                if (appOpPkgs != null) {
9692                    appOpPkgs.remove(pkg.packageName);
9693                }
9694            }
9695        }
9696        if (r != null) {
9697            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9698        }
9699
9700        N = pkg.requestedPermissions.size();
9701        r = null;
9702        for (i=0; i<N; i++) {
9703            String perm = pkg.requestedPermissions.get(i);
9704            BasePermission bp = mSettings.mPermissions.get(perm);
9705            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9706                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9707                if (appOpPkgs != null) {
9708                    appOpPkgs.remove(pkg.packageName);
9709                    if (appOpPkgs.isEmpty()) {
9710                        mAppOpPermissionPackages.remove(perm);
9711                    }
9712                }
9713            }
9714        }
9715        if (r != null) {
9716            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9717        }
9718
9719        N = pkg.instrumentation.size();
9720        r = null;
9721        for (i=0; i<N; i++) {
9722            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9723            mInstrumentation.remove(a.getComponentName());
9724            if (DEBUG_REMOVE && chatty) {
9725                if (r == null) {
9726                    r = new StringBuilder(256);
9727                } else {
9728                    r.append(' ');
9729                }
9730                r.append(a.info.name);
9731            }
9732        }
9733        if (r != null) {
9734            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9735        }
9736
9737        r = null;
9738        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9739            // Only system apps can hold shared libraries.
9740            if (pkg.libraryNames != null) {
9741                for (i=0; i<pkg.libraryNames.size(); i++) {
9742                    String name = pkg.libraryNames.get(i);
9743                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9744                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9745                        mSharedLibraries.remove(name);
9746                        if (DEBUG_REMOVE && chatty) {
9747                            if (r == null) {
9748                                r = new StringBuilder(256);
9749                            } else {
9750                                r.append(' ');
9751                            }
9752                            r.append(name);
9753                        }
9754                    }
9755                }
9756            }
9757        }
9758        if (r != null) {
9759            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9760        }
9761    }
9762
9763    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9764        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9765            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9766                return true;
9767            }
9768        }
9769        return false;
9770    }
9771
9772    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9773    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9774    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9775
9776    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9777        // Update the parent permissions
9778        updatePermissionsLPw(pkg.packageName, pkg, flags);
9779        // Update the child permissions
9780        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9781        for (int i = 0; i < childCount; i++) {
9782            PackageParser.Package childPkg = pkg.childPackages.get(i);
9783            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9784        }
9785    }
9786
9787    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9788            int flags) {
9789        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9790        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9791    }
9792
9793    private void updatePermissionsLPw(String changingPkg,
9794            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9795        // Make sure there are no dangling permission trees.
9796        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9797        while (it.hasNext()) {
9798            final BasePermission bp = it.next();
9799            if (bp.packageSetting == null) {
9800                // We may not yet have parsed the package, so just see if
9801                // we still know about its settings.
9802                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9803            }
9804            if (bp.packageSetting == null) {
9805                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9806                        + " from package " + bp.sourcePackage);
9807                it.remove();
9808            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9809                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9810                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9811                            + " from package " + bp.sourcePackage);
9812                    flags |= UPDATE_PERMISSIONS_ALL;
9813                    it.remove();
9814                }
9815            }
9816        }
9817
9818        // Make sure all dynamic permissions have been assigned to a package,
9819        // and make sure there are no dangling permissions.
9820        it = mSettings.mPermissions.values().iterator();
9821        while (it.hasNext()) {
9822            final BasePermission bp = it.next();
9823            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9824                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9825                        + bp.name + " pkg=" + bp.sourcePackage
9826                        + " info=" + bp.pendingInfo);
9827                if (bp.packageSetting == null && bp.pendingInfo != null) {
9828                    final BasePermission tree = findPermissionTreeLP(bp.name);
9829                    if (tree != null && tree.perm != null) {
9830                        bp.packageSetting = tree.packageSetting;
9831                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9832                                new PermissionInfo(bp.pendingInfo));
9833                        bp.perm.info.packageName = tree.perm.info.packageName;
9834                        bp.perm.info.name = bp.name;
9835                        bp.uid = tree.uid;
9836                    }
9837                }
9838            }
9839            if (bp.packageSetting == null) {
9840                // We may not yet have parsed the package, so just see if
9841                // we still know about its settings.
9842                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9843            }
9844            if (bp.packageSetting == null) {
9845                Slog.w(TAG, "Removing dangling permission: " + bp.name
9846                        + " from package " + bp.sourcePackage);
9847                it.remove();
9848            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9849                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9850                    Slog.i(TAG, "Removing old permission: " + bp.name
9851                            + " from package " + bp.sourcePackage);
9852                    flags |= UPDATE_PERMISSIONS_ALL;
9853                    it.remove();
9854                }
9855            }
9856        }
9857
9858        // Now update the permissions for all packages, in particular
9859        // replace the granted permissions of the system packages.
9860        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9861            for (PackageParser.Package pkg : mPackages.values()) {
9862                if (pkg != pkgInfo) {
9863                    // Only replace for packages on requested volume
9864                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9865                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9866                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9867                    grantPermissionsLPw(pkg, replace, changingPkg);
9868                }
9869            }
9870        }
9871
9872        if (pkgInfo != null) {
9873            // Only replace for packages on requested volume
9874            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9875            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9876                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9877            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9878        }
9879    }
9880
9881    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9882            String packageOfInterest) {
9883        // IMPORTANT: There are two types of permissions: install and runtime.
9884        // Install time permissions are granted when the app is installed to
9885        // all device users and users added in the future. Runtime permissions
9886        // are granted at runtime explicitly to specific users. Normal and signature
9887        // protected permissions are install time permissions. Dangerous permissions
9888        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9889        // otherwise they are runtime permissions. This function does not manage
9890        // runtime permissions except for the case an app targeting Lollipop MR1
9891        // being upgraded to target a newer SDK, in which case dangerous permissions
9892        // are transformed from install time to runtime ones.
9893
9894        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9895        if (ps == null) {
9896            return;
9897        }
9898
9899        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9900
9901        PermissionsState permissionsState = ps.getPermissionsState();
9902        PermissionsState origPermissions = permissionsState;
9903
9904        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9905
9906        boolean runtimePermissionsRevoked = false;
9907        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9908
9909        boolean changedInstallPermission = false;
9910
9911        if (replace) {
9912            ps.installPermissionsFixed = false;
9913            if (!ps.isSharedUser()) {
9914                origPermissions = new PermissionsState(permissionsState);
9915                permissionsState.reset();
9916            } else {
9917                // We need to know only about runtime permission changes since the
9918                // calling code always writes the install permissions state but
9919                // the runtime ones are written only if changed. The only cases of
9920                // changed runtime permissions here are promotion of an install to
9921                // runtime and revocation of a runtime from a shared user.
9922                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9923                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9924                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9925                    runtimePermissionsRevoked = true;
9926                }
9927            }
9928        }
9929
9930        permissionsState.setGlobalGids(mGlobalGids);
9931
9932        final int N = pkg.requestedPermissions.size();
9933        for (int i=0; i<N; i++) {
9934            final String name = pkg.requestedPermissions.get(i);
9935            final BasePermission bp = mSettings.mPermissions.get(name);
9936
9937            if (DEBUG_INSTALL) {
9938                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9939            }
9940
9941            if (bp == null || bp.packageSetting == null) {
9942                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9943                    Slog.w(TAG, "Unknown permission " + name
9944                            + " in package " + pkg.packageName);
9945                }
9946                continue;
9947            }
9948
9949            final String perm = bp.name;
9950            boolean allowedSig = false;
9951            int grant = GRANT_DENIED;
9952
9953            // Keep track of app op permissions.
9954            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9955                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9956                if (pkgs == null) {
9957                    pkgs = new ArraySet<>();
9958                    mAppOpPermissionPackages.put(bp.name, pkgs);
9959                }
9960                pkgs.add(pkg.packageName);
9961            }
9962
9963            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9964            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9965                    >= Build.VERSION_CODES.M;
9966            switch (level) {
9967                case PermissionInfo.PROTECTION_NORMAL: {
9968                    // For all apps normal permissions are install time ones.
9969                    grant = GRANT_INSTALL;
9970                } break;
9971
9972                case PermissionInfo.PROTECTION_DANGEROUS: {
9973                    // If a permission review is required for legacy apps we represent
9974                    // their permissions as always granted runtime ones since we need
9975                    // to keep the review required permission flag per user while an
9976                    // install permission's state is shared across all users.
9977                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired
9978                            && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9979                        // For legacy apps dangerous permissions are install time ones.
9980                        grant = GRANT_INSTALL;
9981                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9982                        // For legacy apps that became modern, install becomes runtime.
9983                        grant = GRANT_UPGRADE;
9984                    } else if (mPromoteSystemApps
9985                            && isSystemApp(ps)
9986                            && mExistingSystemPackages.contains(ps.name)) {
9987                        // For legacy system apps, install becomes runtime.
9988                        // We cannot check hasInstallPermission() for system apps since those
9989                        // permissions were granted implicitly and not persisted pre-M.
9990                        grant = GRANT_UPGRADE;
9991                    } else {
9992                        // For modern apps keep runtime permissions unchanged.
9993                        grant = GRANT_RUNTIME;
9994                    }
9995                } break;
9996
9997                case PermissionInfo.PROTECTION_SIGNATURE: {
9998                    // For all apps signature permissions are install time ones.
9999                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10000                    if (allowedSig) {
10001                        grant = GRANT_INSTALL;
10002                    }
10003                } break;
10004            }
10005
10006            if (DEBUG_INSTALL) {
10007                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10008            }
10009
10010            if (grant != GRANT_DENIED) {
10011                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10012                    // If this is an existing, non-system package, then
10013                    // we can't add any new permissions to it.
10014                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10015                        // Except...  if this is a permission that was added
10016                        // to the platform (note: need to only do this when
10017                        // updating the platform).
10018                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10019                            grant = GRANT_DENIED;
10020                        }
10021                    }
10022                }
10023
10024                switch (grant) {
10025                    case GRANT_INSTALL: {
10026                        // Revoke this as runtime permission to handle the case of
10027                        // a runtime permission being downgraded to an install one.
10028                        // Also in permission review mode we keep dangerous permissions
10029                        // for legacy apps
10030                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10031                            if (origPermissions.getRuntimePermissionState(
10032                                    bp.name, userId) != null) {
10033                                // Revoke the runtime permission and clear the flags.
10034                                origPermissions.revokeRuntimePermission(bp, userId);
10035                                origPermissions.updatePermissionFlags(bp, userId,
10036                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10037                                // If we revoked a permission permission, we have to write.
10038                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10039                                        changedRuntimePermissionUserIds, userId);
10040                            }
10041                        }
10042                        // Grant an install permission.
10043                        if (permissionsState.grantInstallPermission(bp) !=
10044                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10045                            changedInstallPermission = true;
10046                        }
10047                    } break;
10048
10049                    case GRANT_RUNTIME: {
10050                        // Grant previously granted runtime permissions.
10051                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10052                            PermissionState permissionState = origPermissions
10053                                    .getRuntimePermissionState(bp.name, userId);
10054                            int flags = permissionState != null
10055                                    ? permissionState.getFlags() : 0;
10056                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10057                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10058                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10059                                    // If we cannot put the permission as it was, we have to write.
10060                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10061                                            changedRuntimePermissionUserIds, userId);
10062                                }
10063                                // If the app supports runtime permissions no need for a review.
10064                                if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
10065                                        && appSupportsRuntimePermissions
10066                                        && (flags & PackageManager
10067                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10068                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10069                                    // Since we changed the flags, we have to write.
10070                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10071                                            changedRuntimePermissionUserIds, userId);
10072                                }
10073                            } else if ((mPermissionReviewRequired
10074                                        || Build.PERMISSIONS_REVIEW_REQUIRED)
10075                                    && !appSupportsRuntimePermissions) {
10076                                // For legacy apps that need a permission review, every new
10077                                // runtime permission is granted but it is pending a review.
10078                                // We also need to review only platform defined runtime
10079                                // permissions as these are the only ones the platform knows
10080                                // how to disable the API to simulate revocation as legacy
10081                                // apps don't expect to run with revoked permissions.
10082                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10083                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10084                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10085                                        // We changed the flags, hence have to write.
10086                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10087                                                changedRuntimePermissionUserIds, userId);
10088                                    }
10089                                }
10090                                if (permissionsState.grantRuntimePermission(bp, userId)
10091                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10092                                    // We changed the permission, hence have to write.
10093                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10094                                            changedRuntimePermissionUserIds, userId);
10095                                }
10096                            }
10097                            // Propagate the permission flags.
10098                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10099                        }
10100                    } break;
10101
10102                    case GRANT_UPGRADE: {
10103                        // Grant runtime permissions for a previously held install permission.
10104                        PermissionState permissionState = origPermissions
10105                                .getInstallPermissionState(bp.name);
10106                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10107
10108                        if (origPermissions.revokeInstallPermission(bp)
10109                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10110                            // We will be transferring the permission flags, so clear them.
10111                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10112                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10113                            changedInstallPermission = true;
10114                        }
10115
10116                        // If the permission is not to be promoted to runtime we ignore it and
10117                        // also its other flags as they are not applicable to install permissions.
10118                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10119                            for (int userId : currentUserIds) {
10120                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10121                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10122                                    // Transfer the permission flags.
10123                                    permissionsState.updatePermissionFlags(bp, userId,
10124                                            flags, flags);
10125                                    // If we granted the permission, we have to write.
10126                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10127                                            changedRuntimePermissionUserIds, userId);
10128                                }
10129                            }
10130                        }
10131                    } break;
10132
10133                    default: {
10134                        if (packageOfInterest == null
10135                                || packageOfInterest.equals(pkg.packageName)) {
10136                            Slog.w(TAG, "Not granting permission " + perm
10137                                    + " to package " + pkg.packageName
10138                                    + " because it was previously installed without");
10139                        }
10140                    } break;
10141                }
10142            } else {
10143                if (permissionsState.revokeInstallPermission(bp) !=
10144                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10145                    // Also drop the permission flags.
10146                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10147                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10148                    changedInstallPermission = true;
10149                    Slog.i(TAG, "Un-granting permission " + perm
10150                            + " from package " + pkg.packageName
10151                            + " (protectionLevel=" + bp.protectionLevel
10152                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10153                            + ")");
10154                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10155                    // Don't print warning for app op permissions, since it is fine for them
10156                    // not to be granted, there is a UI for the user to decide.
10157                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10158                        Slog.w(TAG, "Not granting permission " + perm
10159                                + " to package " + pkg.packageName
10160                                + " (protectionLevel=" + bp.protectionLevel
10161                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10162                                + ")");
10163                    }
10164                }
10165            }
10166        }
10167
10168        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10169                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10170            // This is the first that we have heard about this package, so the
10171            // permissions we have now selected are fixed until explicitly
10172            // changed.
10173            ps.installPermissionsFixed = true;
10174        }
10175
10176        // Persist the runtime permissions state for users with changes. If permissions
10177        // were revoked because no app in the shared user declares them we have to
10178        // write synchronously to avoid losing runtime permissions state.
10179        for (int userId : changedRuntimePermissionUserIds) {
10180            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10181        }
10182
10183        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10184    }
10185
10186    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10187        boolean allowed = false;
10188        final int NP = PackageParser.NEW_PERMISSIONS.length;
10189        for (int ip=0; ip<NP; ip++) {
10190            final PackageParser.NewPermissionInfo npi
10191                    = PackageParser.NEW_PERMISSIONS[ip];
10192            if (npi.name.equals(perm)
10193                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10194                allowed = true;
10195                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10196                        + pkg.packageName);
10197                break;
10198            }
10199        }
10200        return allowed;
10201    }
10202
10203    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10204            BasePermission bp, PermissionsState origPermissions) {
10205        boolean allowed;
10206        allowed = (compareSignatures(
10207                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10208                        == PackageManager.SIGNATURE_MATCH)
10209                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10210                        == PackageManager.SIGNATURE_MATCH);
10211        if (!allowed && (bp.protectionLevel
10212                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10213            if (isSystemApp(pkg)) {
10214                // For updated system applications, a system permission
10215                // is granted only if it had been defined by the original application.
10216                if (pkg.isUpdatedSystemApp()) {
10217                    final PackageSetting sysPs = mSettings
10218                            .getDisabledSystemPkgLPr(pkg.packageName);
10219                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10220                        // If the original was granted this permission, we take
10221                        // that grant decision as read and propagate it to the
10222                        // update.
10223                        if (sysPs.isPrivileged()) {
10224                            allowed = true;
10225                        }
10226                    } else {
10227                        // The system apk may have been updated with an older
10228                        // version of the one on the data partition, but which
10229                        // granted a new system permission that it didn't have
10230                        // before.  In this case we do want to allow the app to
10231                        // now get the new permission if the ancestral apk is
10232                        // privileged to get it.
10233                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10234                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10235                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10236                                    allowed = true;
10237                                    break;
10238                                }
10239                            }
10240                        }
10241                        // Also if a privileged parent package on the system image or any of
10242                        // its children requested a privileged permission, the updated child
10243                        // packages can also get the permission.
10244                        if (pkg.parentPackage != null) {
10245                            final PackageSetting disabledSysParentPs = mSettings
10246                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10247                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10248                                    && disabledSysParentPs.isPrivileged()) {
10249                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10250                                    allowed = true;
10251                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10252                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10253                                    for (int i = 0; i < count; i++) {
10254                                        PackageParser.Package disabledSysChildPkg =
10255                                                disabledSysParentPs.pkg.childPackages.get(i);
10256                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10257                                                perm)) {
10258                                            allowed = true;
10259                                            break;
10260                                        }
10261                                    }
10262                                }
10263                            }
10264                        }
10265                    }
10266                } else {
10267                    allowed = isPrivilegedApp(pkg);
10268                }
10269            }
10270        }
10271        if (!allowed) {
10272            if (!allowed && (bp.protectionLevel
10273                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10274                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10275                // If this was a previously normal/dangerous permission that got moved
10276                // to a system permission as part of the runtime permission redesign, then
10277                // we still want to blindly grant it to old apps.
10278                allowed = true;
10279            }
10280            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10281                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10282                // If this permission is to be granted to the system installer and
10283                // this app is an installer, then it gets the permission.
10284                allowed = true;
10285            }
10286            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10287                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10288                // If this permission is to be granted to the system verifier and
10289                // this app is a verifier, then it gets the permission.
10290                allowed = true;
10291            }
10292            if (!allowed && (bp.protectionLevel
10293                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10294                    && isSystemApp(pkg)) {
10295                // Any pre-installed system app is allowed to get this permission.
10296                allowed = true;
10297            }
10298            if (!allowed && (bp.protectionLevel
10299                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10300                // For development permissions, a development permission
10301                // is granted only if it was already granted.
10302                allowed = origPermissions.hasInstallPermission(perm);
10303            }
10304            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10305                    && pkg.packageName.equals(mSetupWizardPackage)) {
10306                // If this permission is to be granted to the system setup wizard and
10307                // this app is a setup wizard, then it gets the permission.
10308                allowed = true;
10309            }
10310        }
10311        return allowed;
10312    }
10313
10314    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10315        final int permCount = pkg.requestedPermissions.size();
10316        for (int j = 0; j < permCount; j++) {
10317            String requestedPermission = pkg.requestedPermissions.get(j);
10318            if (permission.equals(requestedPermission)) {
10319                return true;
10320            }
10321        }
10322        return false;
10323    }
10324
10325    final class ActivityIntentResolver
10326            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10327        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10328                boolean defaultOnly, int userId) {
10329            if (!sUserManager.exists(userId)) return null;
10330            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10331            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10332        }
10333
10334        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10335                int userId) {
10336            if (!sUserManager.exists(userId)) return null;
10337            mFlags = flags;
10338            return super.queryIntent(intent, resolvedType,
10339                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10340        }
10341
10342        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10343                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10344            if (!sUserManager.exists(userId)) return null;
10345            if (packageActivities == null) {
10346                return null;
10347            }
10348            mFlags = flags;
10349            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10350            final int N = packageActivities.size();
10351            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10352                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10353
10354            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10355            for (int i = 0; i < N; ++i) {
10356                intentFilters = packageActivities.get(i).intents;
10357                if (intentFilters != null && intentFilters.size() > 0) {
10358                    PackageParser.ActivityIntentInfo[] array =
10359                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10360                    intentFilters.toArray(array);
10361                    listCut.add(array);
10362                }
10363            }
10364            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10365        }
10366
10367        /**
10368         * Finds a privileged activity that matches the specified activity names.
10369         */
10370        private PackageParser.Activity findMatchingActivity(
10371                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10372            for (PackageParser.Activity sysActivity : activityList) {
10373                if (sysActivity.info.name.equals(activityInfo.name)) {
10374                    return sysActivity;
10375                }
10376                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10377                    return sysActivity;
10378                }
10379                if (sysActivity.info.targetActivity != null) {
10380                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10381                        return sysActivity;
10382                    }
10383                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10384                        return sysActivity;
10385                    }
10386                }
10387            }
10388            return null;
10389        }
10390
10391        public class IterGenerator<E> {
10392            public Iterator<E> generate(ActivityIntentInfo info) {
10393                return null;
10394            }
10395        }
10396
10397        public class ActionIterGenerator extends IterGenerator<String> {
10398            @Override
10399            public Iterator<String> generate(ActivityIntentInfo info) {
10400                return info.actionsIterator();
10401            }
10402        }
10403
10404        public class CategoriesIterGenerator extends IterGenerator<String> {
10405            @Override
10406            public Iterator<String> generate(ActivityIntentInfo info) {
10407                return info.categoriesIterator();
10408            }
10409        }
10410
10411        public class SchemesIterGenerator extends IterGenerator<String> {
10412            @Override
10413            public Iterator<String> generate(ActivityIntentInfo info) {
10414                return info.schemesIterator();
10415            }
10416        }
10417
10418        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10419            @Override
10420            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10421                return info.authoritiesIterator();
10422            }
10423        }
10424
10425        /**
10426         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10427         * MODIFIED. Do not pass in a list that should not be changed.
10428         */
10429        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10430                IterGenerator<T> generator, Iterator<T> searchIterator) {
10431            // loop through the set of actions; every one must be found in the intent filter
10432            while (searchIterator.hasNext()) {
10433                // we must have at least one filter in the list to consider a match
10434                if (intentList.size() == 0) {
10435                    break;
10436                }
10437
10438                final T searchAction = searchIterator.next();
10439
10440                // loop through the set of intent filters
10441                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10442                while (intentIter.hasNext()) {
10443                    final ActivityIntentInfo intentInfo = intentIter.next();
10444                    boolean selectionFound = false;
10445
10446                    // loop through the intent filter's selection criteria; at least one
10447                    // of them must match the searched criteria
10448                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10449                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10450                        final T intentSelection = intentSelectionIter.next();
10451                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10452                            selectionFound = true;
10453                            break;
10454                        }
10455                    }
10456
10457                    // the selection criteria wasn't found in this filter's set; this filter
10458                    // is not a potential match
10459                    if (!selectionFound) {
10460                        intentIter.remove();
10461                    }
10462                }
10463            }
10464        }
10465
10466        private boolean isProtectedAction(ActivityIntentInfo filter) {
10467            final Iterator<String> actionsIter = filter.actionsIterator();
10468            while (actionsIter != null && actionsIter.hasNext()) {
10469                final String filterAction = actionsIter.next();
10470                if (PROTECTED_ACTIONS.contains(filterAction)) {
10471                    return true;
10472                }
10473            }
10474            return false;
10475        }
10476
10477        /**
10478         * Adjusts the priority of the given intent filter according to policy.
10479         * <p>
10480         * <ul>
10481         * <li>The priority for non privileged applications is capped to '0'</li>
10482         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10483         * <li>The priority for unbundled updates to privileged applications is capped to the
10484         *      priority defined on the system partition</li>
10485         * </ul>
10486         * <p>
10487         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10488         * allowed to obtain any priority on any action.
10489         */
10490        private void adjustPriority(
10491                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10492            // nothing to do; priority is fine as-is
10493            if (intent.getPriority() <= 0) {
10494                return;
10495            }
10496
10497            final ActivityInfo activityInfo = intent.activity.info;
10498            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10499
10500            final boolean privilegedApp =
10501                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10502            if (!privilegedApp) {
10503                // non-privileged applications can never define a priority >0
10504                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10505                        + " package: " + applicationInfo.packageName
10506                        + " activity: " + intent.activity.className
10507                        + " origPrio: " + intent.getPriority());
10508                intent.setPriority(0);
10509                return;
10510            }
10511
10512            if (systemActivities == null) {
10513                // the system package is not disabled; we're parsing the system partition
10514                if (isProtectedAction(intent)) {
10515                    if (mDeferProtectedFilters) {
10516                        // We can't deal with these just yet. No component should ever obtain a
10517                        // >0 priority for a protected actions, with ONE exception -- the setup
10518                        // wizard. The setup wizard, however, cannot be known until we're able to
10519                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10520                        // until all intent filters have been processed. Chicken, meet egg.
10521                        // Let the filter temporarily have a high priority and rectify the
10522                        // priorities after all system packages have been scanned.
10523                        mProtectedFilters.add(intent);
10524                        if (DEBUG_FILTERS) {
10525                            Slog.i(TAG, "Protected action; save for later;"
10526                                    + " package: " + applicationInfo.packageName
10527                                    + " activity: " + intent.activity.className
10528                                    + " origPrio: " + intent.getPriority());
10529                        }
10530                        return;
10531                    } else {
10532                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10533                            Slog.i(TAG, "No setup wizard;"
10534                                + " All protected intents capped to priority 0");
10535                        }
10536                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10537                            if (DEBUG_FILTERS) {
10538                                Slog.i(TAG, "Found setup wizard;"
10539                                    + " allow priority " + intent.getPriority() + ";"
10540                                    + " package: " + intent.activity.info.packageName
10541                                    + " activity: " + intent.activity.className
10542                                    + " priority: " + intent.getPriority());
10543                            }
10544                            // setup wizard gets whatever it wants
10545                            return;
10546                        }
10547                        Slog.w(TAG, "Protected action; cap priority to 0;"
10548                                + " package: " + intent.activity.info.packageName
10549                                + " activity: " + intent.activity.className
10550                                + " origPrio: " + intent.getPriority());
10551                        intent.setPriority(0);
10552                        return;
10553                    }
10554                }
10555                // privileged apps on the system image get whatever priority they request
10556                return;
10557            }
10558
10559            // privileged app unbundled update ... try to find the same activity
10560            final PackageParser.Activity foundActivity =
10561                    findMatchingActivity(systemActivities, activityInfo);
10562            if (foundActivity == null) {
10563                // this is a new activity; it cannot obtain >0 priority
10564                if (DEBUG_FILTERS) {
10565                    Slog.i(TAG, "New activity; cap priority to 0;"
10566                            + " package: " + applicationInfo.packageName
10567                            + " activity: " + intent.activity.className
10568                            + " origPrio: " + intent.getPriority());
10569                }
10570                intent.setPriority(0);
10571                return;
10572            }
10573
10574            // found activity, now check for filter equivalence
10575
10576            // a shallow copy is enough; we modify the list, not its contents
10577            final List<ActivityIntentInfo> intentListCopy =
10578                    new ArrayList<>(foundActivity.intents);
10579            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10580
10581            // find matching action subsets
10582            final Iterator<String> actionsIterator = intent.actionsIterator();
10583            if (actionsIterator != null) {
10584                getIntentListSubset(
10585                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10586                if (intentListCopy.size() == 0) {
10587                    // no more intents to match; we're not equivalent
10588                    if (DEBUG_FILTERS) {
10589                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10590                                + " package: " + applicationInfo.packageName
10591                                + " activity: " + intent.activity.className
10592                                + " origPrio: " + intent.getPriority());
10593                    }
10594                    intent.setPriority(0);
10595                    return;
10596                }
10597            }
10598
10599            // find matching category subsets
10600            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10601            if (categoriesIterator != null) {
10602                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10603                        categoriesIterator);
10604                if (intentListCopy.size() == 0) {
10605                    // no more intents to match; we're not equivalent
10606                    if (DEBUG_FILTERS) {
10607                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10608                                + " package: " + applicationInfo.packageName
10609                                + " activity: " + intent.activity.className
10610                                + " origPrio: " + intent.getPriority());
10611                    }
10612                    intent.setPriority(0);
10613                    return;
10614                }
10615            }
10616
10617            // find matching schemes subsets
10618            final Iterator<String> schemesIterator = intent.schemesIterator();
10619            if (schemesIterator != null) {
10620                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10621                        schemesIterator);
10622                if (intentListCopy.size() == 0) {
10623                    // no more intents to match; we're not equivalent
10624                    if (DEBUG_FILTERS) {
10625                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10626                                + " package: " + applicationInfo.packageName
10627                                + " activity: " + intent.activity.className
10628                                + " origPrio: " + intent.getPriority());
10629                    }
10630                    intent.setPriority(0);
10631                    return;
10632                }
10633            }
10634
10635            // find matching authorities subsets
10636            final Iterator<IntentFilter.AuthorityEntry>
10637                    authoritiesIterator = intent.authoritiesIterator();
10638            if (authoritiesIterator != null) {
10639                getIntentListSubset(intentListCopy,
10640                        new AuthoritiesIterGenerator(),
10641                        authoritiesIterator);
10642                if (intentListCopy.size() == 0) {
10643                    // no more intents to match; we're not equivalent
10644                    if (DEBUG_FILTERS) {
10645                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10646                                + " package: " + applicationInfo.packageName
10647                                + " activity: " + intent.activity.className
10648                                + " origPrio: " + intent.getPriority());
10649                    }
10650                    intent.setPriority(0);
10651                    return;
10652                }
10653            }
10654
10655            // we found matching filter(s); app gets the max priority of all intents
10656            int cappedPriority = 0;
10657            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10658                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10659            }
10660            if (intent.getPriority() > cappedPriority) {
10661                if (DEBUG_FILTERS) {
10662                    Slog.i(TAG, "Found matching filter(s);"
10663                            + " cap priority to " + cappedPriority + ";"
10664                            + " package: " + applicationInfo.packageName
10665                            + " activity: " + intent.activity.className
10666                            + " origPrio: " + intent.getPriority());
10667                }
10668                intent.setPriority(cappedPriority);
10669                return;
10670            }
10671            // all this for nothing; the requested priority was <= what was on the system
10672        }
10673
10674        public final void addActivity(PackageParser.Activity a, String type) {
10675            mActivities.put(a.getComponentName(), a);
10676            if (DEBUG_SHOW_INFO)
10677                Log.v(
10678                TAG, "  " + type + " " +
10679                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10680            if (DEBUG_SHOW_INFO)
10681                Log.v(TAG, "    Class=" + a.info.name);
10682            final int NI = a.intents.size();
10683            for (int j=0; j<NI; j++) {
10684                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10685                if ("activity".equals(type)) {
10686                    final PackageSetting ps =
10687                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10688                    final List<PackageParser.Activity> systemActivities =
10689                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10690                    adjustPriority(systemActivities, intent);
10691                }
10692                if (DEBUG_SHOW_INFO) {
10693                    Log.v(TAG, "    IntentFilter:");
10694                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10695                }
10696                if (!intent.debugCheck()) {
10697                    Log.w(TAG, "==> For Activity " + a.info.name);
10698                }
10699                addFilter(intent);
10700            }
10701        }
10702
10703        public final void removeActivity(PackageParser.Activity a, String type) {
10704            mActivities.remove(a.getComponentName());
10705            if (DEBUG_SHOW_INFO) {
10706                Log.v(TAG, "  " + type + " "
10707                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10708                                : a.info.name) + ":");
10709                Log.v(TAG, "    Class=" + a.info.name);
10710            }
10711            final int NI = a.intents.size();
10712            for (int j=0; j<NI; j++) {
10713                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10714                if (DEBUG_SHOW_INFO) {
10715                    Log.v(TAG, "    IntentFilter:");
10716                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10717                }
10718                removeFilter(intent);
10719            }
10720        }
10721
10722        @Override
10723        protected boolean allowFilterResult(
10724                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10725            ActivityInfo filterAi = filter.activity.info;
10726            for (int i=dest.size()-1; i>=0; i--) {
10727                ActivityInfo destAi = dest.get(i).activityInfo;
10728                if (destAi.name == filterAi.name
10729                        && destAi.packageName == filterAi.packageName) {
10730                    return false;
10731                }
10732            }
10733            return true;
10734        }
10735
10736        @Override
10737        protected ActivityIntentInfo[] newArray(int size) {
10738            return new ActivityIntentInfo[size];
10739        }
10740
10741        @Override
10742        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10743            if (!sUserManager.exists(userId)) return true;
10744            PackageParser.Package p = filter.activity.owner;
10745            if (p != null) {
10746                PackageSetting ps = (PackageSetting)p.mExtras;
10747                if (ps != null) {
10748                    // System apps are never considered stopped for purposes of
10749                    // filtering, because there may be no way for the user to
10750                    // actually re-launch them.
10751                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10752                            && ps.getStopped(userId);
10753                }
10754            }
10755            return false;
10756        }
10757
10758        @Override
10759        protected boolean isPackageForFilter(String packageName,
10760                PackageParser.ActivityIntentInfo info) {
10761            return packageName.equals(info.activity.owner.packageName);
10762        }
10763
10764        @Override
10765        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10766                int match, int userId) {
10767            if (!sUserManager.exists(userId)) return null;
10768            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10769                return null;
10770            }
10771            final PackageParser.Activity activity = info.activity;
10772            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10773            if (ps == null) {
10774                return null;
10775            }
10776            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10777                    ps.readUserState(userId), userId);
10778            if (ai == null) {
10779                return null;
10780            }
10781            final ResolveInfo res = new ResolveInfo();
10782            res.activityInfo = ai;
10783            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10784                res.filter = info;
10785            }
10786            if (info != null) {
10787                res.handleAllWebDataURI = info.handleAllWebDataURI();
10788            }
10789            res.priority = info.getPriority();
10790            res.preferredOrder = activity.owner.mPreferredOrder;
10791            //System.out.println("Result: " + res.activityInfo.className +
10792            //                   " = " + res.priority);
10793            res.match = match;
10794            res.isDefault = info.hasDefault;
10795            res.labelRes = info.labelRes;
10796            res.nonLocalizedLabel = info.nonLocalizedLabel;
10797            if (userNeedsBadging(userId)) {
10798                res.noResourceId = true;
10799            } else {
10800                res.icon = info.icon;
10801            }
10802            res.iconResourceId = info.icon;
10803            res.system = res.activityInfo.applicationInfo.isSystemApp();
10804            return res;
10805        }
10806
10807        @Override
10808        protected void sortResults(List<ResolveInfo> results) {
10809            Collections.sort(results, mResolvePrioritySorter);
10810        }
10811
10812        @Override
10813        protected void dumpFilter(PrintWriter out, String prefix,
10814                PackageParser.ActivityIntentInfo filter) {
10815            out.print(prefix); out.print(
10816                    Integer.toHexString(System.identityHashCode(filter.activity)));
10817                    out.print(' ');
10818                    filter.activity.printComponentShortName(out);
10819                    out.print(" filter ");
10820                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10821        }
10822
10823        @Override
10824        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10825            return filter.activity;
10826        }
10827
10828        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10829            PackageParser.Activity activity = (PackageParser.Activity)label;
10830            out.print(prefix); out.print(
10831                    Integer.toHexString(System.identityHashCode(activity)));
10832                    out.print(' ');
10833                    activity.printComponentShortName(out);
10834            if (count > 1) {
10835                out.print(" ("); out.print(count); out.print(" filters)");
10836            }
10837            out.println();
10838        }
10839
10840        // Keys are String (activity class name), values are Activity.
10841        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10842                = new ArrayMap<ComponentName, PackageParser.Activity>();
10843        private int mFlags;
10844    }
10845
10846    private final class ServiceIntentResolver
10847            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10848        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10849                boolean defaultOnly, int userId) {
10850            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10851            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10852        }
10853
10854        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10855                int userId) {
10856            if (!sUserManager.exists(userId)) return null;
10857            mFlags = flags;
10858            return super.queryIntent(intent, resolvedType,
10859                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10860        }
10861
10862        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10863                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10864            if (!sUserManager.exists(userId)) return null;
10865            if (packageServices == null) {
10866                return null;
10867            }
10868            mFlags = flags;
10869            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10870            final int N = packageServices.size();
10871            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10872                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10873
10874            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10875            for (int i = 0; i < N; ++i) {
10876                intentFilters = packageServices.get(i).intents;
10877                if (intentFilters != null && intentFilters.size() > 0) {
10878                    PackageParser.ServiceIntentInfo[] array =
10879                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10880                    intentFilters.toArray(array);
10881                    listCut.add(array);
10882                }
10883            }
10884            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10885        }
10886
10887        public final void addService(PackageParser.Service s) {
10888            mServices.put(s.getComponentName(), s);
10889            if (DEBUG_SHOW_INFO) {
10890                Log.v(TAG, "  "
10891                        + (s.info.nonLocalizedLabel != null
10892                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10893                Log.v(TAG, "    Class=" + s.info.name);
10894            }
10895            final int NI = s.intents.size();
10896            int j;
10897            for (j=0; j<NI; j++) {
10898                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10899                if (DEBUG_SHOW_INFO) {
10900                    Log.v(TAG, "    IntentFilter:");
10901                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10902                }
10903                if (!intent.debugCheck()) {
10904                    Log.w(TAG, "==> For Service " + s.info.name);
10905                }
10906                addFilter(intent);
10907            }
10908        }
10909
10910        public final void removeService(PackageParser.Service s) {
10911            mServices.remove(s.getComponentName());
10912            if (DEBUG_SHOW_INFO) {
10913                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10914                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10915                Log.v(TAG, "    Class=" + s.info.name);
10916            }
10917            final int NI = s.intents.size();
10918            int j;
10919            for (j=0; j<NI; j++) {
10920                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10921                if (DEBUG_SHOW_INFO) {
10922                    Log.v(TAG, "    IntentFilter:");
10923                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10924                }
10925                removeFilter(intent);
10926            }
10927        }
10928
10929        @Override
10930        protected boolean allowFilterResult(
10931                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10932            ServiceInfo filterSi = filter.service.info;
10933            for (int i=dest.size()-1; i>=0; i--) {
10934                ServiceInfo destAi = dest.get(i).serviceInfo;
10935                if (destAi.name == filterSi.name
10936                        && destAi.packageName == filterSi.packageName) {
10937                    return false;
10938                }
10939            }
10940            return true;
10941        }
10942
10943        @Override
10944        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10945            return new PackageParser.ServiceIntentInfo[size];
10946        }
10947
10948        @Override
10949        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10950            if (!sUserManager.exists(userId)) return true;
10951            PackageParser.Package p = filter.service.owner;
10952            if (p != null) {
10953                PackageSetting ps = (PackageSetting)p.mExtras;
10954                if (ps != null) {
10955                    // System apps are never considered stopped for purposes of
10956                    // filtering, because there may be no way for the user to
10957                    // actually re-launch them.
10958                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10959                            && ps.getStopped(userId);
10960                }
10961            }
10962            return false;
10963        }
10964
10965        @Override
10966        protected boolean isPackageForFilter(String packageName,
10967                PackageParser.ServiceIntentInfo info) {
10968            return packageName.equals(info.service.owner.packageName);
10969        }
10970
10971        @Override
10972        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10973                int match, int userId) {
10974            if (!sUserManager.exists(userId)) return null;
10975            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10976            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10977                return null;
10978            }
10979            final PackageParser.Service service = info.service;
10980            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10981            if (ps == null) {
10982                return null;
10983            }
10984            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10985                    ps.readUserState(userId), userId);
10986            if (si == null) {
10987                return null;
10988            }
10989            final ResolveInfo res = new ResolveInfo();
10990            res.serviceInfo = si;
10991            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10992                res.filter = filter;
10993            }
10994            res.priority = info.getPriority();
10995            res.preferredOrder = service.owner.mPreferredOrder;
10996            res.match = match;
10997            res.isDefault = info.hasDefault;
10998            res.labelRes = info.labelRes;
10999            res.nonLocalizedLabel = info.nonLocalizedLabel;
11000            res.icon = info.icon;
11001            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11002            return res;
11003        }
11004
11005        @Override
11006        protected void sortResults(List<ResolveInfo> results) {
11007            Collections.sort(results, mResolvePrioritySorter);
11008        }
11009
11010        @Override
11011        protected void dumpFilter(PrintWriter out, String prefix,
11012                PackageParser.ServiceIntentInfo filter) {
11013            out.print(prefix); out.print(
11014                    Integer.toHexString(System.identityHashCode(filter.service)));
11015                    out.print(' ');
11016                    filter.service.printComponentShortName(out);
11017                    out.print(" filter ");
11018                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11019        }
11020
11021        @Override
11022        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11023            return filter.service;
11024        }
11025
11026        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11027            PackageParser.Service service = (PackageParser.Service)label;
11028            out.print(prefix); out.print(
11029                    Integer.toHexString(System.identityHashCode(service)));
11030                    out.print(' ');
11031                    service.printComponentShortName(out);
11032            if (count > 1) {
11033                out.print(" ("); out.print(count); out.print(" filters)");
11034            }
11035            out.println();
11036        }
11037
11038//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11039//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11040//            final List<ResolveInfo> retList = Lists.newArrayList();
11041//            while (i.hasNext()) {
11042//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11043//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11044//                    retList.add(resolveInfo);
11045//                }
11046//            }
11047//            return retList;
11048//        }
11049
11050        // Keys are String (activity class name), values are Activity.
11051        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11052                = new ArrayMap<ComponentName, PackageParser.Service>();
11053        private int mFlags;
11054    };
11055
11056    private final class ProviderIntentResolver
11057            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11058        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11059                boolean defaultOnly, int userId) {
11060            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11061            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11062        }
11063
11064        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11065                int userId) {
11066            if (!sUserManager.exists(userId))
11067                return null;
11068            mFlags = flags;
11069            return super.queryIntent(intent, resolvedType,
11070                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11071        }
11072
11073        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11074                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11075            if (!sUserManager.exists(userId))
11076                return null;
11077            if (packageProviders == null) {
11078                return null;
11079            }
11080            mFlags = flags;
11081            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11082            final int N = packageProviders.size();
11083            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11084                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11085
11086            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11087            for (int i = 0; i < N; ++i) {
11088                intentFilters = packageProviders.get(i).intents;
11089                if (intentFilters != null && intentFilters.size() > 0) {
11090                    PackageParser.ProviderIntentInfo[] array =
11091                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11092                    intentFilters.toArray(array);
11093                    listCut.add(array);
11094                }
11095            }
11096            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11097        }
11098
11099        public final void addProvider(PackageParser.Provider p) {
11100            if (mProviders.containsKey(p.getComponentName())) {
11101                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11102                return;
11103            }
11104
11105            mProviders.put(p.getComponentName(), p);
11106            if (DEBUG_SHOW_INFO) {
11107                Log.v(TAG, "  "
11108                        + (p.info.nonLocalizedLabel != null
11109                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11110                Log.v(TAG, "    Class=" + p.info.name);
11111            }
11112            final int NI = p.intents.size();
11113            int j;
11114            for (j = 0; j < NI; j++) {
11115                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11116                if (DEBUG_SHOW_INFO) {
11117                    Log.v(TAG, "    IntentFilter:");
11118                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11119                }
11120                if (!intent.debugCheck()) {
11121                    Log.w(TAG, "==> For Provider " + p.info.name);
11122                }
11123                addFilter(intent);
11124            }
11125        }
11126
11127        public final void removeProvider(PackageParser.Provider p) {
11128            mProviders.remove(p.getComponentName());
11129            if (DEBUG_SHOW_INFO) {
11130                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11131                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11132                Log.v(TAG, "    Class=" + p.info.name);
11133            }
11134            final int NI = p.intents.size();
11135            int j;
11136            for (j = 0; j < NI; j++) {
11137                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11138                if (DEBUG_SHOW_INFO) {
11139                    Log.v(TAG, "    IntentFilter:");
11140                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11141                }
11142                removeFilter(intent);
11143            }
11144        }
11145
11146        @Override
11147        protected boolean allowFilterResult(
11148                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11149            ProviderInfo filterPi = filter.provider.info;
11150            for (int i = dest.size() - 1; i >= 0; i--) {
11151                ProviderInfo destPi = dest.get(i).providerInfo;
11152                if (destPi.name == filterPi.name
11153                        && destPi.packageName == filterPi.packageName) {
11154                    return false;
11155                }
11156            }
11157            return true;
11158        }
11159
11160        @Override
11161        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11162            return new PackageParser.ProviderIntentInfo[size];
11163        }
11164
11165        @Override
11166        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11167            if (!sUserManager.exists(userId))
11168                return true;
11169            PackageParser.Package p = filter.provider.owner;
11170            if (p != null) {
11171                PackageSetting ps = (PackageSetting) p.mExtras;
11172                if (ps != null) {
11173                    // System apps are never considered stopped for purposes of
11174                    // filtering, because there may be no way for the user to
11175                    // actually re-launch them.
11176                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11177                            && ps.getStopped(userId);
11178                }
11179            }
11180            return false;
11181        }
11182
11183        @Override
11184        protected boolean isPackageForFilter(String packageName,
11185                PackageParser.ProviderIntentInfo info) {
11186            return packageName.equals(info.provider.owner.packageName);
11187        }
11188
11189        @Override
11190        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11191                int match, int userId) {
11192            if (!sUserManager.exists(userId))
11193                return null;
11194            final PackageParser.ProviderIntentInfo info = filter;
11195            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11196                return null;
11197            }
11198            final PackageParser.Provider provider = info.provider;
11199            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11200            if (ps == null) {
11201                return null;
11202            }
11203            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11204                    ps.readUserState(userId), userId);
11205            if (pi == null) {
11206                return null;
11207            }
11208            final ResolveInfo res = new ResolveInfo();
11209            res.providerInfo = pi;
11210            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11211                res.filter = filter;
11212            }
11213            res.priority = info.getPriority();
11214            res.preferredOrder = provider.owner.mPreferredOrder;
11215            res.match = match;
11216            res.isDefault = info.hasDefault;
11217            res.labelRes = info.labelRes;
11218            res.nonLocalizedLabel = info.nonLocalizedLabel;
11219            res.icon = info.icon;
11220            res.system = res.providerInfo.applicationInfo.isSystemApp();
11221            return res;
11222        }
11223
11224        @Override
11225        protected void sortResults(List<ResolveInfo> results) {
11226            Collections.sort(results, mResolvePrioritySorter);
11227        }
11228
11229        @Override
11230        protected void dumpFilter(PrintWriter out, String prefix,
11231                PackageParser.ProviderIntentInfo filter) {
11232            out.print(prefix);
11233            out.print(
11234                    Integer.toHexString(System.identityHashCode(filter.provider)));
11235            out.print(' ');
11236            filter.provider.printComponentShortName(out);
11237            out.print(" filter ");
11238            out.println(Integer.toHexString(System.identityHashCode(filter)));
11239        }
11240
11241        @Override
11242        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11243            return filter.provider;
11244        }
11245
11246        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11247            PackageParser.Provider provider = (PackageParser.Provider)label;
11248            out.print(prefix); out.print(
11249                    Integer.toHexString(System.identityHashCode(provider)));
11250                    out.print(' ');
11251                    provider.printComponentShortName(out);
11252            if (count > 1) {
11253                out.print(" ("); out.print(count); out.print(" filters)");
11254            }
11255            out.println();
11256        }
11257
11258        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11259                = new ArrayMap<ComponentName, PackageParser.Provider>();
11260        private int mFlags;
11261    }
11262
11263    private static final class EphemeralIntentResolver
11264            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11265        /**
11266         * The result that has the highest defined order. Ordering applies on a
11267         * per-package basis. Mapping is from package name to Pair of order and
11268         * EphemeralResolveInfo.
11269         * <p>
11270         * NOTE: This is implemented as a field variable for convenience and efficiency.
11271         * By having a field variable, we're able to track filter ordering as soon as
11272         * a non-zero order is defined. Otherwise, multiple loops across the result set
11273         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11274         * this needs to be contained entirely within {@link #filterResults()}.
11275         */
11276        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11277
11278        @Override
11279        protected EphemeralResolveIntentInfo[] newArray(int size) {
11280            return new EphemeralResolveIntentInfo[size];
11281        }
11282
11283        @Override
11284        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11285            return true;
11286        }
11287
11288        @Override
11289        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11290                int userId) {
11291            if (!sUserManager.exists(userId)) {
11292                return null;
11293            }
11294            final String packageName = info.getEphemeralResolveInfo().getPackageName();
11295            final Integer order = info.getOrder();
11296            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11297                    mOrderResult.get(packageName);
11298            // ordering is enabled and this item's order isn't high enough
11299            if (lastOrderResult != null && lastOrderResult.first >= order) {
11300                return null;
11301            }
11302            final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11303            if (order > 0) {
11304                // non-zero order, enable ordering
11305                mOrderResult.put(packageName, new Pair<>(order, res));
11306            }
11307            return res;
11308        }
11309
11310        @Override
11311        protected void filterResults(List<EphemeralResolveInfo> results) {
11312            // only do work if ordering is enabled [most of the time it won't be]
11313            if (mOrderResult.size() == 0) {
11314                return;
11315            }
11316            int resultSize = results.size();
11317            for (int i = 0; i < resultSize; i++) {
11318                final EphemeralResolveInfo info = results.get(i);
11319                final String packageName = info.getPackageName();
11320                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11321                if (savedInfo == null) {
11322                    // package doesn't having ordering
11323                    continue;
11324                }
11325                if (savedInfo.second == info) {
11326                    // circled back to the highest ordered item; remove from order list
11327                    mOrderResult.remove(savedInfo);
11328                    if (mOrderResult.size() == 0) {
11329                        // no more ordered items
11330                        break;
11331                    }
11332                    continue;
11333                }
11334                // item has a worse order, remove it from the result list
11335                results.remove(i);
11336                resultSize--;
11337                i--;
11338            }
11339        }
11340    }
11341
11342    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11343            new Comparator<ResolveInfo>() {
11344        public int compare(ResolveInfo r1, ResolveInfo r2) {
11345            int v1 = r1.priority;
11346            int v2 = r2.priority;
11347            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11348            if (v1 != v2) {
11349                return (v1 > v2) ? -1 : 1;
11350            }
11351            v1 = r1.preferredOrder;
11352            v2 = r2.preferredOrder;
11353            if (v1 != v2) {
11354                return (v1 > v2) ? -1 : 1;
11355            }
11356            if (r1.isDefault != r2.isDefault) {
11357                return r1.isDefault ? -1 : 1;
11358            }
11359            v1 = r1.match;
11360            v2 = r2.match;
11361            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11362            if (v1 != v2) {
11363                return (v1 > v2) ? -1 : 1;
11364            }
11365            if (r1.system != r2.system) {
11366                return r1.system ? -1 : 1;
11367            }
11368            if (r1.activityInfo != null) {
11369                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11370            }
11371            if (r1.serviceInfo != null) {
11372                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11373            }
11374            if (r1.providerInfo != null) {
11375                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11376            }
11377            return 0;
11378        }
11379    };
11380
11381    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11382            new Comparator<ProviderInfo>() {
11383        public int compare(ProviderInfo p1, ProviderInfo p2) {
11384            final int v1 = p1.initOrder;
11385            final int v2 = p2.initOrder;
11386            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11387        }
11388    };
11389
11390    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11391            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11392            final int[] userIds) {
11393        mHandler.post(new Runnable() {
11394            @Override
11395            public void run() {
11396                try {
11397                    final IActivityManager am = ActivityManagerNative.getDefault();
11398                    if (am == null) return;
11399                    final int[] resolvedUserIds;
11400                    if (userIds == null) {
11401                        resolvedUserIds = am.getRunningUserIds();
11402                    } else {
11403                        resolvedUserIds = userIds;
11404                    }
11405                    for (int id : resolvedUserIds) {
11406                        final Intent intent = new Intent(action,
11407                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11408                        if (extras != null) {
11409                            intent.putExtras(extras);
11410                        }
11411                        if (targetPkg != null) {
11412                            intent.setPackage(targetPkg);
11413                        }
11414                        // Modify the UID when posting to other users
11415                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11416                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11417                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11418                            intent.putExtra(Intent.EXTRA_UID, uid);
11419                        }
11420                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11421                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11422                        if (DEBUG_BROADCASTS) {
11423                            RuntimeException here = new RuntimeException("here");
11424                            here.fillInStackTrace();
11425                            Slog.d(TAG, "Sending to user " + id + ": "
11426                                    + intent.toShortString(false, true, false, false)
11427                                    + " " + intent.getExtras(), here);
11428                        }
11429                        am.broadcastIntent(null, intent, null, finishedReceiver,
11430                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11431                                null, finishedReceiver != null, false, id);
11432                    }
11433                } catch (RemoteException ex) {
11434                }
11435            }
11436        });
11437    }
11438
11439    /**
11440     * Check if the external storage media is available. This is true if there
11441     * is a mounted external storage medium or if the external storage is
11442     * emulated.
11443     */
11444    private boolean isExternalMediaAvailable() {
11445        return mMediaMounted || Environment.isExternalStorageEmulated();
11446    }
11447
11448    @Override
11449    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11450        // writer
11451        synchronized (mPackages) {
11452            if (!isExternalMediaAvailable()) {
11453                // If the external storage is no longer mounted at this point,
11454                // the caller may not have been able to delete all of this
11455                // packages files and can not delete any more.  Bail.
11456                return null;
11457            }
11458            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11459            if (lastPackage != null) {
11460                pkgs.remove(lastPackage);
11461            }
11462            if (pkgs.size() > 0) {
11463                return pkgs.get(0);
11464            }
11465        }
11466        return null;
11467    }
11468
11469    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11470        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11471                userId, andCode ? 1 : 0, packageName);
11472        if (mSystemReady) {
11473            msg.sendToTarget();
11474        } else {
11475            if (mPostSystemReadyMessages == null) {
11476                mPostSystemReadyMessages = new ArrayList<>();
11477            }
11478            mPostSystemReadyMessages.add(msg);
11479        }
11480    }
11481
11482    void startCleaningPackages() {
11483        // reader
11484        if (!isExternalMediaAvailable()) {
11485            return;
11486        }
11487        synchronized (mPackages) {
11488            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11489                return;
11490            }
11491        }
11492        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11493        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11494        IActivityManager am = ActivityManagerNative.getDefault();
11495        if (am != null) {
11496            try {
11497                am.startService(null, intent, null, mContext.getOpPackageName(),
11498                        UserHandle.USER_SYSTEM);
11499            } catch (RemoteException e) {
11500            }
11501        }
11502    }
11503
11504    @Override
11505    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11506            int installFlags, String installerPackageName, int userId) {
11507        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11508
11509        final int callingUid = Binder.getCallingUid();
11510        enforceCrossUserPermission(callingUid, userId,
11511                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11512
11513        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11514            try {
11515                if (observer != null) {
11516                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11517                }
11518            } catch (RemoteException re) {
11519            }
11520            return;
11521        }
11522
11523        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11524            installFlags |= PackageManager.INSTALL_FROM_ADB;
11525
11526        } else {
11527            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11528            // about installerPackageName.
11529
11530            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11531            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11532        }
11533
11534        UserHandle user;
11535        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11536            user = UserHandle.ALL;
11537        } else {
11538            user = new UserHandle(userId);
11539        }
11540
11541        // Only system components can circumvent runtime permissions when installing.
11542        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11543                && mContext.checkCallingOrSelfPermission(Manifest.permission
11544                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11545            throw new SecurityException("You need the "
11546                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11547                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11548        }
11549
11550        final File originFile = new File(originPath);
11551        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11552
11553        final Message msg = mHandler.obtainMessage(INIT_COPY);
11554        final VerificationInfo verificationInfo = new VerificationInfo(
11555                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11556        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11557                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11558                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11559                null /*certificates*/);
11560        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11561        msg.obj = params;
11562
11563        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11564                System.identityHashCode(msg.obj));
11565        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11566                System.identityHashCode(msg.obj));
11567
11568        mHandler.sendMessage(msg);
11569    }
11570
11571    void installStage(String packageName, File stagedDir, String stagedCid,
11572            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11573            String installerPackageName, int installerUid, UserHandle user,
11574            Certificate[][] certificates) {
11575        if (DEBUG_EPHEMERAL) {
11576            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11577                Slog.d(TAG, "Ephemeral install of " + packageName);
11578            }
11579        }
11580        final VerificationInfo verificationInfo = new VerificationInfo(
11581                sessionParams.originatingUri, sessionParams.referrerUri,
11582                sessionParams.originatingUid, installerUid);
11583
11584        final OriginInfo origin;
11585        if (stagedDir != null) {
11586            origin = OriginInfo.fromStagedFile(stagedDir);
11587        } else {
11588            origin = OriginInfo.fromStagedContainer(stagedCid);
11589        }
11590
11591        final Message msg = mHandler.obtainMessage(INIT_COPY);
11592        final InstallParams params = new InstallParams(origin, null, observer,
11593                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11594                verificationInfo, user, sessionParams.abiOverride,
11595                sessionParams.grantedRuntimePermissions, certificates);
11596        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11597        msg.obj = params;
11598
11599        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11600                System.identityHashCode(msg.obj));
11601        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11602                System.identityHashCode(msg.obj));
11603
11604        mHandler.sendMessage(msg);
11605    }
11606
11607    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11608            int userId) {
11609        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11610        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11611    }
11612
11613    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11614            int appId, int userId) {
11615        Bundle extras = new Bundle(1);
11616        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11617
11618        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11619                packageName, extras, 0, null, null, new int[] {userId});
11620        try {
11621            IActivityManager am = ActivityManagerNative.getDefault();
11622            if (isSystem && am.isUserRunning(userId, 0)) {
11623                // The just-installed/enabled app is bundled on the system, so presumed
11624                // to be able to run automatically without needing an explicit launch.
11625                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11626                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11627                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11628                        .setPackage(packageName);
11629                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11630                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11631            }
11632        } catch (RemoteException e) {
11633            // shouldn't happen
11634            Slog.w(TAG, "Unable to bootstrap installed package", e);
11635        }
11636    }
11637
11638    @Override
11639    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11640            int userId) {
11641        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11642        PackageSetting pkgSetting;
11643        final int uid = Binder.getCallingUid();
11644        enforceCrossUserPermission(uid, userId,
11645                true /* requireFullPermission */, true /* checkShell */,
11646                "setApplicationHiddenSetting for user " + userId);
11647
11648        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11649            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11650            return false;
11651        }
11652
11653        long callingId = Binder.clearCallingIdentity();
11654        try {
11655            boolean sendAdded = false;
11656            boolean sendRemoved = false;
11657            // writer
11658            synchronized (mPackages) {
11659                pkgSetting = mSettings.mPackages.get(packageName);
11660                if (pkgSetting == null) {
11661                    return false;
11662                }
11663                // Do not allow "android" is being disabled
11664                if ("android".equals(packageName)) {
11665                    Slog.w(TAG, "Cannot hide package: android");
11666                    return false;
11667                }
11668                // Only allow protected packages to hide themselves.
11669                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11670                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11671                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11672                    return false;
11673                }
11674
11675                if (pkgSetting.getHidden(userId) != hidden) {
11676                    pkgSetting.setHidden(hidden, userId);
11677                    mSettings.writePackageRestrictionsLPr(userId);
11678                    if (hidden) {
11679                        sendRemoved = true;
11680                    } else {
11681                        sendAdded = true;
11682                    }
11683                }
11684            }
11685            if (sendAdded) {
11686                sendPackageAddedForUser(packageName, pkgSetting, userId);
11687                return true;
11688            }
11689            if (sendRemoved) {
11690                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11691                        "hiding pkg");
11692                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11693                return true;
11694            }
11695        } finally {
11696            Binder.restoreCallingIdentity(callingId);
11697        }
11698        return false;
11699    }
11700
11701    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11702            int userId) {
11703        final PackageRemovedInfo info = new PackageRemovedInfo();
11704        info.removedPackage = packageName;
11705        info.removedUsers = new int[] {userId};
11706        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11707        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11708    }
11709
11710    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11711        if (pkgList.length > 0) {
11712            Bundle extras = new Bundle(1);
11713            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11714
11715            sendPackageBroadcast(
11716                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11717                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11718                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11719                    new int[] {userId});
11720        }
11721    }
11722
11723    /**
11724     * Returns true if application is not found or there was an error. Otherwise it returns
11725     * the hidden state of the package for the given user.
11726     */
11727    @Override
11728    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11729        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11730        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11731                true /* requireFullPermission */, false /* checkShell */,
11732                "getApplicationHidden for user " + userId);
11733        PackageSetting pkgSetting;
11734        long callingId = Binder.clearCallingIdentity();
11735        try {
11736            // writer
11737            synchronized (mPackages) {
11738                pkgSetting = mSettings.mPackages.get(packageName);
11739                if (pkgSetting == null) {
11740                    return true;
11741                }
11742                return pkgSetting.getHidden(userId);
11743            }
11744        } finally {
11745            Binder.restoreCallingIdentity(callingId);
11746        }
11747    }
11748
11749    /**
11750     * @hide
11751     */
11752    @Override
11753    public int installExistingPackageAsUser(String packageName, int userId) {
11754        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11755                null);
11756        PackageSetting pkgSetting;
11757        final int uid = Binder.getCallingUid();
11758        enforceCrossUserPermission(uid, userId,
11759                true /* requireFullPermission */, true /* checkShell */,
11760                "installExistingPackage for user " + userId);
11761        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11762            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11763        }
11764
11765        long callingId = Binder.clearCallingIdentity();
11766        try {
11767            boolean installed = false;
11768
11769            // writer
11770            synchronized (mPackages) {
11771                pkgSetting = mSettings.mPackages.get(packageName);
11772                if (pkgSetting == null) {
11773                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11774                }
11775                if (!pkgSetting.getInstalled(userId)) {
11776                    pkgSetting.setInstalled(true, userId);
11777                    pkgSetting.setHidden(false, userId);
11778                    mSettings.writePackageRestrictionsLPr(userId);
11779                    installed = true;
11780                }
11781            }
11782
11783            if (installed) {
11784                if (pkgSetting.pkg != null) {
11785                    synchronized (mInstallLock) {
11786                        // We don't need to freeze for a brand new install
11787                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11788                    }
11789                }
11790                sendPackageAddedForUser(packageName, pkgSetting, userId);
11791            }
11792        } finally {
11793            Binder.restoreCallingIdentity(callingId);
11794        }
11795
11796        return PackageManager.INSTALL_SUCCEEDED;
11797    }
11798
11799    boolean isUserRestricted(int userId, String restrictionKey) {
11800        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11801        if (restrictions.getBoolean(restrictionKey, false)) {
11802            Log.w(TAG, "User is restricted: " + restrictionKey);
11803            return true;
11804        }
11805        return false;
11806    }
11807
11808    @Override
11809    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11810            int userId) {
11811        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11812        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11813                true /* requireFullPermission */, true /* checkShell */,
11814                "setPackagesSuspended for user " + userId);
11815
11816        if (ArrayUtils.isEmpty(packageNames)) {
11817            return packageNames;
11818        }
11819
11820        // List of package names for whom the suspended state has changed.
11821        List<String> changedPackages = new ArrayList<>(packageNames.length);
11822        // List of package names for whom the suspended state is not set as requested in this
11823        // method.
11824        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11825        long callingId = Binder.clearCallingIdentity();
11826        try {
11827            for (int i = 0; i < packageNames.length; i++) {
11828                String packageName = packageNames[i];
11829                boolean changed = false;
11830                final int appId;
11831                synchronized (mPackages) {
11832                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11833                    if (pkgSetting == null) {
11834                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11835                                + "\". Skipping suspending/un-suspending.");
11836                        unactionedPackages.add(packageName);
11837                        continue;
11838                    }
11839                    appId = pkgSetting.appId;
11840                    if (pkgSetting.getSuspended(userId) != suspended) {
11841                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11842                            unactionedPackages.add(packageName);
11843                            continue;
11844                        }
11845                        pkgSetting.setSuspended(suspended, userId);
11846                        mSettings.writePackageRestrictionsLPr(userId);
11847                        changed = true;
11848                        changedPackages.add(packageName);
11849                    }
11850                }
11851
11852                if (changed && suspended) {
11853                    killApplication(packageName, UserHandle.getUid(userId, appId),
11854                            "suspending package");
11855                }
11856            }
11857        } finally {
11858            Binder.restoreCallingIdentity(callingId);
11859        }
11860
11861        if (!changedPackages.isEmpty()) {
11862            sendPackagesSuspendedForUser(changedPackages.toArray(
11863                    new String[changedPackages.size()]), userId, suspended);
11864        }
11865
11866        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11867    }
11868
11869    @Override
11870    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11871        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11872                true /* requireFullPermission */, false /* checkShell */,
11873                "isPackageSuspendedForUser for user " + userId);
11874        synchronized (mPackages) {
11875            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11876            if (pkgSetting == null) {
11877                throw new IllegalArgumentException("Unknown target package: " + packageName);
11878            }
11879            return pkgSetting.getSuspended(userId);
11880        }
11881    }
11882
11883    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11884        if (isPackageDeviceAdmin(packageName, userId)) {
11885            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11886                    + "\": has an active device admin");
11887            return false;
11888        }
11889
11890        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11891        if (packageName.equals(activeLauncherPackageName)) {
11892            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11893                    + "\": contains the active launcher");
11894            return false;
11895        }
11896
11897        if (packageName.equals(mRequiredInstallerPackage)) {
11898            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11899                    + "\": required for package installation");
11900            return false;
11901        }
11902
11903        if (packageName.equals(mRequiredUninstallerPackage)) {
11904            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11905                    + "\": required for package uninstallation");
11906            return false;
11907        }
11908
11909        if (packageName.equals(mRequiredVerifierPackage)) {
11910            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11911                    + "\": required for package verification");
11912            return false;
11913        }
11914
11915        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11916            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11917                    + "\": is the default dialer");
11918            return false;
11919        }
11920
11921        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11922            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11923                    + "\": protected package");
11924            return false;
11925        }
11926
11927        return true;
11928    }
11929
11930    private String getActiveLauncherPackageName(int userId) {
11931        Intent intent = new Intent(Intent.ACTION_MAIN);
11932        intent.addCategory(Intent.CATEGORY_HOME);
11933        ResolveInfo resolveInfo = resolveIntent(
11934                intent,
11935                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11936                PackageManager.MATCH_DEFAULT_ONLY,
11937                userId);
11938
11939        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11940    }
11941
11942    private String getDefaultDialerPackageName(int userId) {
11943        synchronized (mPackages) {
11944            return mSettings.getDefaultDialerPackageNameLPw(userId);
11945        }
11946    }
11947
11948    @Override
11949    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11950        mContext.enforceCallingOrSelfPermission(
11951                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11952                "Only package verification agents can verify applications");
11953
11954        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11955        final PackageVerificationResponse response = new PackageVerificationResponse(
11956                verificationCode, Binder.getCallingUid());
11957        msg.arg1 = id;
11958        msg.obj = response;
11959        mHandler.sendMessage(msg);
11960    }
11961
11962    @Override
11963    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11964            long millisecondsToDelay) {
11965        mContext.enforceCallingOrSelfPermission(
11966                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11967                "Only package verification agents can extend verification timeouts");
11968
11969        final PackageVerificationState state = mPendingVerification.get(id);
11970        final PackageVerificationResponse response = new PackageVerificationResponse(
11971                verificationCodeAtTimeout, Binder.getCallingUid());
11972
11973        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11974            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11975        }
11976        if (millisecondsToDelay < 0) {
11977            millisecondsToDelay = 0;
11978        }
11979        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11980                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11981            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11982        }
11983
11984        if ((state != null) && !state.timeoutExtended()) {
11985            state.extendTimeout();
11986
11987            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11988            msg.arg1 = id;
11989            msg.obj = response;
11990            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11991        }
11992    }
11993
11994    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11995            int verificationCode, UserHandle user) {
11996        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11997        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11998        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11999        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12000        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12001
12002        mContext.sendBroadcastAsUser(intent, user,
12003                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12004    }
12005
12006    private ComponentName matchComponentForVerifier(String packageName,
12007            List<ResolveInfo> receivers) {
12008        ActivityInfo targetReceiver = null;
12009
12010        final int NR = receivers.size();
12011        for (int i = 0; i < NR; i++) {
12012            final ResolveInfo info = receivers.get(i);
12013            if (info.activityInfo == null) {
12014                continue;
12015            }
12016
12017            if (packageName.equals(info.activityInfo.packageName)) {
12018                targetReceiver = info.activityInfo;
12019                break;
12020            }
12021        }
12022
12023        if (targetReceiver == null) {
12024            return null;
12025        }
12026
12027        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12028    }
12029
12030    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12031            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12032        if (pkgInfo.verifiers.length == 0) {
12033            return null;
12034        }
12035
12036        final int N = pkgInfo.verifiers.length;
12037        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12038        for (int i = 0; i < N; i++) {
12039            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12040
12041            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12042                    receivers);
12043            if (comp == null) {
12044                continue;
12045            }
12046
12047            final int verifierUid = getUidForVerifier(verifierInfo);
12048            if (verifierUid == -1) {
12049                continue;
12050            }
12051
12052            if (DEBUG_VERIFY) {
12053                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12054                        + " with the correct signature");
12055            }
12056            sufficientVerifiers.add(comp);
12057            verificationState.addSufficientVerifier(verifierUid);
12058        }
12059
12060        return sufficientVerifiers;
12061    }
12062
12063    private int getUidForVerifier(VerifierInfo verifierInfo) {
12064        synchronized (mPackages) {
12065            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12066            if (pkg == null) {
12067                return -1;
12068            } else if (pkg.mSignatures.length != 1) {
12069                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12070                        + " has more than one signature; ignoring");
12071                return -1;
12072            }
12073
12074            /*
12075             * If the public key of the package's signature does not match
12076             * our expected public key, then this is a different package and
12077             * we should skip.
12078             */
12079
12080            final byte[] expectedPublicKey;
12081            try {
12082                final Signature verifierSig = pkg.mSignatures[0];
12083                final PublicKey publicKey = verifierSig.getPublicKey();
12084                expectedPublicKey = publicKey.getEncoded();
12085            } catch (CertificateException e) {
12086                return -1;
12087            }
12088
12089            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12090
12091            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12092                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12093                        + " does not have the expected public key; ignoring");
12094                return -1;
12095            }
12096
12097            return pkg.applicationInfo.uid;
12098        }
12099    }
12100
12101    @Override
12102    public void finishPackageInstall(int token, boolean didLaunch) {
12103        enforceSystemOrRoot("Only the system is allowed to finish installs");
12104
12105        if (DEBUG_INSTALL) {
12106            Slog.v(TAG, "BM finishing package install for " + token);
12107        }
12108        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12109
12110        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12111        mHandler.sendMessage(msg);
12112    }
12113
12114    /**
12115     * Get the verification agent timeout.
12116     *
12117     * @return verification timeout in milliseconds
12118     */
12119    private long getVerificationTimeout() {
12120        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12121                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12122                DEFAULT_VERIFICATION_TIMEOUT);
12123    }
12124
12125    /**
12126     * Get the default verification agent response code.
12127     *
12128     * @return default verification response code
12129     */
12130    private int getDefaultVerificationResponse() {
12131        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12132                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12133                DEFAULT_VERIFICATION_RESPONSE);
12134    }
12135
12136    /**
12137     * Check whether or not package verification has been enabled.
12138     *
12139     * @return true if verification should be performed
12140     */
12141    private boolean isVerificationEnabled(int userId, int installFlags) {
12142        if (!DEFAULT_VERIFY_ENABLE) {
12143            return false;
12144        }
12145        // Ephemeral apps don't get the full verification treatment
12146        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12147            if (DEBUG_EPHEMERAL) {
12148                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12149            }
12150            return false;
12151        }
12152
12153        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12154
12155        // Check if installing from ADB
12156        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12157            // Do not run verification in a test harness environment
12158            if (ActivityManager.isRunningInTestHarness()) {
12159                return false;
12160            }
12161            if (ensureVerifyAppsEnabled) {
12162                return true;
12163            }
12164            // Check if the developer does not want package verification for ADB installs
12165            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12166                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12167                return false;
12168            }
12169        }
12170
12171        if (ensureVerifyAppsEnabled) {
12172            return true;
12173        }
12174
12175        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12176                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12177    }
12178
12179    @Override
12180    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12181            throws RemoteException {
12182        mContext.enforceCallingOrSelfPermission(
12183                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12184                "Only intentfilter verification agents can verify applications");
12185
12186        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12187        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12188                Binder.getCallingUid(), verificationCode, failedDomains);
12189        msg.arg1 = id;
12190        msg.obj = response;
12191        mHandler.sendMessage(msg);
12192    }
12193
12194    @Override
12195    public int getIntentVerificationStatus(String packageName, int userId) {
12196        synchronized (mPackages) {
12197            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12198        }
12199    }
12200
12201    @Override
12202    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12203        mContext.enforceCallingOrSelfPermission(
12204                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12205
12206        boolean result = false;
12207        synchronized (mPackages) {
12208            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12209        }
12210        if (result) {
12211            scheduleWritePackageRestrictionsLocked(userId);
12212        }
12213        return result;
12214    }
12215
12216    @Override
12217    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12218            String packageName) {
12219        synchronized (mPackages) {
12220            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12221        }
12222    }
12223
12224    @Override
12225    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12226        if (TextUtils.isEmpty(packageName)) {
12227            return ParceledListSlice.emptyList();
12228        }
12229        synchronized (mPackages) {
12230            PackageParser.Package pkg = mPackages.get(packageName);
12231            if (pkg == null || pkg.activities == null) {
12232                return ParceledListSlice.emptyList();
12233            }
12234            final int count = pkg.activities.size();
12235            ArrayList<IntentFilter> result = new ArrayList<>();
12236            for (int n=0; n<count; n++) {
12237                PackageParser.Activity activity = pkg.activities.get(n);
12238                if (activity.intents != null && activity.intents.size() > 0) {
12239                    result.addAll(activity.intents);
12240                }
12241            }
12242            return new ParceledListSlice<>(result);
12243        }
12244    }
12245
12246    @Override
12247    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12248        mContext.enforceCallingOrSelfPermission(
12249                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12250
12251        synchronized (mPackages) {
12252            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12253            if (packageName != null) {
12254                result |= updateIntentVerificationStatus(packageName,
12255                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12256                        userId);
12257                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12258                        packageName, userId);
12259            }
12260            return result;
12261        }
12262    }
12263
12264    @Override
12265    public String getDefaultBrowserPackageName(int userId) {
12266        synchronized (mPackages) {
12267            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12268        }
12269    }
12270
12271    /**
12272     * Get the "allow unknown sources" setting.
12273     *
12274     * @return the current "allow unknown sources" setting
12275     */
12276    private int getUnknownSourcesSettings() {
12277        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12278                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12279                -1);
12280    }
12281
12282    @Override
12283    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12284        final int uid = Binder.getCallingUid();
12285        // writer
12286        synchronized (mPackages) {
12287            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12288            if (targetPackageSetting == null) {
12289                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12290            }
12291
12292            PackageSetting installerPackageSetting;
12293            if (installerPackageName != null) {
12294                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12295                if (installerPackageSetting == null) {
12296                    throw new IllegalArgumentException("Unknown installer package: "
12297                            + installerPackageName);
12298                }
12299            } else {
12300                installerPackageSetting = null;
12301            }
12302
12303            Signature[] callerSignature;
12304            Object obj = mSettings.getUserIdLPr(uid);
12305            if (obj != null) {
12306                if (obj instanceof SharedUserSetting) {
12307                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12308                } else if (obj instanceof PackageSetting) {
12309                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12310                } else {
12311                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12312                }
12313            } else {
12314                throw new SecurityException("Unknown calling UID: " + uid);
12315            }
12316
12317            // Verify: can't set installerPackageName to a package that is
12318            // not signed with the same cert as the caller.
12319            if (installerPackageSetting != null) {
12320                if (compareSignatures(callerSignature,
12321                        installerPackageSetting.signatures.mSignatures)
12322                        != PackageManager.SIGNATURE_MATCH) {
12323                    throw new SecurityException(
12324                            "Caller does not have same cert as new installer package "
12325                            + installerPackageName);
12326                }
12327            }
12328
12329            // Verify: if target already has an installer package, it must
12330            // be signed with the same cert as the caller.
12331            if (targetPackageSetting.installerPackageName != null) {
12332                PackageSetting setting = mSettings.mPackages.get(
12333                        targetPackageSetting.installerPackageName);
12334                // If the currently set package isn't valid, then it's always
12335                // okay to change it.
12336                if (setting != null) {
12337                    if (compareSignatures(callerSignature,
12338                            setting.signatures.mSignatures)
12339                            != PackageManager.SIGNATURE_MATCH) {
12340                        throw new SecurityException(
12341                                "Caller does not have same cert as old installer package "
12342                                + targetPackageSetting.installerPackageName);
12343                    }
12344                }
12345            }
12346
12347            // Okay!
12348            targetPackageSetting.installerPackageName = installerPackageName;
12349            if (installerPackageName != null) {
12350                mSettings.mInstallerPackages.add(installerPackageName);
12351            }
12352            scheduleWriteSettingsLocked();
12353        }
12354    }
12355
12356    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12357        // Queue up an async operation since the package installation may take a little while.
12358        mHandler.post(new Runnable() {
12359            public void run() {
12360                mHandler.removeCallbacks(this);
12361                 // Result object to be returned
12362                PackageInstalledInfo res = new PackageInstalledInfo();
12363                res.setReturnCode(currentStatus);
12364                res.uid = -1;
12365                res.pkg = null;
12366                res.removedInfo = null;
12367                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12368                    args.doPreInstall(res.returnCode);
12369                    synchronized (mInstallLock) {
12370                        installPackageTracedLI(args, res);
12371                    }
12372                    args.doPostInstall(res.returnCode, res.uid);
12373                }
12374
12375                // A restore should be performed at this point if (a) the install
12376                // succeeded, (b) the operation is not an update, and (c) the new
12377                // package has not opted out of backup participation.
12378                final boolean update = res.removedInfo != null
12379                        && res.removedInfo.removedPackage != null;
12380                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12381                boolean doRestore = !update
12382                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12383
12384                // Set up the post-install work request bookkeeping.  This will be used
12385                // and cleaned up by the post-install event handling regardless of whether
12386                // there's a restore pass performed.  Token values are >= 1.
12387                int token;
12388                if (mNextInstallToken < 0) mNextInstallToken = 1;
12389                token = mNextInstallToken++;
12390
12391                PostInstallData data = new PostInstallData(args, res);
12392                mRunningInstalls.put(token, data);
12393                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12394
12395                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12396                    // Pass responsibility to the Backup Manager.  It will perform a
12397                    // restore if appropriate, then pass responsibility back to the
12398                    // Package Manager to run the post-install observer callbacks
12399                    // and broadcasts.
12400                    IBackupManager bm = IBackupManager.Stub.asInterface(
12401                            ServiceManager.getService(Context.BACKUP_SERVICE));
12402                    if (bm != null) {
12403                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12404                                + " to BM for possible restore");
12405                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12406                        try {
12407                            // TODO: http://b/22388012
12408                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12409                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12410                            } else {
12411                                doRestore = false;
12412                            }
12413                        } catch (RemoteException e) {
12414                            // can't happen; the backup manager is local
12415                        } catch (Exception e) {
12416                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12417                            doRestore = false;
12418                        }
12419                    } else {
12420                        Slog.e(TAG, "Backup Manager not found!");
12421                        doRestore = false;
12422                    }
12423                }
12424
12425                if (!doRestore) {
12426                    // No restore possible, or the Backup Manager was mysteriously not
12427                    // available -- just fire the post-install work request directly.
12428                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12429
12430                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12431
12432                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12433                    mHandler.sendMessage(msg);
12434                }
12435            }
12436        });
12437    }
12438
12439    /**
12440     * Callback from PackageSettings whenever an app is first transitioned out of the
12441     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12442     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12443     * here whether the app is the target of an ongoing install, and only send the
12444     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12445     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12446     * handling.
12447     */
12448    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12449        // Serialize this with the rest of the install-process message chain.  In the
12450        // restore-at-install case, this Runnable will necessarily run before the
12451        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12452        // are coherent.  In the non-restore case, the app has already completed install
12453        // and been launched through some other means, so it is not in a problematic
12454        // state for observers to see the FIRST_LAUNCH signal.
12455        mHandler.post(new Runnable() {
12456            @Override
12457            public void run() {
12458                for (int i = 0; i < mRunningInstalls.size(); i++) {
12459                    final PostInstallData data = mRunningInstalls.valueAt(i);
12460                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12461                        continue;
12462                    }
12463                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12464                        // right package; but is it for the right user?
12465                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12466                            if (userId == data.res.newUsers[uIndex]) {
12467                                if (DEBUG_BACKUP) {
12468                                    Slog.i(TAG, "Package " + pkgName
12469                                            + " being restored so deferring FIRST_LAUNCH");
12470                                }
12471                                return;
12472                            }
12473                        }
12474                    }
12475                }
12476                // didn't find it, so not being restored
12477                if (DEBUG_BACKUP) {
12478                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12479                }
12480                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12481            }
12482        });
12483    }
12484
12485    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12486        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12487                installerPkg, null, userIds);
12488    }
12489
12490    private abstract class HandlerParams {
12491        private static final int MAX_RETRIES = 4;
12492
12493        /**
12494         * Number of times startCopy() has been attempted and had a non-fatal
12495         * error.
12496         */
12497        private int mRetries = 0;
12498
12499        /** User handle for the user requesting the information or installation. */
12500        private final UserHandle mUser;
12501        String traceMethod;
12502        int traceCookie;
12503
12504        HandlerParams(UserHandle user) {
12505            mUser = user;
12506        }
12507
12508        UserHandle getUser() {
12509            return mUser;
12510        }
12511
12512        HandlerParams setTraceMethod(String traceMethod) {
12513            this.traceMethod = traceMethod;
12514            return this;
12515        }
12516
12517        HandlerParams setTraceCookie(int traceCookie) {
12518            this.traceCookie = traceCookie;
12519            return this;
12520        }
12521
12522        final boolean startCopy() {
12523            boolean res;
12524            try {
12525                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12526
12527                if (++mRetries > MAX_RETRIES) {
12528                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12529                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12530                    handleServiceError();
12531                    return false;
12532                } else {
12533                    handleStartCopy();
12534                    res = true;
12535                }
12536            } catch (RemoteException e) {
12537                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12538                mHandler.sendEmptyMessage(MCS_RECONNECT);
12539                res = false;
12540            }
12541            handleReturnCode();
12542            return res;
12543        }
12544
12545        final void serviceError() {
12546            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12547            handleServiceError();
12548            handleReturnCode();
12549        }
12550
12551        abstract void handleStartCopy() throws RemoteException;
12552        abstract void handleServiceError();
12553        abstract void handleReturnCode();
12554    }
12555
12556    class MeasureParams extends HandlerParams {
12557        private final PackageStats mStats;
12558        private boolean mSuccess;
12559
12560        private final IPackageStatsObserver mObserver;
12561
12562        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12563            super(new UserHandle(stats.userHandle));
12564            mObserver = observer;
12565            mStats = stats;
12566        }
12567
12568        @Override
12569        public String toString() {
12570            return "MeasureParams{"
12571                + Integer.toHexString(System.identityHashCode(this))
12572                + " " + mStats.packageName + "}";
12573        }
12574
12575        @Override
12576        void handleStartCopy() throws RemoteException {
12577            synchronized (mInstallLock) {
12578                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12579            }
12580
12581            if (mSuccess) {
12582                boolean mounted = false;
12583                try {
12584                    final String status = Environment.getExternalStorageState();
12585                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12586                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12587                } catch (Exception e) {
12588                }
12589
12590                if (mounted) {
12591                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12592
12593                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12594                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12595
12596                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12597                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12598
12599                    // Always subtract cache size, since it's a subdirectory
12600                    mStats.externalDataSize -= mStats.externalCacheSize;
12601
12602                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12603                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12604
12605                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12606                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12607                }
12608            }
12609        }
12610
12611        @Override
12612        void handleReturnCode() {
12613            if (mObserver != null) {
12614                try {
12615                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12616                } catch (RemoteException e) {
12617                    Slog.i(TAG, "Observer no longer exists.");
12618                }
12619            }
12620        }
12621
12622        @Override
12623        void handleServiceError() {
12624            Slog.e(TAG, "Could not measure application " + mStats.packageName
12625                            + " external storage");
12626        }
12627    }
12628
12629    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12630            throws RemoteException {
12631        long result = 0;
12632        for (File path : paths) {
12633            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12634        }
12635        return result;
12636    }
12637
12638    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12639        for (File path : paths) {
12640            try {
12641                mcs.clearDirectory(path.getAbsolutePath());
12642            } catch (RemoteException e) {
12643            }
12644        }
12645    }
12646
12647    static class OriginInfo {
12648        /**
12649         * Location where install is coming from, before it has been
12650         * copied/renamed into place. This could be a single monolithic APK
12651         * file, or a cluster directory. This location may be untrusted.
12652         */
12653        final File file;
12654        final String cid;
12655
12656        /**
12657         * Flag indicating that {@link #file} or {@link #cid} has already been
12658         * staged, meaning downstream users don't need to defensively copy the
12659         * contents.
12660         */
12661        final boolean staged;
12662
12663        /**
12664         * Flag indicating that {@link #file} or {@link #cid} is an already
12665         * installed app that is being moved.
12666         */
12667        final boolean existing;
12668
12669        final String resolvedPath;
12670        final File resolvedFile;
12671
12672        static OriginInfo fromNothing() {
12673            return new OriginInfo(null, null, false, false);
12674        }
12675
12676        static OriginInfo fromUntrustedFile(File file) {
12677            return new OriginInfo(file, null, false, false);
12678        }
12679
12680        static OriginInfo fromExistingFile(File file) {
12681            return new OriginInfo(file, null, false, true);
12682        }
12683
12684        static OriginInfo fromStagedFile(File file) {
12685            return new OriginInfo(file, null, true, false);
12686        }
12687
12688        static OriginInfo fromStagedContainer(String cid) {
12689            return new OriginInfo(null, cid, true, false);
12690        }
12691
12692        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12693            this.file = file;
12694            this.cid = cid;
12695            this.staged = staged;
12696            this.existing = existing;
12697
12698            if (cid != null) {
12699                resolvedPath = PackageHelper.getSdDir(cid);
12700                resolvedFile = new File(resolvedPath);
12701            } else if (file != null) {
12702                resolvedPath = file.getAbsolutePath();
12703                resolvedFile = file;
12704            } else {
12705                resolvedPath = null;
12706                resolvedFile = null;
12707            }
12708        }
12709    }
12710
12711    static class MoveInfo {
12712        final int moveId;
12713        final String fromUuid;
12714        final String toUuid;
12715        final String packageName;
12716        final String dataAppName;
12717        final int appId;
12718        final String seinfo;
12719        final int targetSdkVersion;
12720
12721        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12722                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12723            this.moveId = moveId;
12724            this.fromUuid = fromUuid;
12725            this.toUuid = toUuid;
12726            this.packageName = packageName;
12727            this.dataAppName = dataAppName;
12728            this.appId = appId;
12729            this.seinfo = seinfo;
12730            this.targetSdkVersion = targetSdkVersion;
12731        }
12732    }
12733
12734    static class VerificationInfo {
12735        /** A constant used to indicate that a uid value is not present. */
12736        public static final int NO_UID = -1;
12737
12738        /** URI referencing where the package was downloaded from. */
12739        final Uri originatingUri;
12740
12741        /** HTTP referrer URI associated with the originatingURI. */
12742        final Uri referrer;
12743
12744        /** UID of the application that the install request originated from. */
12745        final int originatingUid;
12746
12747        /** UID of application requesting the install */
12748        final int installerUid;
12749
12750        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12751            this.originatingUri = originatingUri;
12752            this.referrer = referrer;
12753            this.originatingUid = originatingUid;
12754            this.installerUid = installerUid;
12755        }
12756    }
12757
12758    class InstallParams extends HandlerParams {
12759        final OriginInfo origin;
12760        final MoveInfo move;
12761        final IPackageInstallObserver2 observer;
12762        int installFlags;
12763        final String installerPackageName;
12764        final String volumeUuid;
12765        private InstallArgs mArgs;
12766        private int mRet;
12767        final String packageAbiOverride;
12768        final String[] grantedRuntimePermissions;
12769        final VerificationInfo verificationInfo;
12770        final Certificate[][] certificates;
12771
12772        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12773                int installFlags, String installerPackageName, String volumeUuid,
12774                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12775                String[] grantedPermissions, Certificate[][] certificates) {
12776            super(user);
12777            this.origin = origin;
12778            this.move = move;
12779            this.observer = observer;
12780            this.installFlags = installFlags;
12781            this.installerPackageName = installerPackageName;
12782            this.volumeUuid = volumeUuid;
12783            this.verificationInfo = verificationInfo;
12784            this.packageAbiOverride = packageAbiOverride;
12785            this.grantedRuntimePermissions = grantedPermissions;
12786            this.certificates = certificates;
12787        }
12788
12789        @Override
12790        public String toString() {
12791            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12792                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12793        }
12794
12795        private int installLocationPolicy(PackageInfoLite pkgLite) {
12796            String packageName = pkgLite.packageName;
12797            int installLocation = pkgLite.installLocation;
12798            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12799            // reader
12800            synchronized (mPackages) {
12801                // Currently installed package which the new package is attempting to replace or
12802                // null if no such package is installed.
12803                PackageParser.Package installedPkg = mPackages.get(packageName);
12804                // Package which currently owns the data which the new package will own if installed.
12805                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12806                // will be null whereas dataOwnerPkg will contain information about the package
12807                // which was uninstalled while keeping its data.
12808                PackageParser.Package dataOwnerPkg = installedPkg;
12809                if (dataOwnerPkg  == null) {
12810                    PackageSetting ps = mSettings.mPackages.get(packageName);
12811                    if (ps != null) {
12812                        dataOwnerPkg = ps.pkg;
12813                    }
12814                }
12815
12816                if (dataOwnerPkg != null) {
12817                    // If installed, the package will get access to data left on the device by its
12818                    // predecessor. As a security measure, this is permited only if this is not a
12819                    // version downgrade or if the predecessor package is marked as debuggable and
12820                    // a downgrade is explicitly requested.
12821                    //
12822                    // On debuggable platform builds, downgrades are permitted even for
12823                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12824                    // not offer security guarantees and thus it's OK to disable some security
12825                    // mechanisms to make debugging/testing easier on those builds. However, even on
12826                    // debuggable builds downgrades of packages are permitted only if requested via
12827                    // installFlags. This is because we aim to keep the behavior of debuggable
12828                    // platform builds as close as possible to the behavior of non-debuggable
12829                    // platform builds.
12830                    final boolean downgradeRequested =
12831                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12832                    final boolean packageDebuggable =
12833                                (dataOwnerPkg.applicationInfo.flags
12834                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12835                    final boolean downgradePermitted =
12836                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12837                    if (!downgradePermitted) {
12838                        try {
12839                            checkDowngrade(dataOwnerPkg, pkgLite);
12840                        } catch (PackageManagerException e) {
12841                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12842                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12843                        }
12844                    }
12845                }
12846
12847                if (installedPkg != null) {
12848                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12849                        // Check for updated system application.
12850                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12851                            if (onSd) {
12852                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12853                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12854                            }
12855                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12856                        } else {
12857                            if (onSd) {
12858                                // Install flag overrides everything.
12859                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12860                            }
12861                            // If current upgrade specifies particular preference
12862                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12863                                // Application explicitly specified internal.
12864                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12865                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12866                                // App explictly prefers external. Let policy decide
12867                            } else {
12868                                // Prefer previous location
12869                                if (isExternal(installedPkg)) {
12870                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12871                                }
12872                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12873                            }
12874                        }
12875                    } else {
12876                        // Invalid install. Return error code
12877                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12878                    }
12879                }
12880            }
12881            // All the special cases have been taken care of.
12882            // Return result based on recommended install location.
12883            if (onSd) {
12884                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12885            }
12886            return pkgLite.recommendedInstallLocation;
12887        }
12888
12889        /*
12890         * Invoke remote method to get package information and install
12891         * location values. Override install location based on default
12892         * policy if needed and then create install arguments based
12893         * on the install location.
12894         */
12895        public void handleStartCopy() throws RemoteException {
12896            int ret = PackageManager.INSTALL_SUCCEEDED;
12897
12898            // If we're already staged, we've firmly committed to an install location
12899            if (origin.staged) {
12900                if (origin.file != null) {
12901                    installFlags |= PackageManager.INSTALL_INTERNAL;
12902                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12903                } else if (origin.cid != null) {
12904                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12905                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12906                } else {
12907                    throw new IllegalStateException("Invalid stage location");
12908                }
12909            }
12910
12911            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12912            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12913            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12914            PackageInfoLite pkgLite = null;
12915
12916            if (onInt && onSd) {
12917                // Check if both bits are set.
12918                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12919                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12920            } else if (onSd && ephemeral) {
12921                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12922                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12923            } else {
12924                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12925                        packageAbiOverride);
12926
12927                if (DEBUG_EPHEMERAL && ephemeral) {
12928                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12929                }
12930
12931                /*
12932                 * If we have too little free space, try to free cache
12933                 * before giving up.
12934                 */
12935                if (!origin.staged && pkgLite.recommendedInstallLocation
12936                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12937                    // TODO: focus freeing disk space on the target device
12938                    final StorageManager storage = StorageManager.from(mContext);
12939                    final long lowThreshold = storage.getStorageLowBytes(
12940                            Environment.getDataDirectory());
12941
12942                    final long sizeBytes = mContainerService.calculateInstalledSize(
12943                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12944
12945                    try {
12946                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
12947                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12948                                installFlags, packageAbiOverride);
12949                    } catch (InstallerException e) {
12950                        Slog.w(TAG, "Failed to free cache", e);
12951                    }
12952
12953                    /*
12954                     * The cache free must have deleted the file we
12955                     * downloaded to install.
12956                     *
12957                     * TODO: fix the "freeCache" call to not delete
12958                     *       the file we care about.
12959                     */
12960                    if (pkgLite.recommendedInstallLocation
12961                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12962                        pkgLite.recommendedInstallLocation
12963                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12964                    }
12965                }
12966            }
12967
12968            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12969                int loc = pkgLite.recommendedInstallLocation;
12970                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12971                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12972                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12973                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12974                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12975                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12976                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12977                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12978                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12979                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12980                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12981                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12982                } else {
12983                    // Override with defaults if needed.
12984                    loc = installLocationPolicy(pkgLite);
12985                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12986                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12987                    } else if (!onSd && !onInt) {
12988                        // Override install location with flags
12989                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12990                            // Set the flag to install on external media.
12991                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12992                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12993                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12994                            if (DEBUG_EPHEMERAL) {
12995                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12996                            }
12997                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12998                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12999                                    |PackageManager.INSTALL_INTERNAL);
13000                        } else {
13001                            // Make sure the flag for installing on external
13002                            // media is unset
13003                            installFlags |= PackageManager.INSTALL_INTERNAL;
13004                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13005                        }
13006                    }
13007                }
13008            }
13009
13010            final InstallArgs args = createInstallArgs(this);
13011            mArgs = args;
13012
13013            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13014                // TODO: http://b/22976637
13015                // Apps installed for "all" users use the device owner to verify the app
13016                UserHandle verifierUser = getUser();
13017                if (verifierUser == UserHandle.ALL) {
13018                    verifierUser = UserHandle.SYSTEM;
13019                }
13020
13021                /*
13022                 * Determine if we have any installed package verifiers. If we
13023                 * do, then we'll defer to them to verify the packages.
13024                 */
13025                final int requiredUid = mRequiredVerifierPackage == null ? -1
13026                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13027                                verifierUser.getIdentifier());
13028                if (!origin.existing && requiredUid != -1
13029                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13030                    final Intent verification = new Intent(
13031                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13032                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13033                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13034                            PACKAGE_MIME_TYPE);
13035                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13036
13037                    // Query all live verifiers based on current user state
13038                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13039                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13040
13041                    if (DEBUG_VERIFY) {
13042                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13043                                + verification.toString() + " with " + pkgLite.verifiers.length
13044                                + " optional verifiers");
13045                    }
13046
13047                    final int verificationId = mPendingVerificationToken++;
13048
13049                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13050
13051                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13052                            installerPackageName);
13053
13054                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13055                            installFlags);
13056
13057                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13058                            pkgLite.packageName);
13059
13060                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13061                            pkgLite.versionCode);
13062
13063                    if (verificationInfo != null) {
13064                        if (verificationInfo.originatingUri != null) {
13065                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13066                                    verificationInfo.originatingUri);
13067                        }
13068                        if (verificationInfo.referrer != null) {
13069                            verification.putExtra(Intent.EXTRA_REFERRER,
13070                                    verificationInfo.referrer);
13071                        }
13072                        if (verificationInfo.originatingUid >= 0) {
13073                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13074                                    verificationInfo.originatingUid);
13075                        }
13076                        if (verificationInfo.installerUid >= 0) {
13077                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13078                                    verificationInfo.installerUid);
13079                        }
13080                    }
13081
13082                    final PackageVerificationState verificationState = new PackageVerificationState(
13083                            requiredUid, args);
13084
13085                    mPendingVerification.append(verificationId, verificationState);
13086
13087                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13088                            receivers, verificationState);
13089
13090                    /*
13091                     * If any sufficient verifiers were listed in the package
13092                     * manifest, attempt to ask them.
13093                     */
13094                    if (sufficientVerifiers != null) {
13095                        final int N = sufficientVerifiers.size();
13096                        if (N == 0) {
13097                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13098                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13099                        } else {
13100                            for (int i = 0; i < N; i++) {
13101                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13102
13103                                final Intent sufficientIntent = new Intent(verification);
13104                                sufficientIntent.setComponent(verifierComponent);
13105                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13106                            }
13107                        }
13108                    }
13109
13110                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13111                            mRequiredVerifierPackage, receivers);
13112                    if (ret == PackageManager.INSTALL_SUCCEEDED
13113                            && mRequiredVerifierPackage != null) {
13114                        Trace.asyncTraceBegin(
13115                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13116                        /*
13117                         * Send the intent to the required verification agent,
13118                         * but only start the verification timeout after the
13119                         * target BroadcastReceivers have run.
13120                         */
13121                        verification.setComponent(requiredVerifierComponent);
13122                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13123                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13124                                new BroadcastReceiver() {
13125                                    @Override
13126                                    public void onReceive(Context context, Intent intent) {
13127                                        final Message msg = mHandler
13128                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13129                                        msg.arg1 = verificationId;
13130                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13131                                    }
13132                                }, null, 0, null, null);
13133
13134                        /*
13135                         * We don't want the copy to proceed until verification
13136                         * succeeds, so null out this field.
13137                         */
13138                        mArgs = null;
13139                    }
13140                } else {
13141                    /*
13142                     * No package verification is enabled, so immediately start
13143                     * the remote call to initiate copy using temporary file.
13144                     */
13145                    ret = args.copyApk(mContainerService, true);
13146                }
13147            }
13148
13149            mRet = ret;
13150        }
13151
13152        @Override
13153        void handleReturnCode() {
13154            // If mArgs is null, then MCS couldn't be reached. When it
13155            // reconnects, it will try again to install. At that point, this
13156            // will succeed.
13157            if (mArgs != null) {
13158                processPendingInstall(mArgs, mRet);
13159            }
13160        }
13161
13162        @Override
13163        void handleServiceError() {
13164            mArgs = createInstallArgs(this);
13165            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13166        }
13167
13168        public boolean isForwardLocked() {
13169            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13170        }
13171    }
13172
13173    /**
13174     * Used during creation of InstallArgs
13175     *
13176     * @param installFlags package installation flags
13177     * @return true if should be installed on external storage
13178     */
13179    private static boolean installOnExternalAsec(int installFlags) {
13180        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13181            return false;
13182        }
13183        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13184            return true;
13185        }
13186        return false;
13187    }
13188
13189    /**
13190     * Used during creation of InstallArgs
13191     *
13192     * @param installFlags package installation flags
13193     * @return true if should be installed as forward locked
13194     */
13195    private static boolean installForwardLocked(int installFlags) {
13196        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13197    }
13198
13199    private InstallArgs createInstallArgs(InstallParams params) {
13200        if (params.move != null) {
13201            return new MoveInstallArgs(params);
13202        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13203            return new AsecInstallArgs(params);
13204        } else {
13205            return new FileInstallArgs(params);
13206        }
13207    }
13208
13209    /**
13210     * Create args that describe an existing installed package. Typically used
13211     * when cleaning up old installs, or used as a move source.
13212     */
13213    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13214            String resourcePath, String[] instructionSets) {
13215        final boolean isInAsec;
13216        if (installOnExternalAsec(installFlags)) {
13217            /* Apps on SD card are always in ASEC containers. */
13218            isInAsec = true;
13219        } else if (installForwardLocked(installFlags)
13220                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13221            /*
13222             * Forward-locked apps are only in ASEC containers if they're the
13223             * new style
13224             */
13225            isInAsec = true;
13226        } else {
13227            isInAsec = false;
13228        }
13229
13230        if (isInAsec) {
13231            return new AsecInstallArgs(codePath, instructionSets,
13232                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13233        } else {
13234            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13235        }
13236    }
13237
13238    static abstract class InstallArgs {
13239        /** @see InstallParams#origin */
13240        final OriginInfo origin;
13241        /** @see InstallParams#move */
13242        final MoveInfo move;
13243
13244        final IPackageInstallObserver2 observer;
13245        // Always refers to PackageManager flags only
13246        final int installFlags;
13247        final String installerPackageName;
13248        final String volumeUuid;
13249        final UserHandle user;
13250        final String abiOverride;
13251        final String[] installGrantPermissions;
13252        /** If non-null, drop an async trace when the install completes */
13253        final String traceMethod;
13254        final int traceCookie;
13255        final Certificate[][] certificates;
13256
13257        // The list of instruction sets supported by this app. This is currently
13258        // only used during the rmdex() phase to clean up resources. We can get rid of this
13259        // if we move dex files under the common app path.
13260        /* nullable */ String[] instructionSets;
13261
13262        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13263                int installFlags, String installerPackageName, String volumeUuid,
13264                UserHandle user, String[] instructionSets,
13265                String abiOverride, String[] installGrantPermissions,
13266                String traceMethod, int traceCookie, Certificate[][] certificates) {
13267            this.origin = origin;
13268            this.move = move;
13269            this.installFlags = installFlags;
13270            this.observer = observer;
13271            this.installerPackageName = installerPackageName;
13272            this.volumeUuid = volumeUuid;
13273            this.user = user;
13274            this.instructionSets = instructionSets;
13275            this.abiOverride = abiOverride;
13276            this.installGrantPermissions = installGrantPermissions;
13277            this.traceMethod = traceMethod;
13278            this.traceCookie = traceCookie;
13279            this.certificates = certificates;
13280        }
13281
13282        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13283        abstract int doPreInstall(int status);
13284
13285        /**
13286         * Rename package into final resting place. All paths on the given
13287         * scanned package should be updated to reflect the rename.
13288         */
13289        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13290        abstract int doPostInstall(int status, int uid);
13291
13292        /** @see PackageSettingBase#codePathString */
13293        abstract String getCodePath();
13294        /** @see PackageSettingBase#resourcePathString */
13295        abstract String getResourcePath();
13296
13297        // Need installer lock especially for dex file removal.
13298        abstract void cleanUpResourcesLI();
13299        abstract boolean doPostDeleteLI(boolean delete);
13300
13301        /**
13302         * Called before the source arguments are copied. This is used mostly
13303         * for MoveParams when it needs to read the source file to put it in the
13304         * destination.
13305         */
13306        int doPreCopy() {
13307            return PackageManager.INSTALL_SUCCEEDED;
13308        }
13309
13310        /**
13311         * Called after the source arguments are copied. This is used mostly for
13312         * MoveParams when it needs to read the source file to put it in the
13313         * destination.
13314         */
13315        int doPostCopy(int uid) {
13316            return PackageManager.INSTALL_SUCCEEDED;
13317        }
13318
13319        protected boolean isFwdLocked() {
13320            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13321        }
13322
13323        protected boolean isExternalAsec() {
13324            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13325        }
13326
13327        protected boolean isEphemeral() {
13328            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13329        }
13330
13331        UserHandle getUser() {
13332            return user;
13333        }
13334    }
13335
13336    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13337        if (!allCodePaths.isEmpty()) {
13338            if (instructionSets == null) {
13339                throw new IllegalStateException("instructionSet == null");
13340            }
13341            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13342            for (String codePath : allCodePaths) {
13343                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13344                    try {
13345                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13346                    } catch (InstallerException ignored) {
13347                    }
13348                }
13349            }
13350        }
13351    }
13352
13353    /**
13354     * Logic to handle installation of non-ASEC applications, including copying
13355     * and renaming logic.
13356     */
13357    class FileInstallArgs extends InstallArgs {
13358        private File codeFile;
13359        private File resourceFile;
13360
13361        // Example topology:
13362        // /data/app/com.example/base.apk
13363        // /data/app/com.example/split_foo.apk
13364        // /data/app/com.example/lib/arm/libfoo.so
13365        // /data/app/com.example/lib/arm64/libfoo.so
13366        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13367
13368        /** New install */
13369        FileInstallArgs(InstallParams params) {
13370            super(params.origin, params.move, params.observer, params.installFlags,
13371                    params.installerPackageName, params.volumeUuid,
13372                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13373                    params.grantedRuntimePermissions,
13374                    params.traceMethod, params.traceCookie, params.certificates);
13375            if (isFwdLocked()) {
13376                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13377            }
13378        }
13379
13380        /** Existing install */
13381        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13382            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13383                    null, null, null, 0, null /*certificates*/);
13384            this.codeFile = (codePath != null) ? new File(codePath) : null;
13385            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13386        }
13387
13388        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13389            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13390            try {
13391                return doCopyApk(imcs, temp);
13392            } finally {
13393                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13394            }
13395        }
13396
13397        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13398            if (origin.staged) {
13399                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13400                codeFile = origin.file;
13401                resourceFile = origin.file;
13402                return PackageManager.INSTALL_SUCCEEDED;
13403            }
13404
13405            try {
13406                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13407                final File tempDir =
13408                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13409                codeFile = tempDir;
13410                resourceFile = tempDir;
13411            } catch (IOException e) {
13412                Slog.w(TAG, "Failed to create copy file: " + e);
13413                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13414            }
13415
13416            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13417                @Override
13418                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13419                    if (!FileUtils.isValidExtFilename(name)) {
13420                        throw new IllegalArgumentException("Invalid filename: " + name);
13421                    }
13422                    try {
13423                        final File file = new File(codeFile, name);
13424                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13425                                O_RDWR | O_CREAT, 0644);
13426                        Os.chmod(file.getAbsolutePath(), 0644);
13427                        return new ParcelFileDescriptor(fd);
13428                    } catch (ErrnoException e) {
13429                        throw new RemoteException("Failed to open: " + e.getMessage());
13430                    }
13431                }
13432            };
13433
13434            int ret = PackageManager.INSTALL_SUCCEEDED;
13435            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13436            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13437                Slog.e(TAG, "Failed to copy package");
13438                return ret;
13439            }
13440
13441            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13442            NativeLibraryHelper.Handle handle = null;
13443            try {
13444                handle = NativeLibraryHelper.Handle.create(codeFile);
13445                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13446                        abiOverride);
13447            } catch (IOException e) {
13448                Slog.e(TAG, "Copying native libraries failed", e);
13449                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13450            } finally {
13451                IoUtils.closeQuietly(handle);
13452            }
13453
13454            return ret;
13455        }
13456
13457        int doPreInstall(int status) {
13458            if (status != PackageManager.INSTALL_SUCCEEDED) {
13459                cleanUp();
13460            }
13461            return status;
13462        }
13463
13464        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13465            if (status != PackageManager.INSTALL_SUCCEEDED) {
13466                cleanUp();
13467                return false;
13468            }
13469
13470            final File targetDir = codeFile.getParentFile();
13471            final File beforeCodeFile = codeFile;
13472            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13473
13474            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13475            try {
13476                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13477            } catch (ErrnoException e) {
13478                Slog.w(TAG, "Failed to rename", e);
13479                return false;
13480            }
13481
13482            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13483                Slog.w(TAG, "Failed to restorecon");
13484                return false;
13485            }
13486
13487            // Reflect the rename internally
13488            codeFile = afterCodeFile;
13489            resourceFile = afterCodeFile;
13490
13491            // Reflect the rename in scanned details
13492            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13493            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13494                    afterCodeFile, pkg.baseCodePath));
13495            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13496                    afterCodeFile, pkg.splitCodePaths));
13497
13498            // Reflect the rename in app info
13499            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13500            pkg.setApplicationInfoCodePath(pkg.codePath);
13501            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13502            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13503            pkg.setApplicationInfoResourcePath(pkg.codePath);
13504            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13505            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13506
13507            return true;
13508        }
13509
13510        int doPostInstall(int status, int uid) {
13511            if (status != PackageManager.INSTALL_SUCCEEDED) {
13512                cleanUp();
13513            }
13514            return status;
13515        }
13516
13517        @Override
13518        String getCodePath() {
13519            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13520        }
13521
13522        @Override
13523        String getResourcePath() {
13524            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13525        }
13526
13527        private boolean cleanUp() {
13528            if (codeFile == null || !codeFile.exists()) {
13529                return false;
13530            }
13531
13532            removeCodePathLI(codeFile);
13533
13534            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13535                resourceFile.delete();
13536            }
13537
13538            return true;
13539        }
13540
13541        void cleanUpResourcesLI() {
13542            // Try enumerating all code paths before deleting
13543            List<String> allCodePaths = Collections.EMPTY_LIST;
13544            if (codeFile != null && codeFile.exists()) {
13545                try {
13546                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13547                    allCodePaths = pkg.getAllCodePaths();
13548                } catch (PackageParserException e) {
13549                    // Ignored; we tried our best
13550                }
13551            }
13552
13553            cleanUp();
13554            removeDexFiles(allCodePaths, instructionSets);
13555        }
13556
13557        boolean doPostDeleteLI(boolean delete) {
13558            // XXX err, shouldn't we respect the delete flag?
13559            cleanUpResourcesLI();
13560            return true;
13561        }
13562    }
13563
13564    private boolean isAsecExternal(String cid) {
13565        final String asecPath = PackageHelper.getSdFilesystem(cid);
13566        return !asecPath.startsWith(mAsecInternalPath);
13567    }
13568
13569    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13570            PackageManagerException {
13571        if (copyRet < 0) {
13572            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13573                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13574                throw new PackageManagerException(copyRet, message);
13575            }
13576        }
13577    }
13578
13579    /**
13580     * Extract the MountService "container ID" from the full code path of an
13581     * .apk.
13582     */
13583    static String cidFromCodePath(String fullCodePath) {
13584        int eidx = fullCodePath.lastIndexOf("/");
13585        String subStr1 = fullCodePath.substring(0, eidx);
13586        int sidx = subStr1.lastIndexOf("/");
13587        return subStr1.substring(sidx+1, eidx);
13588    }
13589
13590    /**
13591     * Logic to handle installation of ASEC applications, including copying and
13592     * renaming logic.
13593     */
13594    class AsecInstallArgs extends InstallArgs {
13595        static final String RES_FILE_NAME = "pkg.apk";
13596        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13597
13598        String cid;
13599        String packagePath;
13600        String resourcePath;
13601
13602        /** New install */
13603        AsecInstallArgs(InstallParams params) {
13604            super(params.origin, params.move, params.observer, params.installFlags,
13605                    params.installerPackageName, params.volumeUuid,
13606                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13607                    params.grantedRuntimePermissions,
13608                    params.traceMethod, params.traceCookie, params.certificates);
13609        }
13610
13611        /** Existing install */
13612        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13613                        boolean isExternal, boolean isForwardLocked) {
13614            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13615              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13616                    instructionSets, null, null, null, 0, null /*certificates*/);
13617            // Hackily pretend we're still looking at a full code path
13618            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13619                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13620            }
13621
13622            // Extract cid from fullCodePath
13623            int eidx = fullCodePath.lastIndexOf("/");
13624            String subStr1 = fullCodePath.substring(0, eidx);
13625            int sidx = subStr1.lastIndexOf("/");
13626            cid = subStr1.substring(sidx+1, eidx);
13627            setMountPath(subStr1);
13628        }
13629
13630        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13631            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13632              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13633                    instructionSets, null, null, null, 0, null /*certificates*/);
13634            this.cid = cid;
13635            setMountPath(PackageHelper.getSdDir(cid));
13636        }
13637
13638        void createCopyFile() {
13639            cid = mInstallerService.allocateExternalStageCidLegacy();
13640        }
13641
13642        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13643            if (origin.staged && origin.cid != null) {
13644                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13645                cid = origin.cid;
13646                setMountPath(PackageHelper.getSdDir(cid));
13647                return PackageManager.INSTALL_SUCCEEDED;
13648            }
13649
13650            if (temp) {
13651                createCopyFile();
13652            } else {
13653                /*
13654                 * Pre-emptively destroy the container since it's destroyed if
13655                 * copying fails due to it existing anyway.
13656                 */
13657                PackageHelper.destroySdDir(cid);
13658            }
13659
13660            final String newMountPath = imcs.copyPackageToContainer(
13661                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13662                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13663
13664            if (newMountPath != null) {
13665                setMountPath(newMountPath);
13666                return PackageManager.INSTALL_SUCCEEDED;
13667            } else {
13668                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13669            }
13670        }
13671
13672        @Override
13673        String getCodePath() {
13674            return packagePath;
13675        }
13676
13677        @Override
13678        String getResourcePath() {
13679            return resourcePath;
13680        }
13681
13682        int doPreInstall(int status) {
13683            if (status != PackageManager.INSTALL_SUCCEEDED) {
13684                // Destroy container
13685                PackageHelper.destroySdDir(cid);
13686            } else {
13687                boolean mounted = PackageHelper.isContainerMounted(cid);
13688                if (!mounted) {
13689                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13690                            Process.SYSTEM_UID);
13691                    if (newMountPath != null) {
13692                        setMountPath(newMountPath);
13693                    } else {
13694                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13695                    }
13696                }
13697            }
13698            return status;
13699        }
13700
13701        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13702            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13703            String newMountPath = null;
13704            if (PackageHelper.isContainerMounted(cid)) {
13705                // Unmount the container
13706                if (!PackageHelper.unMountSdDir(cid)) {
13707                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13708                    return false;
13709                }
13710            }
13711            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13712                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13713                        " which might be stale. Will try to clean up.");
13714                // Clean up the stale container and proceed to recreate.
13715                if (!PackageHelper.destroySdDir(newCacheId)) {
13716                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13717                    return false;
13718                }
13719                // Successfully cleaned up stale container. Try to rename again.
13720                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13721                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13722                            + " inspite of cleaning it up.");
13723                    return false;
13724                }
13725            }
13726            if (!PackageHelper.isContainerMounted(newCacheId)) {
13727                Slog.w(TAG, "Mounting container " + newCacheId);
13728                newMountPath = PackageHelper.mountSdDir(newCacheId,
13729                        getEncryptKey(), Process.SYSTEM_UID);
13730            } else {
13731                newMountPath = PackageHelper.getSdDir(newCacheId);
13732            }
13733            if (newMountPath == null) {
13734                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13735                return false;
13736            }
13737            Log.i(TAG, "Succesfully renamed " + cid +
13738                    " to " + newCacheId +
13739                    " at new path: " + newMountPath);
13740            cid = newCacheId;
13741
13742            final File beforeCodeFile = new File(packagePath);
13743            setMountPath(newMountPath);
13744            final File afterCodeFile = new File(packagePath);
13745
13746            // Reflect the rename in scanned details
13747            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13748            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13749                    afterCodeFile, pkg.baseCodePath));
13750            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13751                    afterCodeFile, pkg.splitCodePaths));
13752
13753            // Reflect the rename in app info
13754            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13755            pkg.setApplicationInfoCodePath(pkg.codePath);
13756            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13757            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13758            pkg.setApplicationInfoResourcePath(pkg.codePath);
13759            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13760            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13761
13762            return true;
13763        }
13764
13765        private void setMountPath(String mountPath) {
13766            final File mountFile = new File(mountPath);
13767
13768            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13769            if (monolithicFile.exists()) {
13770                packagePath = monolithicFile.getAbsolutePath();
13771                if (isFwdLocked()) {
13772                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13773                } else {
13774                    resourcePath = packagePath;
13775                }
13776            } else {
13777                packagePath = mountFile.getAbsolutePath();
13778                resourcePath = packagePath;
13779            }
13780        }
13781
13782        int doPostInstall(int status, int uid) {
13783            if (status != PackageManager.INSTALL_SUCCEEDED) {
13784                cleanUp();
13785            } else {
13786                final int groupOwner;
13787                final String protectedFile;
13788                if (isFwdLocked()) {
13789                    groupOwner = UserHandle.getSharedAppGid(uid);
13790                    protectedFile = RES_FILE_NAME;
13791                } else {
13792                    groupOwner = -1;
13793                    protectedFile = null;
13794                }
13795
13796                if (uid < Process.FIRST_APPLICATION_UID
13797                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13798                    Slog.e(TAG, "Failed to finalize " + cid);
13799                    PackageHelper.destroySdDir(cid);
13800                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13801                }
13802
13803                boolean mounted = PackageHelper.isContainerMounted(cid);
13804                if (!mounted) {
13805                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13806                }
13807            }
13808            return status;
13809        }
13810
13811        private void cleanUp() {
13812            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13813
13814            // Destroy secure container
13815            PackageHelper.destroySdDir(cid);
13816        }
13817
13818        private List<String> getAllCodePaths() {
13819            final File codeFile = new File(getCodePath());
13820            if (codeFile != null && codeFile.exists()) {
13821                try {
13822                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13823                    return pkg.getAllCodePaths();
13824                } catch (PackageParserException e) {
13825                    // Ignored; we tried our best
13826                }
13827            }
13828            return Collections.EMPTY_LIST;
13829        }
13830
13831        void cleanUpResourcesLI() {
13832            // Enumerate all code paths before deleting
13833            cleanUpResourcesLI(getAllCodePaths());
13834        }
13835
13836        private void cleanUpResourcesLI(List<String> allCodePaths) {
13837            cleanUp();
13838            removeDexFiles(allCodePaths, instructionSets);
13839        }
13840
13841        String getPackageName() {
13842            return getAsecPackageName(cid);
13843        }
13844
13845        boolean doPostDeleteLI(boolean delete) {
13846            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13847            final List<String> allCodePaths = getAllCodePaths();
13848            boolean mounted = PackageHelper.isContainerMounted(cid);
13849            if (mounted) {
13850                // Unmount first
13851                if (PackageHelper.unMountSdDir(cid)) {
13852                    mounted = false;
13853                }
13854            }
13855            if (!mounted && delete) {
13856                cleanUpResourcesLI(allCodePaths);
13857            }
13858            return !mounted;
13859        }
13860
13861        @Override
13862        int doPreCopy() {
13863            if (isFwdLocked()) {
13864                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13865                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13866                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13867                }
13868            }
13869
13870            return PackageManager.INSTALL_SUCCEEDED;
13871        }
13872
13873        @Override
13874        int doPostCopy(int uid) {
13875            if (isFwdLocked()) {
13876                if (uid < Process.FIRST_APPLICATION_UID
13877                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13878                                RES_FILE_NAME)) {
13879                    Slog.e(TAG, "Failed to finalize " + cid);
13880                    PackageHelper.destroySdDir(cid);
13881                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13882                }
13883            }
13884
13885            return PackageManager.INSTALL_SUCCEEDED;
13886        }
13887    }
13888
13889    /**
13890     * Logic to handle movement of existing installed applications.
13891     */
13892    class MoveInstallArgs extends InstallArgs {
13893        private File codeFile;
13894        private File resourceFile;
13895
13896        /** New install */
13897        MoveInstallArgs(InstallParams params) {
13898            super(params.origin, params.move, params.observer, params.installFlags,
13899                    params.installerPackageName, params.volumeUuid,
13900                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13901                    params.grantedRuntimePermissions,
13902                    params.traceMethod, params.traceCookie, params.certificates);
13903        }
13904
13905        int copyApk(IMediaContainerService imcs, boolean temp) {
13906            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13907                    + move.fromUuid + " to " + move.toUuid);
13908            synchronized (mInstaller) {
13909                try {
13910                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13911                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13912                } catch (InstallerException e) {
13913                    Slog.w(TAG, "Failed to move app", e);
13914                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13915                }
13916            }
13917
13918            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13919            resourceFile = codeFile;
13920            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13921
13922            return PackageManager.INSTALL_SUCCEEDED;
13923        }
13924
13925        int doPreInstall(int status) {
13926            if (status != PackageManager.INSTALL_SUCCEEDED) {
13927                cleanUp(move.toUuid);
13928            }
13929            return status;
13930        }
13931
13932        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13933            if (status != PackageManager.INSTALL_SUCCEEDED) {
13934                cleanUp(move.toUuid);
13935                return false;
13936            }
13937
13938            // Reflect the move in app info
13939            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13940            pkg.setApplicationInfoCodePath(pkg.codePath);
13941            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13942            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13943            pkg.setApplicationInfoResourcePath(pkg.codePath);
13944            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13945            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13946
13947            return true;
13948        }
13949
13950        int doPostInstall(int status, int uid) {
13951            if (status == PackageManager.INSTALL_SUCCEEDED) {
13952                cleanUp(move.fromUuid);
13953            } else {
13954                cleanUp(move.toUuid);
13955            }
13956            return status;
13957        }
13958
13959        @Override
13960        String getCodePath() {
13961            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13962        }
13963
13964        @Override
13965        String getResourcePath() {
13966            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13967        }
13968
13969        private boolean cleanUp(String volumeUuid) {
13970            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13971                    move.dataAppName);
13972            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13973            final int[] userIds = sUserManager.getUserIds();
13974            synchronized (mInstallLock) {
13975                // Clean up both app data and code
13976                // All package moves are frozen until finished
13977                for (int userId : userIds) {
13978                    try {
13979                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13980                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13981                    } catch (InstallerException e) {
13982                        Slog.w(TAG, String.valueOf(e));
13983                    }
13984                }
13985                removeCodePathLI(codeFile);
13986            }
13987            return true;
13988        }
13989
13990        void cleanUpResourcesLI() {
13991            throw new UnsupportedOperationException();
13992        }
13993
13994        boolean doPostDeleteLI(boolean delete) {
13995            throw new UnsupportedOperationException();
13996        }
13997    }
13998
13999    static String getAsecPackageName(String packageCid) {
14000        int idx = packageCid.lastIndexOf("-");
14001        if (idx == -1) {
14002            return packageCid;
14003        }
14004        return packageCid.substring(0, idx);
14005    }
14006
14007    // Utility method used to create code paths based on package name and available index.
14008    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14009        String idxStr = "";
14010        int idx = 1;
14011        // Fall back to default value of idx=1 if prefix is not
14012        // part of oldCodePath
14013        if (oldCodePath != null) {
14014            String subStr = oldCodePath;
14015            // Drop the suffix right away
14016            if (suffix != null && subStr.endsWith(suffix)) {
14017                subStr = subStr.substring(0, subStr.length() - suffix.length());
14018            }
14019            // If oldCodePath already contains prefix find out the
14020            // ending index to either increment or decrement.
14021            int sidx = subStr.lastIndexOf(prefix);
14022            if (sidx != -1) {
14023                subStr = subStr.substring(sidx + prefix.length());
14024                if (subStr != null) {
14025                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14026                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14027                    }
14028                    try {
14029                        idx = Integer.parseInt(subStr);
14030                        if (idx <= 1) {
14031                            idx++;
14032                        } else {
14033                            idx--;
14034                        }
14035                    } catch(NumberFormatException e) {
14036                    }
14037                }
14038            }
14039        }
14040        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14041        return prefix + idxStr;
14042    }
14043
14044    private File getNextCodePath(File targetDir, String packageName) {
14045        int suffix = 1;
14046        File result;
14047        do {
14048            result = new File(targetDir, packageName + "-" + suffix);
14049            suffix++;
14050        } while (result.exists());
14051        return result;
14052    }
14053
14054    // Utility method that returns the relative package path with respect
14055    // to the installation directory. Like say for /data/data/com.test-1.apk
14056    // string com.test-1 is returned.
14057    static String deriveCodePathName(String codePath) {
14058        if (codePath == null) {
14059            return null;
14060        }
14061        final File codeFile = new File(codePath);
14062        final String name = codeFile.getName();
14063        if (codeFile.isDirectory()) {
14064            return name;
14065        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14066            final int lastDot = name.lastIndexOf('.');
14067            return name.substring(0, lastDot);
14068        } else {
14069            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14070            return null;
14071        }
14072    }
14073
14074    static class PackageInstalledInfo {
14075        String name;
14076        int uid;
14077        // The set of users that originally had this package installed.
14078        int[] origUsers;
14079        // The set of users that now have this package installed.
14080        int[] newUsers;
14081        PackageParser.Package pkg;
14082        int returnCode;
14083        String returnMsg;
14084        PackageRemovedInfo removedInfo;
14085        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14086
14087        public void setError(int code, String msg) {
14088            setReturnCode(code);
14089            setReturnMessage(msg);
14090            Slog.w(TAG, msg);
14091        }
14092
14093        public void setError(String msg, PackageParserException e) {
14094            setReturnCode(e.error);
14095            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14096            Slog.w(TAG, msg, e);
14097        }
14098
14099        public void setError(String msg, PackageManagerException e) {
14100            returnCode = e.error;
14101            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14102            Slog.w(TAG, msg, e);
14103        }
14104
14105        public void setReturnCode(int returnCode) {
14106            this.returnCode = returnCode;
14107            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14108            for (int i = 0; i < childCount; i++) {
14109                addedChildPackages.valueAt(i).returnCode = returnCode;
14110            }
14111        }
14112
14113        private void setReturnMessage(String returnMsg) {
14114            this.returnMsg = returnMsg;
14115            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14116            for (int i = 0; i < childCount; i++) {
14117                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14118            }
14119        }
14120
14121        // In some error cases we want to convey more info back to the observer
14122        String origPackage;
14123        String origPermission;
14124    }
14125
14126    /*
14127     * Install a non-existing package.
14128     */
14129    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14130            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14131            PackageInstalledInfo res) {
14132        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14133
14134        // Remember this for later, in case we need to rollback this install
14135        String pkgName = pkg.packageName;
14136
14137        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14138
14139        synchronized(mPackages) {
14140            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14141                // A package with the same name is already installed, though
14142                // it has been renamed to an older name.  The package we
14143                // are trying to install should be installed as an update to
14144                // the existing one, but that has not been requested, so bail.
14145                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14146                        + " without first uninstalling package running as "
14147                        + mSettings.mRenamedPackages.get(pkgName));
14148                return;
14149            }
14150            if (mPackages.containsKey(pkgName)) {
14151                // Don't allow installation over an existing package with the same name.
14152                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14153                        + " without first uninstalling.");
14154                return;
14155            }
14156        }
14157
14158        try {
14159            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14160                    System.currentTimeMillis(), user);
14161
14162            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14163
14164            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14165                prepareAppDataAfterInstallLIF(newPackage);
14166
14167            } else {
14168                // Remove package from internal structures, but keep around any
14169                // data that might have already existed
14170                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14171                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14172            }
14173        } catch (PackageManagerException e) {
14174            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14175        }
14176
14177        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14178    }
14179
14180    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14181        // Can't rotate keys during boot or if sharedUser.
14182        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14183                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14184            return false;
14185        }
14186        // app is using upgradeKeySets; make sure all are valid
14187        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14188        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14189        for (int i = 0; i < upgradeKeySets.length; i++) {
14190            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14191                Slog.wtf(TAG, "Package "
14192                         + (oldPs.name != null ? oldPs.name : "<null>")
14193                         + " contains upgrade-key-set reference to unknown key-set: "
14194                         + upgradeKeySets[i]
14195                         + " reverting to signatures check.");
14196                return false;
14197            }
14198        }
14199        return true;
14200    }
14201
14202    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14203        // Upgrade keysets are being used.  Determine if new package has a superset of the
14204        // required keys.
14205        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14206        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14207        for (int i = 0; i < upgradeKeySets.length; i++) {
14208            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14209            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14210                return true;
14211            }
14212        }
14213        return false;
14214    }
14215
14216    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14217        try (DigestInputStream digestStream =
14218                new DigestInputStream(new FileInputStream(file), digest)) {
14219            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14220        }
14221    }
14222
14223    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14224            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14225        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14226
14227        final PackageParser.Package oldPackage;
14228        final String pkgName = pkg.packageName;
14229        final int[] allUsers;
14230        final int[] installedUsers;
14231
14232        synchronized(mPackages) {
14233            oldPackage = mPackages.get(pkgName);
14234            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14235
14236            // don't allow upgrade to target a release SDK from a pre-release SDK
14237            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14238                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14239            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14240                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14241            if (oldTargetsPreRelease
14242                    && !newTargetsPreRelease
14243                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14244                Slog.w(TAG, "Can't install package targeting released sdk");
14245                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14246                return;
14247            }
14248
14249            // don't allow an upgrade from full to ephemeral
14250            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14251            if (isEphemeral && !oldIsEphemeral) {
14252                // can't downgrade from full to ephemeral
14253                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14254                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14255                return;
14256            }
14257
14258            // verify signatures are valid
14259            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14260            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14261                if (!checkUpgradeKeySetLP(ps, pkg)) {
14262                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14263                            "New package not signed by keys specified by upgrade-keysets: "
14264                                    + pkgName);
14265                    return;
14266                }
14267            } else {
14268                // default to original signature matching
14269                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14270                        != PackageManager.SIGNATURE_MATCH) {
14271                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14272                            "New package has a different signature: " + pkgName);
14273                    return;
14274                }
14275            }
14276
14277            // don't allow a system upgrade unless the upgrade hash matches
14278            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14279                byte[] digestBytes = null;
14280                try {
14281                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14282                    updateDigest(digest, new File(pkg.baseCodePath));
14283                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14284                        for (String path : pkg.splitCodePaths) {
14285                            updateDigest(digest, new File(path));
14286                        }
14287                    }
14288                    digestBytes = digest.digest();
14289                } catch (NoSuchAlgorithmException | IOException e) {
14290                    res.setError(INSTALL_FAILED_INVALID_APK,
14291                            "Could not compute hash: " + pkgName);
14292                    return;
14293                }
14294                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14295                    res.setError(INSTALL_FAILED_INVALID_APK,
14296                            "New package fails restrict-update check: " + pkgName);
14297                    return;
14298                }
14299                // retain upgrade restriction
14300                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14301            }
14302
14303            // Check for shared user id changes
14304            String invalidPackageName =
14305                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14306            if (invalidPackageName != null) {
14307                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14308                        "Package " + invalidPackageName + " tried to change user "
14309                                + oldPackage.mSharedUserId);
14310                return;
14311            }
14312
14313            // In case of rollback, remember per-user/profile install state
14314            allUsers = sUserManager.getUserIds();
14315            installedUsers = ps.queryInstalledUsers(allUsers, true);
14316        }
14317
14318        // Update what is removed
14319        res.removedInfo = new PackageRemovedInfo();
14320        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14321        res.removedInfo.removedPackage = oldPackage.packageName;
14322        res.removedInfo.isUpdate = true;
14323        res.removedInfo.origUsers = installedUsers;
14324        final int childCount = (oldPackage.childPackages != null)
14325                ? oldPackage.childPackages.size() : 0;
14326        for (int i = 0; i < childCount; i++) {
14327            boolean childPackageUpdated = false;
14328            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14329            if (res.addedChildPackages != null) {
14330                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14331                if (childRes != null) {
14332                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14333                    childRes.removedInfo.removedPackage = childPkg.packageName;
14334                    childRes.removedInfo.isUpdate = true;
14335                    childPackageUpdated = true;
14336                }
14337            }
14338            if (!childPackageUpdated) {
14339                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14340                childRemovedRes.removedPackage = childPkg.packageName;
14341                childRemovedRes.isUpdate = false;
14342                childRemovedRes.dataRemoved = true;
14343                synchronized (mPackages) {
14344                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14345                    if (childPs != null) {
14346                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14347                    }
14348                }
14349                if (res.removedInfo.removedChildPackages == null) {
14350                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14351                }
14352                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14353            }
14354        }
14355
14356        boolean sysPkg = (isSystemApp(oldPackage));
14357        if (sysPkg) {
14358            // Set the system/privileged flags as needed
14359            final boolean privileged =
14360                    (oldPackage.applicationInfo.privateFlags
14361                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14362            final int systemPolicyFlags = policyFlags
14363                    | PackageParser.PARSE_IS_SYSTEM
14364                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14365
14366            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14367                    user, allUsers, installerPackageName, res);
14368        } else {
14369            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14370                    user, allUsers, installerPackageName, res);
14371        }
14372    }
14373
14374    public List<String> getPreviousCodePaths(String packageName) {
14375        final PackageSetting ps = mSettings.mPackages.get(packageName);
14376        final List<String> result = new ArrayList<String>();
14377        if (ps != null && ps.oldCodePaths != null) {
14378            result.addAll(ps.oldCodePaths);
14379        }
14380        return result;
14381    }
14382
14383    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14384            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14385            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14386        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14387                + deletedPackage);
14388
14389        String pkgName = deletedPackage.packageName;
14390        boolean deletedPkg = true;
14391        boolean addedPkg = false;
14392        boolean updatedSettings = false;
14393        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14394        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14395                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14396
14397        final long origUpdateTime = (pkg.mExtras != null)
14398                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14399
14400        // First delete the existing package while retaining the data directory
14401        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14402                res.removedInfo, true, pkg)) {
14403            // If the existing package wasn't successfully deleted
14404            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14405            deletedPkg = false;
14406        } else {
14407            // Successfully deleted the old package; proceed with replace.
14408
14409            // If deleted package lived in a container, give users a chance to
14410            // relinquish resources before killing.
14411            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14412                if (DEBUG_INSTALL) {
14413                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14414                }
14415                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14416                final ArrayList<String> pkgList = new ArrayList<String>(1);
14417                pkgList.add(deletedPackage.applicationInfo.packageName);
14418                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14419            }
14420
14421            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14422                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14423            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14424
14425            try {
14426                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14427                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14428                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14429
14430                // Update the in-memory copy of the previous code paths.
14431                PackageSetting ps = mSettings.mPackages.get(pkgName);
14432                if (!killApp) {
14433                    if (ps.oldCodePaths == null) {
14434                        ps.oldCodePaths = new ArraySet<>();
14435                    }
14436                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14437                    if (deletedPackage.splitCodePaths != null) {
14438                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14439                    }
14440                } else {
14441                    ps.oldCodePaths = null;
14442                }
14443                if (ps.childPackageNames != null) {
14444                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14445                        final String childPkgName = ps.childPackageNames.get(i);
14446                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14447                        childPs.oldCodePaths = ps.oldCodePaths;
14448                    }
14449                }
14450                prepareAppDataAfterInstallLIF(newPackage);
14451                addedPkg = true;
14452            } catch (PackageManagerException e) {
14453                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14454            }
14455        }
14456
14457        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14458            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14459
14460            // Revert all internal state mutations and added folders for the failed install
14461            if (addedPkg) {
14462                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14463                        res.removedInfo, true, null);
14464            }
14465
14466            // Restore the old package
14467            if (deletedPkg) {
14468                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14469                File restoreFile = new File(deletedPackage.codePath);
14470                // Parse old package
14471                boolean oldExternal = isExternal(deletedPackage);
14472                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14473                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14474                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14475                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14476                try {
14477                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14478                            null);
14479                } catch (PackageManagerException e) {
14480                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14481                            + e.getMessage());
14482                    return;
14483                }
14484
14485                synchronized (mPackages) {
14486                    // Ensure the installer package name up to date
14487                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14488
14489                    // Update permissions for restored package
14490                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14491
14492                    mSettings.writeLPr();
14493                }
14494
14495                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14496            }
14497        } else {
14498            synchronized (mPackages) {
14499                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14500                if (ps != null) {
14501                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14502                    if (res.removedInfo.removedChildPackages != null) {
14503                        final int childCount = res.removedInfo.removedChildPackages.size();
14504                        // Iterate in reverse as we may modify the collection
14505                        for (int i = childCount - 1; i >= 0; i--) {
14506                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14507                            if (res.addedChildPackages.containsKey(childPackageName)) {
14508                                res.removedInfo.removedChildPackages.removeAt(i);
14509                            } else {
14510                                PackageRemovedInfo childInfo = res.removedInfo
14511                                        .removedChildPackages.valueAt(i);
14512                                childInfo.removedForAllUsers = mPackages.get(
14513                                        childInfo.removedPackage) == null;
14514                            }
14515                        }
14516                    }
14517                }
14518            }
14519        }
14520    }
14521
14522    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14523            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14524            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14525        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14526                + ", old=" + deletedPackage);
14527
14528        final boolean disabledSystem;
14529
14530        // Remove existing system package
14531        removePackageLI(deletedPackage, true);
14532
14533        synchronized (mPackages) {
14534            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14535        }
14536        if (!disabledSystem) {
14537            // We didn't need to disable the .apk as a current system package,
14538            // which means we are replacing another update that is already
14539            // installed.  We need to make sure to delete the older one's .apk.
14540            res.removedInfo.args = createInstallArgsForExisting(0,
14541                    deletedPackage.applicationInfo.getCodePath(),
14542                    deletedPackage.applicationInfo.getResourcePath(),
14543                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14544        } else {
14545            res.removedInfo.args = null;
14546        }
14547
14548        // Successfully disabled the old package. Now proceed with re-installation
14549        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14550                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14551        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14552
14553        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14554        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14555                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14556
14557        PackageParser.Package newPackage = null;
14558        try {
14559            // Add the package to the internal data structures
14560            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14561
14562            // Set the update and install times
14563            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14564            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14565                    System.currentTimeMillis());
14566
14567            // Update the package dynamic state if succeeded
14568            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14569                // Now that the install succeeded make sure we remove data
14570                // directories for any child package the update removed.
14571                final int deletedChildCount = (deletedPackage.childPackages != null)
14572                        ? deletedPackage.childPackages.size() : 0;
14573                final int newChildCount = (newPackage.childPackages != null)
14574                        ? newPackage.childPackages.size() : 0;
14575                for (int i = 0; i < deletedChildCount; i++) {
14576                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14577                    boolean childPackageDeleted = true;
14578                    for (int j = 0; j < newChildCount; j++) {
14579                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14580                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14581                            childPackageDeleted = false;
14582                            break;
14583                        }
14584                    }
14585                    if (childPackageDeleted) {
14586                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14587                                deletedChildPkg.packageName);
14588                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14589                            PackageRemovedInfo removedChildRes = res.removedInfo
14590                                    .removedChildPackages.get(deletedChildPkg.packageName);
14591                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14592                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14593                        }
14594                    }
14595                }
14596
14597                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14598                prepareAppDataAfterInstallLIF(newPackage);
14599            }
14600        } catch (PackageManagerException e) {
14601            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14602            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14603        }
14604
14605        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14606            // Re installation failed. Restore old information
14607            // Remove new pkg information
14608            if (newPackage != null) {
14609                removeInstalledPackageLI(newPackage, true);
14610            }
14611            // Add back the old system package
14612            try {
14613                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14614            } catch (PackageManagerException e) {
14615                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14616            }
14617
14618            synchronized (mPackages) {
14619                if (disabledSystem) {
14620                    enableSystemPackageLPw(deletedPackage);
14621                }
14622
14623                // Ensure the installer package name up to date
14624                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14625
14626                // Update permissions for restored package
14627                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14628
14629                mSettings.writeLPr();
14630            }
14631
14632            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14633                    + " after failed upgrade");
14634        }
14635    }
14636
14637    /**
14638     * Checks whether the parent or any of the child packages have a change shared
14639     * user. For a package to be a valid update the shred users of the parent and
14640     * the children should match. We may later support changing child shared users.
14641     * @param oldPkg The updated package.
14642     * @param newPkg The update package.
14643     * @return The shared user that change between the versions.
14644     */
14645    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14646            PackageParser.Package newPkg) {
14647        // Check parent shared user
14648        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14649            return newPkg.packageName;
14650        }
14651        // Check child shared users
14652        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14653        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14654        for (int i = 0; i < newChildCount; i++) {
14655            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14656            // If this child was present, did it have the same shared user?
14657            for (int j = 0; j < oldChildCount; j++) {
14658                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14659                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14660                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14661                    return newChildPkg.packageName;
14662                }
14663            }
14664        }
14665        return null;
14666    }
14667
14668    private void removeNativeBinariesLI(PackageSetting ps) {
14669        // Remove the lib path for the parent package
14670        if (ps != null) {
14671            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14672            // Remove the lib path for the child packages
14673            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14674            for (int i = 0; i < childCount; i++) {
14675                PackageSetting childPs = null;
14676                synchronized (mPackages) {
14677                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14678                }
14679                if (childPs != null) {
14680                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14681                            .legacyNativeLibraryPathString);
14682                }
14683            }
14684        }
14685    }
14686
14687    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14688        // Enable the parent package
14689        mSettings.enableSystemPackageLPw(pkg.packageName);
14690        // Enable the child packages
14691        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14692        for (int i = 0; i < childCount; i++) {
14693            PackageParser.Package childPkg = pkg.childPackages.get(i);
14694            mSettings.enableSystemPackageLPw(childPkg.packageName);
14695        }
14696    }
14697
14698    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14699            PackageParser.Package newPkg) {
14700        // Disable the parent package (parent always replaced)
14701        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14702        // Disable the child packages
14703        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14704        for (int i = 0; i < childCount; i++) {
14705            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14706            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14707            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14708        }
14709        return disabled;
14710    }
14711
14712    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14713            String installerPackageName) {
14714        // Enable the parent package
14715        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14716        // Enable the child packages
14717        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14718        for (int i = 0; i < childCount; i++) {
14719            PackageParser.Package childPkg = pkg.childPackages.get(i);
14720            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14721        }
14722    }
14723
14724    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14725        // Collect all used permissions in the UID
14726        ArraySet<String> usedPermissions = new ArraySet<>();
14727        final int packageCount = su.packages.size();
14728        for (int i = 0; i < packageCount; i++) {
14729            PackageSetting ps = su.packages.valueAt(i);
14730            if (ps.pkg == null) {
14731                continue;
14732            }
14733            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14734            for (int j = 0; j < requestedPermCount; j++) {
14735                String permission = ps.pkg.requestedPermissions.get(j);
14736                BasePermission bp = mSettings.mPermissions.get(permission);
14737                if (bp != null) {
14738                    usedPermissions.add(permission);
14739                }
14740            }
14741        }
14742
14743        PermissionsState permissionsState = su.getPermissionsState();
14744        // Prune install permissions
14745        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14746        final int installPermCount = installPermStates.size();
14747        for (int i = installPermCount - 1; i >= 0;  i--) {
14748            PermissionState permissionState = installPermStates.get(i);
14749            if (!usedPermissions.contains(permissionState.getName())) {
14750                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14751                if (bp != null) {
14752                    permissionsState.revokeInstallPermission(bp);
14753                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14754                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14755                }
14756            }
14757        }
14758
14759        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14760
14761        // Prune runtime permissions
14762        for (int userId : allUserIds) {
14763            List<PermissionState> runtimePermStates = permissionsState
14764                    .getRuntimePermissionStates(userId);
14765            final int runtimePermCount = runtimePermStates.size();
14766            for (int i = runtimePermCount - 1; i >= 0; i--) {
14767                PermissionState permissionState = runtimePermStates.get(i);
14768                if (!usedPermissions.contains(permissionState.getName())) {
14769                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14770                    if (bp != null) {
14771                        permissionsState.revokeRuntimePermission(bp, userId);
14772                        permissionsState.updatePermissionFlags(bp, userId,
14773                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14774                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14775                                runtimePermissionChangedUserIds, userId);
14776                    }
14777                }
14778            }
14779        }
14780
14781        return runtimePermissionChangedUserIds;
14782    }
14783
14784    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14785            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14786        // Update the parent package setting
14787        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14788                res, user);
14789        // Update the child packages setting
14790        final int childCount = (newPackage.childPackages != null)
14791                ? newPackage.childPackages.size() : 0;
14792        for (int i = 0; i < childCount; i++) {
14793            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14794            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14795            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14796                    childRes.origUsers, childRes, user);
14797        }
14798    }
14799
14800    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14801            String installerPackageName, int[] allUsers, int[] installedForUsers,
14802            PackageInstalledInfo res, UserHandle user) {
14803        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14804
14805        String pkgName = newPackage.packageName;
14806        synchronized (mPackages) {
14807            //write settings. the installStatus will be incomplete at this stage.
14808            //note that the new package setting would have already been
14809            //added to mPackages. It hasn't been persisted yet.
14810            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14811            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14812            mSettings.writeLPr();
14813            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14814        }
14815
14816        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14817        synchronized (mPackages) {
14818            updatePermissionsLPw(newPackage.packageName, newPackage,
14819                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14820                            ? UPDATE_PERMISSIONS_ALL : 0));
14821            // For system-bundled packages, we assume that installing an upgraded version
14822            // of the package implies that the user actually wants to run that new code,
14823            // so we enable the package.
14824            PackageSetting ps = mSettings.mPackages.get(pkgName);
14825            final int userId = user.getIdentifier();
14826            if (ps != null) {
14827                if (isSystemApp(newPackage)) {
14828                    if (DEBUG_INSTALL) {
14829                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14830                    }
14831                    // Enable system package for requested users
14832                    if (res.origUsers != null) {
14833                        for (int origUserId : res.origUsers) {
14834                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14835                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14836                                        origUserId, installerPackageName);
14837                            }
14838                        }
14839                    }
14840                    // Also convey the prior install/uninstall state
14841                    if (allUsers != null && installedForUsers != null) {
14842                        for (int currentUserId : allUsers) {
14843                            final boolean installed = ArrayUtils.contains(
14844                                    installedForUsers, currentUserId);
14845                            if (DEBUG_INSTALL) {
14846                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14847                            }
14848                            ps.setInstalled(installed, currentUserId);
14849                        }
14850                        // these install state changes will be persisted in the
14851                        // upcoming call to mSettings.writeLPr().
14852                    }
14853                }
14854                // It's implied that when a user requests installation, they want the app to be
14855                // installed and enabled.
14856                if (userId != UserHandle.USER_ALL) {
14857                    ps.setInstalled(true, userId);
14858                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14859                }
14860            }
14861            res.name = pkgName;
14862            res.uid = newPackage.applicationInfo.uid;
14863            res.pkg = newPackage;
14864            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14865            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14866            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14867            //to update install status
14868            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14869            mSettings.writeLPr();
14870            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14871        }
14872
14873        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14874    }
14875
14876    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14877        try {
14878            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14879            installPackageLI(args, res);
14880        } finally {
14881            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14882        }
14883    }
14884
14885    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14886        final int installFlags = args.installFlags;
14887        final String installerPackageName = args.installerPackageName;
14888        final String volumeUuid = args.volumeUuid;
14889        final File tmpPackageFile = new File(args.getCodePath());
14890        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14891        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14892                || (args.volumeUuid != null));
14893        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14894        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14895        boolean replace = false;
14896        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14897        if (args.move != null) {
14898            // moving a complete application; perform an initial scan on the new install location
14899            scanFlags |= SCAN_INITIAL;
14900        }
14901        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14902            scanFlags |= SCAN_DONT_KILL_APP;
14903        }
14904
14905        // Result object to be returned
14906        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14907
14908        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14909
14910        // Sanity check
14911        if (ephemeral && (forwardLocked || onExternal)) {
14912            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14913                    + " external=" + onExternal);
14914            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14915            return;
14916        }
14917
14918        // Retrieve PackageSettings and parse package
14919        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14920                | PackageParser.PARSE_ENFORCE_CODE
14921                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14922                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14923                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14924                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14925        PackageParser pp = new PackageParser();
14926        pp.setSeparateProcesses(mSeparateProcesses);
14927        pp.setDisplayMetrics(mMetrics);
14928
14929        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14930        final PackageParser.Package pkg;
14931        try {
14932            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14933        } catch (PackageParserException e) {
14934            res.setError("Failed parse during installPackageLI", e);
14935            return;
14936        } finally {
14937            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14938        }
14939
14940        // If we are installing a clustered package add results for the children
14941        if (pkg.childPackages != null) {
14942            synchronized (mPackages) {
14943                final int childCount = pkg.childPackages.size();
14944                for (int i = 0; i < childCount; i++) {
14945                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14946                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14947                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14948                    childRes.pkg = childPkg;
14949                    childRes.name = childPkg.packageName;
14950                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14951                    if (childPs != null) {
14952                        childRes.origUsers = childPs.queryInstalledUsers(
14953                                sUserManager.getUserIds(), true);
14954                    }
14955                    if ((mPackages.containsKey(childPkg.packageName))) {
14956                        childRes.removedInfo = new PackageRemovedInfo();
14957                        childRes.removedInfo.removedPackage = childPkg.packageName;
14958                    }
14959                    if (res.addedChildPackages == null) {
14960                        res.addedChildPackages = new ArrayMap<>();
14961                    }
14962                    res.addedChildPackages.put(childPkg.packageName, childRes);
14963                }
14964            }
14965        }
14966
14967        // If package doesn't declare API override, mark that we have an install
14968        // time CPU ABI override.
14969        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14970            pkg.cpuAbiOverride = args.abiOverride;
14971        }
14972
14973        String pkgName = res.name = pkg.packageName;
14974        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14975            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14976                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14977                return;
14978            }
14979        }
14980
14981        try {
14982            // either use what we've been given or parse directly from the APK
14983            if (args.certificates != null) {
14984                try {
14985                    PackageParser.populateCertificates(pkg, args.certificates);
14986                } catch (PackageParserException e) {
14987                    // there was something wrong with the certificates we were given;
14988                    // try to pull them from the APK
14989                    PackageParser.collectCertificates(pkg, parseFlags);
14990                }
14991            } else {
14992                PackageParser.collectCertificates(pkg, parseFlags);
14993            }
14994        } catch (PackageParserException e) {
14995            res.setError("Failed collect during installPackageLI", e);
14996            return;
14997        }
14998
14999        // Get rid of all references to package scan path via parser.
15000        pp = null;
15001        String oldCodePath = null;
15002        boolean systemApp = false;
15003        synchronized (mPackages) {
15004            // Check if installing already existing package
15005            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15006                String oldName = mSettings.mRenamedPackages.get(pkgName);
15007                if (pkg.mOriginalPackages != null
15008                        && pkg.mOriginalPackages.contains(oldName)
15009                        && mPackages.containsKey(oldName)) {
15010                    // This package is derived from an original package,
15011                    // and this device has been updating from that original
15012                    // name.  We must continue using the original name, so
15013                    // rename the new package here.
15014                    pkg.setPackageName(oldName);
15015                    pkgName = pkg.packageName;
15016                    replace = true;
15017                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15018                            + oldName + " pkgName=" + pkgName);
15019                } else if (mPackages.containsKey(pkgName)) {
15020                    // This package, under its official name, already exists
15021                    // on the device; we should replace it.
15022                    replace = true;
15023                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15024                }
15025
15026                // Child packages are installed through the parent package
15027                if (pkg.parentPackage != null) {
15028                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15029                            "Package " + pkg.packageName + " is child of package "
15030                                    + pkg.parentPackage.parentPackage + ". Child packages "
15031                                    + "can be updated only through the parent package.");
15032                    return;
15033                }
15034
15035                if (replace) {
15036                    // Prevent apps opting out from runtime permissions
15037                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15038                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15039                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15040                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15041                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15042                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15043                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15044                                        + " doesn't support runtime permissions but the old"
15045                                        + " target SDK " + oldTargetSdk + " does.");
15046                        return;
15047                    }
15048
15049                    // Prevent installing of child packages
15050                    if (oldPackage.parentPackage != null) {
15051                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15052                                "Package " + pkg.packageName + " is child of package "
15053                                        + oldPackage.parentPackage + ". Child packages "
15054                                        + "can be updated only through the parent package.");
15055                        return;
15056                    }
15057                }
15058            }
15059
15060            PackageSetting ps = mSettings.mPackages.get(pkgName);
15061            if (ps != null) {
15062                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15063
15064                // Quick sanity check that we're signed correctly if updating;
15065                // we'll check this again later when scanning, but we want to
15066                // bail early here before tripping over redefined permissions.
15067                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15068                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15069                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15070                                + pkg.packageName + " upgrade keys do not match the "
15071                                + "previously installed version");
15072                        return;
15073                    }
15074                } else {
15075                    try {
15076                        verifySignaturesLP(ps, pkg);
15077                    } catch (PackageManagerException e) {
15078                        res.setError(e.error, e.getMessage());
15079                        return;
15080                    }
15081                }
15082
15083                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15084                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15085                    systemApp = (ps.pkg.applicationInfo.flags &
15086                            ApplicationInfo.FLAG_SYSTEM) != 0;
15087                }
15088                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15089            }
15090
15091            // Check whether the newly-scanned package wants to define an already-defined perm
15092            int N = pkg.permissions.size();
15093            for (int i = N-1; i >= 0; i--) {
15094                PackageParser.Permission perm = pkg.permissions.get(i);
15095                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15096                if (bp != null) {
15097                    // If the defining package is signed with our cert, it's okay.  This
15098                    // also includes the "updating the same package" case, of course.
15099                    // "updating same package" could also involve key-rotation.
15100                    final boolean sigsOk;
15101                    if (bp.sourcePackage.equals(pkg.packageName)
15102                            && (bp.packageSetting instanceof PackageSetting)
15103                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15104                                    scanFlags))) {
15105                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15106                    } else {
15107                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15108                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15109                    }
15110                    if (!sigsOk) {
15111                        // If the owning package is the system itself, we log but allow
15112                        // install to proceed; we fail the install on all other permission
15113                        // redefinitions.
15114                        if (!bp.sourcePackage.equals("android")) {
15115                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15116                                    + pkg.packageName + " attempting to redeclare permission "
15117                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15118                            res.origPermission = perm.info.name;
15119                            res.origPackage = bp.sourcePackage;
15120                            return;
15121                        } else {
15122                            Slog.w(TAG, "Package " + pkg.packageName
15123                                    + " attempting to redeclare system permission "
15124                                    + perm.info.name + "; ignoring new declaration");
15125                            pkg.permissions.remove(i);
15126                        }
15127                    }
15128                }
15129            }
15130        }
15131
15132        if (systemApp) {
15133            if (onExternal) {
15134                // Abort update; system app can't be replaced with app on sdcard
15135                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15136                        "Cannot install updates to system apps on sdcard");
15137                return;
15138            } else if (ephemeral) {
15139                // Abort update; system app can't be replaced with an ephemeral app
15140                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15141                        "Cannot update a system app with an ephemeral app");
15142                return;
15143            }
15144        }
15145
15146        if (args.move != null) {
15147            // We did an in-place move, so dex is ready to roll
15148            scanFlags |= SCAN_NO_DEX;
15149            scanFlags |= SCAN_MOVE;
15150
15151            synchronized (mPackages) {
15152                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15153                if (ps == null) {
15154                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15155                            "Missing settings for moved package " + pkgName);
15156                }
15157
15158                // We moved the entire application as-is, so bring over the
15159                // previously derived ABI information.
15160                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15161                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15162            }
15163
15164        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15165            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15166            scanFlags |= SCAN_NO_DEX;
15167
15168            try {
15169                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15170                    args.abiOverride : pkg.cpuAbiOverride);
15171                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15172                        true /* extract libs */);
15173            } catch (PackageManagerException pme) {
15174                Slog.e(TAG, "Error deriving application ABI", pme);
15175                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15176                return;
15177            }
15178
15179            // Shared libraries for the package need to be updated.
15180            synchronized (mPackages) {
15181                try {
15182                    updateSharedLibrariesLPw(pkg, null);
15183                } catch (PackageManagerException e) {
15184                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15185                }
15186            }
15187            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15188            // Do not run PackageDexOptimizer through the local performDexOpt
15189            // method because `pkg` may not be in `mPackages` yet.
15190            //
15191            // Also, don't fail application installs if the dexopt step fails.
15192            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15193                    null /* instructionSets */, false /* checkProfiles */,
15194                    getCompilerFilterForReason(REASON_INSTALL),
15195                    getOrCreateCompilerPackageStats(pkg),
15196                    mDexManager.isUsedByOtherApps(pkg.packageName));
15197            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15198
15199            // Notify BackgroundDexOptService that the package has been changed.
15200            // If this is an update of a package which used to fail to compile,
15201            // BDOS will remove it from its blacklist.
15202            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15203        }
15204
15205        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15206            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15207            return;
15208        }
15209
15210        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15211
15212        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15213                "installPackageLI")) {
15214            if (replace) {
15215                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15216                        installerPackageName, res);
15217            } else {
15218                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15219                        args.user, installerPackageName, volumeUuid, res);
15220            }
15221        }
15222        synchronized (mPackages) {
15223            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15224            if (ps != null) {
15225                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15226            }
15227
15228            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15229            for (int i = 0; i < childCount; i++) {
15230                PackageParser.Package childPkg = pkg.childPackages.get(i);
15231                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15232                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15233                if (childPs != null) {
15234                    childRes.newUsers = childPs.queryInstalledUsers(
15235                            sUserManager.getUserIds(), true);
15236                }
15237            }
15238        }
15239    }
15240
15241    private void startIntentFilterVerifications(int userId, boolean replacing,
15242            PackageParser.Package pkg) {
15243        if (mIntentFilterVerifierComponent == null) {
15244            Slog.w(TAG, "No IntentFilter verification will not be done as "
15245                    + "there is no IntentFilterVerifier available!");
15246            return;
15247        }
15248
15249        final int verifierUid = getPackageUid(
15250                mIntentFilterVerifierComponent.getPackageName(),
15251                MATCH_DEBUG_TRIAGED_MISSING,
15252                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15253
15254        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15255        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15256        mHandler.sendMessage(msg);
15257
15258        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15259        for (int i = 0; i < childCount; i++) {
15260            PackageParser.Package childPkg = pkg.childPackages.get(i);
15261            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15262            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15263            mHandler.sendMessage(msg);
15264        }
15265    }
15266
15267    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15268            PackageParser.Package pkg) {
15269        int size = pkg.activities.size();
15270        if (size == 0) {
15271            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15272                    "No activity, so no need to verify any IntentFilter!");
15273            return;
15274        }
15275
15276        final boolean hasDomainURLs = hasDomainURLs(pkg);
15277        if (!hasDomainURLs) {
15278            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15279                    "No domain URLs, so no need to verify any IntentFilter!");
15280            return;
15281        }
15282
15283        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15284                + " if any IntentFilter from the " + size
15285                + " Activities needs verification ...");
15286
15287        int count = 0;
15288        final String packageName = pkg.packageName;
15289
15290        synchronized (mPackages) {
15291            // If this is a new install and we see that we've already run verification for this
15292            // package, we have nothing to do: it means the state was restored from backup.
15293            if (!replacing) {
15294                IntentFilterVerificationInfo ivi =
15295                        mSettings.getIntentFilterVerificationLPr(packageName);
15296                if (ivi != null) {
15297                    if (DEBUG_DOMAIN_VERIFICATION) {
15298                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15299                                + ivi.getStatusString());
15300                    }
15301                    return;
15302                }
15303            }
15304
15305            // If any filters need to be verified, then all need to be.
15306            boolean needToVerify = false;
15307            for (PackageParser.Activity a : pkg.activities) {
15308                for (ActivityIntentInfo filter : a.intents) {
15309                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15310                        if (DEBUG_DOMAIN_VERIFICATION) {
15311                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15312                        }
15313                        needToVerify = true;
15314                        break;
15315                    }
15316                }
15317            }
15318
15319            if (needToVerify) {
15320                final int verificationId = mIntentFilterVerificationToken++;
15321                for (PackageParser.Activity a : pkg.activities) {
15322                    for (ActivityIntentInfo filter : a.intents) {
15323                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15324                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15325                                    "Verification needed for IntentFilter:" + filter.toString());
15326                            mIntentFilterVerifier.addOneIntentFilterVerification(
15327                                    verifierUid, userId, verificationId, filter, packageName);
15328                            count++;
15329                        }
15330                    }
15331                }
15332            }
15333        }
15334
15335        if (count > 0) {
15336            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15337                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15338                    +  " for userId:" + userId);
15339            mIntentFilterVerifier.startVerifications(userId);
15340        } else {
15341            if (DEBUG_DOMAIN_VERIFICATION) {
15342                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15343            }
15344        }
15345    }
15346
15347    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15348        final ComponentName cn  = filter.activity.getComponentName();
15349        final String packageName = cn.getPackageName();
15350
15351        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15352                packageName);
15353        if (ivi == null) {
15354            return true;
15355        }
15356        int status = ivi.getStatus();
15357        switch (status) {
15358            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15359            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15360                return true;
15361
15362            default:
15363                // Nothing to do
15364                return false;
15365        }
15366    }
15367
15368    private static boolean isMultiArch(ApplicationInfo info) {
15369        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15370    }
15371
15372    private static boolean isExternal(PackageParser.Package pkg) {
15373        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15374    }
15375
15376    private static boolean isExternal(PackageSetting ps) {
15377        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15378    }
15379
15380    private static boolean isEphemeral(PackageParser.Package pkg) {
15381        return pkg.applicationInfo.isEphemeralApp();
15382    }
15383
15384    private static boolean isEphemeral(PackageSetting ps) {
15385        return ps.pkg != null && isEphemeral(ps.pkg);
15386    }
15387
15388    private static boolean isSystemApp(PackageParser.Package pkg) {
15389        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15390    }
15391
15392    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15393        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15394    }
15395
15396    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15397        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15398    }
15399
15400    private static boolean isSystemApp(PackageSetting ps) {
15401        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15402    }
15403
15404    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15405        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15406    }
15407
15408    private int packageFlagsToInstallFlags(PackageSetting ps) {
15409        int installFlags = 0;
15410        if (isEphemeral(ps)) {
15411            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15412        }
15413        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15414            // This existing package was an external ASEC install when we have
15415            // the external flag without a UUID
15416            installFlags |= PackageManager.INSTALL_EXTERNAL;
15417        }
15418        if (ps.isForwardLocked()) {
15419            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15420        }
15421        return installFlags;
15422    }
15423
15424    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15425        if (isExternal(pkg)) {
15426            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15427                return StorageManager.UUID_PRIMARY_PHYSICAL;
15428            } else {
15429                return pkg.volumeUuid;
15430            }
15431        } else {
15432            return StorageManager.UUID_PRIVATE_INTERNAL;
15433        }
15434    }
15435
15436    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15437        if (isExternal(pkg)) {
15438            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15439                return mSettings.getExternalVersion();
15440            } else {
15441                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15442            }
15443        } else {
15444            return mSettings.getInternalVersion();
15445        }
15446    }
15447
15448    private void deleteTempPackageFiles() {
15449        final FilenameFilter filter = new FilenameFilter() {
15450            public boolean accept(File dir, String name) {
15451                return name.startsWith("vmdl") && name.endsWith(".tmp");
15452            }
15453        };
15454        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15455            file.delete();
15456        }
15457    }
15458
15459    @Override
15460    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15461            int flags) {
15462        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15463                flags);
15464    }
15465
15466    @Override
15467    public void deletePackage(final String packageName,
15468            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15469        mContext.enforceCallingOrSelfPermission(
15470                android.Manifest.permission.DELETE_PACKAGES, null);
15471        Preconditions.checkNotNull(packageName);
15472        Preconditions.checkNotNull(observer);
15473        final int uid = Binder.getCallingUid();
15474        if (!isOrphaned(packageName)
15475                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15476            try {
15477                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15478                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15479                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15480                observer.onUserActionRequired(intent);
15481            } catch (RemoteException re) {
15482            }
15483            return;
15484        }
15485        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15486        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15487        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15488            mContext.enforceCallingOrSelfPermission(
15489                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15490                    "deletePackage for user " + userId);
15491        }
15492
15493        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15494            try {
15495                observer.onPackageDeleted(packageName,
15496                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15497            } catch (RemoteException re) {
15498            }
15499            return;
15500        }
15501
15502        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15503            try {
15504                observer.onPackageDeleted(packageName,
15505                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15506            } catch (RemoteException re) {
15507            }
15508            return;
15509        }
15510
15511        if (DEBUG_REMOVE) {
15512            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15513                    + " deleteAllUsers: " + deleteAllUsers );
15514        }
15515        // Queue up an async operation since the package deletion may take a little while.
15516        mHandler.post(new Runnable() {
15517            public void run() {
15518                mHandler.removeCallbacks(this);
15519                int returnCode;
15520                if (!deleteAllUsers) {
15521                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15522                } else {
15523                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15524                    // If nobody is blocking uninstall, proceed with delete for all users
15525                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15526                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15527                    } else {
15528                        // Otherwise uninstall individually for users with blockUninstalls=false
15529                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15530                        for (int userId : users) {
15531                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15532                                returnCode = deletePackageX(packageName, userId, userFlags);
15533                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15534                                    Slog.w(TAG, "Package delete failed for user " + userId
15535                                            + ", returnCode " + returnCode);
15536                                }
15537                            }
15538                        }
15539                        // The app has only been marked uninstalled for certain users.
15540                        // We still need to report that delete was blocked
15541                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15542                    }
15543                }
15544                try {
15545                    observer.onPackageDeleted(packageName, returnCode, null);
15546                } catch (RemoteException e) {
15547                    Log.i(TAG, "Observer no longer exists.");
15548                } //end catch
15549            } //end run
15550        });
15551    }
15552
15553    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15554        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15555              || callingUid == Process.SYSTEM_UID) {
15556            return true;
15557        }
15558        final int callingUserId = UserHandle.getUserId(callingUid);
15559        // If the caller installed the pkgName, then allow it to silently uninstall.
15560        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15561            return true;
15562        }
15563
15564        // Allow package verifier to silently uninstall.
15565        if (mRequiredVerifierPackage != null &&
15566                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15567            return true;
15568        }
15569
15570        // Allow package uninstaller to silently uninstall.
15571        if (mRequiredUninstallerPackage != null &&
15572                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15573            return true;
15574        }
15575
15576        // Allow storage manager to silently uninstall.
15577        if (mStorageManagerPackage != null &&
15578                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15579            return true;
15580        }
15581        return false;
15582    }
15583
15584    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15585        int[] result = EMPTY_INT_ARRAY;
15586        for (int userId : userIds) {
15587            if (getBlockUninstallForUser(packageName, userId)) {
15588                result = ArrayUtils.appendInt(result, userId);
15589            }
15590        }
15591        return result;
15592    }
15593
15594    @Override
15595    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15596        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15597    }
15598
15599    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15600        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15601                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15602        try {
15603            if (dpm != null) {
15604                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15605                        /* callingUserOnly =*/ false);
15606                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15607                        : deviceOwnerComponentName.getPackageName();
15608                // Does the package contains the device owner?
15609                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15610                // this check is probably not needed, since DO should be registered as a device
15611                // admin on some user too. (Original bug for this: b/17657954)
15612                if (packageName.equals(deviceOwnerPackageName)) {
15613                    return true;
15614                }
15615                // Does it contain a device admin for any user?
15616                int[] users;
15617                if (userId == UserHandle.USER_ALL) {
15618                    users = sUserManager.getUserIds();
15619                } else {
15620                    users = new int[]{userId};
15621                }
15622                for (int i = 0; i < users.length; ++i) {
15623                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15624                        return true;
15625                    }
15626                }
15627            }
15628        } catch (RemoteException e) {
15629        }
15630        return false;
15631    }
15632
15633    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15634        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15635    }
15636
15637    /**
15638     *  This method is an internal method that could be get invoked either
15639     *  to delete an installed package or to clean up a failed installation.
15640     *  After deleting an installed package, a broadcast is sent to notify any
15641     *  listeners that the package has been removed. For cleaning up a failed
15642     *  installation, the broadcast is not necessary since the package's
15643     *  installation wouldn't have sent the initial broadcast either
15644     *  The key steps in deleting a package are
15645     *  deleting the package information in internal structures like mPackages,
15646     *  deleting the packages base directories through installd
15647     *  updating mSettings to reflect current status
15648     *  persisting settings for later use
15649     *  sending a broadcast if necessary
15650     */
15651    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15652        final PackageRemovedInfo info = new PackageRemovedInfo();
15653        final boolean res;
15654
15655        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15656                ? UserHandle.USER_ALL : userId;
15657
15658        if (isPackageDeviceAdmin(packageName, removeUser)) {
15659            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15660            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15661        }
15662
15663        PackageSetting uninstalledPs = null;
15664
15665        // for the uninstall-updates case and restricted profiles, remember the per-
15666        // user handle installed state
15667        int[] allUsers;
15668        synchronized (mPackages) {
15669            uninstalledPs = mSettings.mPackages.get(packageName);
15670            if (uninstalledPs == null) {
15671                Slog.w(TAG, "Not removing non-existent package " + packageName);
15672                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15673            }
15674            allUsers = sUserManager.getUserIds();
15675            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15676        }
15677
15678        final int freezeUser;
15679        if (isUpdatedSystemApp(uninstalledPs)
15680                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15681            // We're downgrading a system app, which will apply to all users, so
15682            // freeze them all during the downgrade
15683            freezeUser = UserHandle.USER_ALL;
15684        } else {
15685            freezeUser = removeUser;
15686        }
15687
15688        synchronized (mInstallLock) {
15689            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15690            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15691                    deleteFlags, "deletePackageX")) {
15692                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15693                        deleteFlags | REMOVE_CHATTY, info, true, null);
15694            }
15695            synchronized (mPackages) {
15696                if (res) {
15697                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15698                }
15699            }
15700        }
15701
15702        if (res) {
15703            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15704            info.sendPackageRemovedBroadcasts(killApp);
15705            info.sendSystemPackageUpdatedBroadcasts();
15706            info.sendSystemPackageAppearedBroadcasts();
15707        }
15708        // Force a gc here.
15709        Runtime.getRuntime().gc();
15710        // Delete the resources here after sending the broadcast to let
15711        // other processes clean up before deleting resources.
15712        if (info.args != null) {
15713            synchronized (mInstallLock) {
15714                info.args.doPostDeleteLI(true);
15715            }
15716        }
15717
15718        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15719    }
15720
15721    class PackageRemovedInfo {
15722        String removedPackage;
15723        int uid = -1;
15724        int removedAppId = -1;
15725        int[] origUsers;
15726        int[] removedUsers = null;
15727        boolean isRemovedPackageSystemUpdate = false;
15728        boolean isUpdate;
15729        boolean dataRemoved;
15730        boolean removedForAllUsers;
15731        // Clean up resources deleted packages.
15732        InstallArgs args = null;
15733        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15734        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15735
15736        void sendPackageRemovedBroadcasts(boolean killApp) {
15737            sendPackageRemovedBroadcastInternal(killApp);
15738            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15739            for (int i = 0; i < childCount; i++) {
15740                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15741                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15742            }
15743        }
15744
15745        void sendSystemPackageUpdatedBroadcasts() {
15746            if (isRemovedPackageSystemUpdate) {
15747                sendSystemPackageUpdatedBroadcastsInternal();
15748                final int childCount = (removedChildPackages != null)
15749                        ? removedChildPackages.size() : 0;
15750                for (int i = 0; i < childCount; i++) {
15751                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15752                    if (childInfo.isRemovedPackageSystemUpdate) {
15753                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15754                    }
15755                }
15756            }
15757        }
15758
15759        void sendSystemPackageAppearedBroadcasts() {
15760            final int packageCount = (appearedChildPackages != null)
15761                    ? appearedChildPackages.size() : 0;
15762            for (int i = 0; i < packageCount; i++) {
15763                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15764                for (int userId : installedInfo.newUsers) {
15765                    sendPackageAddedForUser(installedInfo.name, true,
15766                            UserHandle.getAppId(installedInfo.uid), userId);
15767                }
15768            }
15769        }
15770
15771        private void sendSystemPackageUpdatedBroadcastsInternal() {
15772            Bundle extras = new Bundle(2);
15773            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15774            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15775            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15776                    extras, 0, null, null, null);
15777            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15778                    extras, 0, null, null, null);
15779            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15780                    null, 0, removedPackage, null, null);
15781        }
15782
15783        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15784            Bundle extras = new Bundle(2);
15785            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15786            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15787            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15788            if (isUpdate || isRemovedPackageSystemUpdate) {
15789                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15790            }
15791            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15792            if (removedPackage != null) {
15793                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15794                        extras, 0, null, null, removedUsers);
15795                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15796                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15797                            removedPackage, extras, 0, null, null, removedUsers);
15798                }
15799            }
15800            if (removedAppId >= 0) {
15801                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15802                        removedUsers);
15803            }
15804        }
15805    }
15806
15807    /*
15808     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15809     * flag is not set, the data directory is removed as well.
15810     * make sure this flag is set for partially installed apps. If not its meaningless to
15811     * delete a partially installed application.
15812     */
15813    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15814            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15815        String packageName = ps.name;
15816        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15817        // Retrieve object to delete permissions for shared user later on
15818        final PackageParser.Package deletedPkg;
15819        final PackageSetting deletedPs;
15820        // reader
15821        synchronized (mPackages) {
15822            deletedPkg = mPackages.get(packageName);
15823            deletedPs = mSettings.mPackages.get(packageName);
15824            if (outInfo != null) {
15825                outInfo.removedPackage = packageName;
15826                outInfo.removedUsers = deletedPs != null
15827                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15828                        : null;
15829            }
15830        }
15831
15832        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15833
15834        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15835            final PackageParser.Package resolvedPkg;
15836            if (deletedPkg != null) {
15837                resolvedPkg = deletedPkg;
15838            } else {
15839                // We don't have a parsed package when it lives on an ejected
15840                // adopted storage device, so fake something together
15841                resolvedPkg = new PackageParser.Package(ps.name);
15842                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15843            }
15844            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15845                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15846            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15847            if (outInfo != null) {
15848                outInfo.dataRemoved = true;
15849            }
15850            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15851        }
15852
15853        // writer
15854        synchronized (mPackages) {
15855            if (deletedPs != null) {
15856                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15857                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15858                    clearDefaultBrowserIfNeeded(packageName);
15859                    if (outInfo != null) {
15860                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15861                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15862                    }
15863                    updatePermissionsLPw(deletedPs.name, null, 0);
15864                    if (deletedPs.sharedUser != null) {
15865                        // Remove permissions associated with package. Since runtime
15866                        // permissions are per user we have to kill the removed package
15867                        // or packages running under the shared user of the removed
15868                        // package if revoking the permissions requested only by the removed
15869                        // package is successful and this causes a change in gids.
15870                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15871                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15872                                    userId);
15873                            if (userIdToKill == UserHandle.USER_ALL
15874                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15875                                // If gids changed for this user, kill all affected packages.
15876                                mHandler.post(new Runnable() {
15877                                    @Override
15878                                    public void run() {
15879                                        // This has to happen with no lock held.
15880                                        killApplication(deletedPs.name, deletedPs.appId,
15881                                                KILL_APP_REASON_GIDS_CHANGED);
15882                                    }
15883                                });
15884                                break;
15885                            }
15886                        }
15887                    }
15888                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15889                }
15890                // make sure to preserve per-user disabled state if this removal was just
15891                // a downgrade of a system app to the factory package
15892                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15893                    if (DEBUG_REMOVE) {
15894                        Slog.d(TAG, "Propagating install state across downgrade");
15895                    }
15896                    for (int userId : allUserHandles) {
15897                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15898                        if (DEBUG_REMOVE) {
15899                            Slog.d(TAG, "    user " + userId + " => " + installed);
15900                        }
15901                        ps.setInstalled(installed, userId);
15902                    }
15903                }
15904            }
15905            // can downgrade to reader
15906            if (writeSettings) {
15907                // Save settings now
15908                mSettings.writeLPr();
15909            }
15910        }
15911        if (outInfo != null) {
15912            // A user ID was deleted here. Go through all users and remove it
15913            // from KeyStore.
15914            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15915        }
15916    }
15917
15918    static boolean locationIsPrivileged(File path) {
15919        try {
15920            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15921                    .getCanonicalPath();
15922            return path.getCanonicalPath().startsWith(privilegedAppDir);
15923        } catch (IOException e) {
15924            Slog.e(TAG, "Unable to access code path " + path);
15925        }
15926        return false;
15927    }
15928
15929    /*
15930     * Tries to delete system package.
15931     */
15932    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15933            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15934            boolean writeSettings) {
15935        if (deletedPs.parentPackageName != null) {
15936            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15937            return false;
15938        }
15939
15940        final boolean applyUserRestrictions
15941                = (allUserHandles != null) && (outInfo.origUsers != null);
15942        final PackageSetting disabledPs;
15943        // Confirm if the system package has been updated
15944        // An updated system app can be deleted. This will also have to restore
15945        // the system pkg from system partition
15946        // reader
15947        synchronized (mPackages) {
15948            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15949        }
15950
15951        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15952                + " disabledPs=" + disabledPs);
15953
15954        if (disabledPs == null) {
15955            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15956            return false;
15957        } else if (DEBUG_REMOVE) {
15958            Slog.d(TAG, "Deleting system pkg from data partition");
15959        }
15960
15961        if (DEBUG_REMOVE) {
15962            if (applyUserRestrictions) {
15963                Slog.d(TAG, "Remembering install states:");
15964                for (int userId : allUserHandles) {
15965                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15966                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15967                }
15968            }
15969        }
15970
15971        // Delete the updated package
15972        outInfo.isRemovedPackageSystemUpdate = true;
15973        if (outInfo.removedChildPackages != null) {
15974            final int childCount = (deletedPs.childPackageNames != null)
15975                    ? deletedPs.childPackageNames.size() : 0;
15976            for (int i = 0; i < childCount; i++) {
15977                String childPackageName = deletedPs.childPackageNames.get(i);
15978                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15979                        .contains(childPackageName)) {
15980                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15981                            childPackageName);
15982                    if (childInfo != null) {
15983                        childInfo.isRemovedPackageSystemUpdate = true;
15984                    }
15985                }
15986            }
15987        }
15988
15989        if (disabledPs.versionCode < deletedPs.versionCode) {
15990            // Delete data for downgrades
15991            flags &= ~PackageManager.DELETE_KEEP_DATA;
15992        } else {
15993            // Preserve data by setting flag
15994            flags |= PackageManager.DELETE_KEEP_DATA;
15995        }
15996
15997        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15998                outInfo, writeSettings, disabledPs.pkg);
15999        if (!ret) {
16000            return false;
16001        }
16002
16003        // writer
16004        synchronized (mPackages) {
16005            // Reinstate the old system package
16006            enableSystemPackageLPw(disabledPs.pkg);
16007            // Remove any native libraries from the upgraded package.
16008            removeNativeBinariesLI(deletedPs);
16009        }
16010
16011        // Install the system package
16012        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16013        int parseFlags = mDefParseFlags
16014                | PackageParser.PARSE_MUST_BE_APK
16015                | PackageParser.PARSE_IS_SYSTEM
16016                | PackageParser.PARSE_IS_SYSTEM_DIR;
16017        if (locationIsPrivileged(disabledPs.codePath)) {
16018            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16019        }
16020
16021        final PackageParser.Package newPkg;
16022        try {
16023            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16024        } catch (PackageManagerException e) {
16025            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16026                    + e.getMessage());
16027            return false;
16028        }
16029        try {
16030            // update shared libraries for the newly re-installed system package
16031            updateSharedLibrariesLPw(newPkg, null);
16032        } catch (PackageManagerException e) {
16033            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16034        }
16035
16036        prepareAppDataAfterInstallLIF(newPkg);
16037
16038        // writer
16039        synchronized (mPackages) {
16040            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16041
16042            // Propagate the permissions state as we do not want to drop on the floor
16043            // runtime permissions. The update permissions method below will take
16044            // care of removing obsolete permissions and grant install permissions.
16045            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16046            updatePermissionsLPw(newPkg.packageName, newPkg,
16047                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16048
16049            if (applyUserRestrictions) {
16050                if (DEBUG_REMOVE) {
16051                    Slog.d(TAG, "Propagating install state across reinstall");
16052                }
16053                for (int userId : allUserHandles) {
16054                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16055                    if (DEBUG_REMOVE) {
16056                        Slog.d(TAG, "    user " + userId + " => " + installed);
16057                    }
16058                    ps.setInstalled(installed, userId);
16059
16060                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16061                }
16062                // Regardless of writeSettings we need to ensure that this restriction
16063                // state propagation is persisted
16064                mSettings.writeAllUsersPackageRestrictionsLPr();
16065            }
16066            // can downgrade to reader here
16067            if (writeSettings) {
16068                mSettings.writeLPr();
16069            }
16070        }
16071        return true;
16072    }
16073
16074    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16075            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16076            PackageRemovedInfo outInfo, boolean writeSettings,
16077            PackageParser.Package replacingPackage) {
16078        synchronized (mPackages) {
16079            if (outInfo != null) {
16080                outInfo.uid = ps.appId;
16081            }
16082
16083            if (outInfo != null && outInfo.removedChildPackages != null) {
16084                final int childCount = (ps.childPackageNames != null)
16085                        ? ps.childPackageNames.size() : 0;
16086                for (int i = 0; i < childCount; i++) {
16087                    String childPackageName = ps.childPackageNames.get(i);
16088                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16089                    if (childPs == null) {
16090                        return false;
16091                    }
16092                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16093                            childPackageName);
16094                    if (childInfo != null) {
16095                        childInfo.uid = childPs.appId;
16096                    }
16097                }
16098            }
16099        }
16100
16101        // Delete package data from internal structures and also remove data if flag is set
16102        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16103
16104        // Delete the child packages data
16105        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16106        for (int i = 0; i < childCount; i++) {
16107            PackageSetting childPs;
16108            synchronized (mPackages) {
16109                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16110            }
16111            if (childPs != null) {
16112                PackageRemovedInfo childOutInfo = (outInfo != null
16113                        && outInfo.removedChildPackages != null)
16114                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16115                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16116                        && (replacingPackage != null
16117                        && !replacingPackage.hasChildPackage(childPs.name))
16118                        ? flags & ~DELETE_KEEP_DATA : flags;
16119                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16120                        deleteFlags, writeSettings);
16121            }
16122        }
16123
16124        // Delete application code and resources only for parent packages
16125        if (ps.parentPackageName == null) {
16126            if (deleteCodeAndResources && (outInfo != null)) {
16127                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16128                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16129                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16130            }
16131        }
16132
16133        return true;
16134    }
16135
16136    @Override
16137    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16138            int userId) {
16139        mContext.enforceCallingOrSelfPermission(
16140                android.Manifest.permission.DELETE_PACKAGES, null);
16141        synchronized (mPackages) {
16142            PackageSetting ps = mSettings.mPackages.get(packageName);
16143            if (ps == null) {
16144                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16145                return false;
16146            }
16147            if (!ps.getInstalled(userId)) {
16148                // Can't block uninstall for an app that is not installed or enabled.
16149                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16150                return false;
16151            }
16152            ps.setBlockUninstall(blockUninstall, userId);
16153            mSettings.writePackageRestrictionsLPr(userId);
16154        }
16155        return true;
16156    }
16157
16158    @Override
16159    public boolean getBlockUninstallForUser(String packageName, int userId) {
16160        synchronized (mPackages) {
16161            PackageSetting ps = mSettings.mPackages.get(packageName);
16162            if (ps == null) {
16163                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16164                return false;
16165            }
16166            return ps.getBlockUninstall(userId);
16167        }
16168    }
16169
16170    @Override
16171    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16172        int callingUid = Binder.getCallingUid();
16173        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16174            throw new SecurityException(
16175                    "setRequiredForSystemUser can only be run by the system or root");
16176        }
16177        synchronized (mPackages) {
16178            PackageSetting ps = mSettings.mPackages.get(packageName);
16179            if (ps == null) {
16180                Log.w(TAG, "Package doesn't exist: " + packageName);
16181                return false;
16182            }
16183            if (systemUserApp) {
16184                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16185            } else {
16186                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16187            }
16188            mSettings.writeLPr();
16189        }
16190        return true;
16191    }
16192
16193    /*
16194     * This method handles package deletion in general
16195     */
16196    private boolean deletePackageLIF(String packageName, UserHandle user,
16197            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16198            PackageRemovedInfo outInfo, boolean writeSettings,
16199            PackageParser.Package replacingPackage) {
16200        if (packageName == null) {
16201            Slog.w(TAG, "Attempt to delete null packageName.");
16202            return false;
16203        }
16204
16205        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16206
16207        PackageSetting ps;
16208
16209        synchronized (mPackages) {
16210            ps = mSettings.mPackages.get(packageName);
16211            if (ps == null) {
16212                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16213                return false;
16214            }
16215
16216            if (ps.parentPackageName != null && (!isSystemApp(ps)
16217                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16218                if (DEBUG_REMOVE) {
16219                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16220                            + ((user == null) ? UserHandle.USER_ALL : user));
16221                }
16222                final int removedUserId = (user != null) ? user.getIdentifier()
16223                        : UserHandle.USER_ALL;
16224                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16225                    return false;
16226                }
16227                markPackageUninstalledForUserLPw(ps, user);
16228                scheduleWritePackageRestrictionsLocked(user);
16229                return true;
16230            }
16231        }
16232
16233        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16234                && user.getIdentifier() != UserHandle.USER_ALL)) {
16235            // The caller is asking that the package only be deleted for a single
16236            // user.  To do this, we just mark its uninstalled state and delete
16237            // its data. If this is a system app, we only allow this to happen if
16238            // they have set the special DELETE_SYSTEM_APP which requests different
16239            // semantics than normal for uninstalling system apps.
16240            markPackageUninstalledForUserLPw(ps, user);
16241
16242            if (!isSystemApp(ps)) {
16243                // Do not uninstall the APK if an app should be cached
16244                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16245                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16246                    // Other user still have this package installed, so all
16247                    // we need to do is clear this user's data and save that
16248                    // it is uninstalled.
16249                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16250                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16251                        return false;
16252                    }
16253                    scheduleWritePackageRestrictionsLocked(user);
16254                    return true;
16255                } else {
16256                    // We need to set it back to 'installed' so the uninstall
16257                    // broadcasts will be sent correctly.
16258                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16259                    ps.setInstalled(true, user.getIdentifier());
16260                }
16261            } else {
16262                // This is a system app, so we assume that the
16263                // other users still have this package installed, so all
16264                // we need to do is clear this user's data and save that
16265                // it is uninstalled.
16266                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16267                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16268                    return false;
16269                }
16270                scheduleWritePackageRestrictionsLocked(user);
16271                return true;
16272            }
16273        }
16274
16275        // If we are deleting a composite package for all users, keep track
16276        // of result for each child.
16277        if (ps.childPackageNames != null && outInfo != null) {
16278            synchronized (mPackages) {
16279                final int childCount = ps.childPackageNames.size();
16280                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16281                for (int i = 0; i < childCount; i++) {
16282                    String childPackageName = ps.childPackageNames.get(i);
16283                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16284                    childInfo.removedPackage = childPackageName;
16285                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16286                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16287                    if (childPs != null) {
16288                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16289                    }
16290                }
16291            }
16292        }
16293
16294        boolean ret = false;
16295        if (isSystemApp(ps)) {
16296            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16297            // When an updated system application is deleted we delete the existing resources
16298            // as well and fall back to existing code in system partition
16299            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16300        } else {
16301            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16302            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16303                    outInfo, writeSettings, replacingPackage);
16304        }
16305
16306        // Take a note whether we deleted the package for all users
16307        if (outInfo != null) {
16308            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16309            if (outInfo.removedChildPackages != null) {
16310                synchronized (mPackages) {
16311                    final int childCount = outInfo.removedChildPackages.size();
16312                    for (int i = 0; i < childCount; i++) {
16313                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16314                        if (childInfo != null) {
16315                            childInfo.removedForAllUsers = mPackages.get(
16316                                    childInfo.removedPackage) == null;
16317                        }
16318                    }
16319                }
16320            }
16321            // If we uninstalled an update to a system app there may be some
16322            // child packages that appeared as they are declared in the system
16323            // app but were not declared in the update.
16324            if (isSystemApp(ps)) {
16325                synchronized (mPackages) {
16326                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16327                    final int childCount = (updatedPs.childPackageNames != null)
16328                            ? updatedPs.childPackageNames.size() : 0;
16329                    for (int i = 0; i < childCount; i++) {
16330                        String childPackageName = updatedPs.childPackageNames.get(i);
16331                        if (outInfo.removedChildPackages == null
16332                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16333                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16334                            if (childPs == null) {
16335                                continue;
16336                            }
16337                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16338                            installRes.name = childPackageName;
16339                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16340                            installRes.pkg = mPackages.get(childPackageName);
16341                            installRes.uid = childPs.pkg.applicationInfo.uid;
16342                            if (outInfo.appearedChildPackages == null) {
16343                                outInfo.appearedChildPackages = new ArrayMap<>();
16344                            }
16345                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16346                        }
16347                    }
16348                }
16349            }
16350        }
16351
16352        return ret;
16353    }
16354
16355    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16356        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16357                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16358        for (int nextUserId : userIds) {
16359            if (DEBUG_REMOVE) {
16360                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16361            }
16362            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16363                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16364                    false /*hidden*/, false /*suspended*/, null, null, null,
16365                    false /*blockUninstall*/,
16366                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16367        }
16368    }
16369
16370    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16371            PackageRemovedInfo outInfo) {
16372        final PackageParser.Package pkg;
16373        synchronized (mPackages) {
16374            pkg = mPackages.get(ps.name);
16375        }
16376
16377        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16378                : new int[] {userId};
16379        for (int nextUserId : userIds) {
16380            if (DEBUG_REMOVE) {
16381                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16382                        + nextUserId);
16383            }
16384
16385            destroyAppDataLIF(pkg, userId,
16386                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16387            destroyAppProfilesLIF(pkg, userId);
16388            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16389            schedulePackageCleaning(ps.name, nextUserId, false);
16390            synchronized (mPackages) {
16391                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16392                    scheduleWritePackageRestrictionsLocked(nextUserId);
16393                }
16394                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16395            }
16396        }
16397
16398        if (outInfo != null) {
16399            outInfo.removedPackage = ps.name;
16400            outInfo.removedAppId = ps.appId;
16401            outInfo.removedUsers = userIds;
16402        }
16403
16404        return true;
16405    }
16406
16407    private final class ClearStorageConnection implements ServiceConnection {
16408        IMediaContainerService mContainerService;
16409
16410        @Override
16411        public void onServiceConnected(ComponentName name, IBinder service) {
16412            synchronized (this) {
16413                mContainerService = IMediaContainerService.Stub.asInterface(service);
16414                notifyAll();
16415            }
16416        }
16417
16418        @Override
16419        public void onServiceDisconnected(ComponentName name) {
16420        }
16421    }
16422
16423    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16424        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16425
16426        final boolean mounted;
16427        if (Environment.isExternalStorageEmulated()) {
16428            mounted = true;
16429        } else {
16430            final String status = Environment.getExternalStorageState();
16431
16432            mounted = status.equals(Environment.MEDIA_MOUNTED)
16433                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16434        }
16435
16436        if (!mounted) {
16437            return;
16438        }
16439
16440        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16441        int[] users;
16442        if (userId == UserHandle.USER_ALL) {
16443            users = sUserManager.getUserIds();
16444        } else {
16445            users = new int[] { userId };
16446        }
16447        final ClearStorageConnection conn = new ClearStorageConnection();
16448        if (mContext.bindServiceAsUser(
16449                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16450            try {
16451                for (int curUser : users) {
16452                    long timeout = SystemClock.uptimeMillis() + 5000;
16453                    synchronized (conn) {
16454                        long now;
16455                        while (conn.mContainerService == null &&
16456                                (now = SystemClock.uptimeMillis()) < timeout) {
16457                            try {
16458                                conn.wait(timeout - now);
16459                            } catch (InterruptedException e) {
16460                            }
16461                        }
16462                    }
16463                    if (conn.mContainerService == null) {
16464                        return;
16465                    }
16466
16467                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16468                    clearDirectory(conn.mContainerService,
16469                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16470                    if (allData) {
16471                        clearDirectory(conn.mContainerService,
16472                                userEnv.buildExternalStorageAppDataDirs(packageName));
16473                        clearDirectory(conn.mContainerService,
16474                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16475                    }
16476                }
16477            } finally {
16478                mContext.unbindService(conn);
16479            }
16480        }
16481    }
16482
16483    @Override
16484    public void clearApplicationProfileData(String packageName) {
16485        enforceSystemOrRoot("Only the system can clear all profile data");
16486
16487        final PackageParser.Package pkg;
16488        synchronized (mPackages) {
16489            pkg = mPackages.get(packageName);
16490        }
16491
16492        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16493            synchronized (mInstallLock) {
16494                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16495            }
16496        }
16497    }
16498
16499    @Override
16500    public void clearApplicationUserData(final String packageName,
16501            final IPackageDataObserver observer, final int userId) {
16502        mContext.enforceCallingOrSelfPermission(
16503                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16504
16505        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16506                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16507
16508        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16509            throw new SecurityException("Cannot clear data for a protected package: "
16510                    + packageName);
16511        }
16512        // Queue up an async operation since the package deletion may take a little while.
16513        mHandler.post(new Runnable() {
16514            public void run() {
16515                mHandler.removeCallbacks(this);
16516                final boolean succeeded;
16517                try (PackageFreezer freezer = freezePackage(packageName,
16518                        "clearApplicationUserData")) {
16519                    synchronized (mInstallLock) {
16520                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16521                    }
16522                    clearExternalStorageDataSync(packageName, userId, true);
16523                }
16524                if (succeeded) {
16525                    // invoke DeviceStorageMonitor's update method to clear any notifications
16526                    DeviceStorageMonitorInternal dsm = LocalServices
16527                            .getService(DeviceStorageMonitorInternal.class);
16528                    if (dsm != null) {
16529                        dsm.checkMemory();
16530                    }
16531                }
16532                if(observer != null) {
16533                    try {
16534                        observer.onRemoveCompleted(packageName, succeeded);
16535                    } catch (RemoteException e) {
16536                        Log.i(TAG, "Observer no longer exists.");
16537                    }
16538                } //end if observer
16539            } //end run
16540        });
16541    }
16542
16543    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16544        if (packageName == null) {
16545            Slog.w(TAG, "Attempt to delete null packageName.");
16546            return false;
16547        }
16548
16549        // Try finding details about the requested package
16550        PackageParser.Package pkg;
16551        synchronized (mPackages) {
16552            pkg = mPackages.get(packageName);
16553            if (pkg == null) {
16554                final PackageSetting ps = mSettings.mPackages.get(packageName);
16555                if (ps != null) {
16556                    pkg = ps.pkg;
16557                }
16558            }
16559
16560            if (pkg == null) {
16561                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16562                return false;
16563            }
16564
16565            PackageSetting ps = (PackageSetting) pkg.mExtras;
16566            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16567        }
16568
16569        clearAppDataLIF(pkg, userId,
16570                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16571
16572        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16573        removeKeystoreDataIfNeeded(userId, appId);
16574
16575        UserManagerInternal umInternal = getUserManagerInternal();
16576        final int flags;
16577        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16578            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16579        } else if (umInternal.isUserRunning(userId)) {
16580            flags = StorageManager.FLAG_STORAGE_DE;
16581        } else {
16582            flags = 0;
16583        }
16584        prepareAppDataContentsLIF(pkg, userId, flags);
16585
16586        return true;
16587    }
16588
16589    /**
16590     * Reverts user permission state changes (permissions and flags) in
16591     * all packages for a given user.
16592     *
16593     * @param userId The device user for which to do a reset.
16594     */
16595    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16596        final int packageCount = mPackages.size();
16597        for (int i = 0; i < packageCount; i++) {
16598            PackageParser.Package pkg = mPackages.valueAt(i);
16599            PackageSetting ps = (PackageSetting) pkg.mExtras;
16600            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16601        }
16602    }
16603
16604    private void resetNetworkPolicies(int userId) {
16605        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16606    }
16607
16608    /**
16609     * Reverts user permission state changes (permissions and flags).
16610     *
16611     * @param ps The package for which to reset.
16612     * @param userId The device user for which to do a reset.
16613     */
16614    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16615            final PackageSetting ps, final int userId) {
16616        if (ps.pkg == null) {
16617            return;
16618        }
16619
16620        // These are flags that can change base on user actions.
16621        final int userSettableMask = FLAG_PERMISSION_USER_SET
16622                | FLAG_PERMISSION_USER_FIXED
16623                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16624                | FLAG_PERMISSION_REVIEW_REQUIRED;
16625
16626        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16627                | FLAG_PERMISSION_POLICY_FIXED;
16628
16629        boolean writeInstallPermissions = false;
16630        boolean writeRuntimePermissions = false;
16631
16632        final int permissionCount = ps.pkg.requestedPermissions.size();
16633        for (int i = 0; i < permissionCount; i++) {
16634            String permission = ps.pkg.requestedPermissions.get(i);
16635
16636            BasePermission bp = mSettings.mPermissions.get(permission);
16637            if (bp == null) {
16638                continue;
16639            }
16640
16641            // If shared user we just reset the state to which only this app contributed.
16642            if (ps.sharedUser != null) {
16643                boolean used = false;
16644                final int packageCount = ps.sharedUser.packages.size();
16645                for (int j = 0; j < packageCount; j++) {
16646                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16647                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16648                            && pkg.pkg.requestedPermissions.contains(permission)) {
16649                        used = true;
16650                        break;
16651                    }
16652                }
16653                if (used) {
16654                    continue;
16655                }
16656            }
16657
16658            PermissionsState permissionsState = ps.getPermissionsState();
16659
16660            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16661
16662            // Always clear the user settable flags.
16663            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16664                    bp.name) != null;
16665            // If permission review is enabled and this is a legacy app, mark the
16666            // permission as requiring a review as this is the initial state.
16667            int flags = 0;
16668            if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
16669                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16670                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16671            }
16672            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16673                if (hasInstallState) {
16674                    writeInstallPermissions = true;
16675                } else {
16676                    writeRuntimePermissions = true;
16677                }
16678            }
16679
16680            // Below is only runtime permission handling.
16681            if (!bp.isRuntime()) {
16682                continue;
16683            }
16684
16685            // Never clobber system or policy.
16686            if ((oldFlags & policyOrSystemFlags) != 0) {
16687                continue;
16688            }
16689
16690            // If this permission was granted by default, make sure it is.
16691            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16692                if (permissionsState.grantRuntimePermission(bp, userId)
16693                        != PERMISSION_OPERATION_FAILURE) {
16694                    writeRuntimePermissions = true;
16695                }
16696            // If permission review is enabled the permissions for a legacy apps
16697            // are represented as constantly granted runtime ones, so don't revoke.
16698            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16699                // Otherwise, reset the permission.
16700                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16701                switch (revokeResult) {
16702                    case PERMISSION_OPERATION_SUCCESS:
16703                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16704                        writeRuntimePermissions = true;
16705                        final int appId = ps.appId;
16706                        mHandler.post(new Runnable() {
16707                            @Override
16708                            public void run() {
16709                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16710                            }
16711                        });
16712                    } break;
16713                }
16714            }
16715        }
16716
16717        // Synchronously write as we are taking permissions away.
16718        if (writeRuntimePermissions) {
16719            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16720        }
16721
16722        // Synchronously write as we are taking permissions away.
16723        if (writeInstallPermissions) {
16724            mSettings.writeLPr();
16725        }
16726    }
16727
16728    /**
16729     * Remove entries from the keystore daemon. Will only remove it if the
16730     * {@code appId} is valid.
16731     */
16732    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16733        if (appId < 0) {
16734            return;
16735        }
16736
16737        final KeyStore keyStore = KeyStore.getInstance();
16738        if (keyStore != null) {
16739            if (userId == UserHandle.USER_ALL) {
16740                for (final int individual : sUserManager.getUserIds()) {
16741                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16742                }
16743            } else {
16744                keyStore.clearUid(UserHandle.getUid(userId, appId));
16745            }
16746        } else {
16747            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16748        }
16749    }
16750
16751    @Override
16752    public void deleteApplicationCacheFiles(final String packageName,
16753            final IPackageDataObserver observer) {
16754        final int userId = UserHandle.getCallingUserId();
16755        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16756    }
16757
16758    @Override
16759    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16760            final IPackageDataObserver observer) {
16761        mContext.enforceCallingOrSelfPermission(
16762                android.Manifest.permission.DELETE_CACHE_FILES, null);
16763        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16764                /* requireFullPermission= */ true, /* checkShell= */ false,
16765                "delete application cache files");
16766
16767        final PackageParser.Package pkg;
16768        synchronized (mPackages) {
16769            pkg = mPackages.get(packageName);
16770        }
16771
16772        // Queue up an async operation since the package deletion may take a little while.
16773        mHandler.post(new Runnable() {
16774            public void run() {
16775                synchronized (mInstallLock) {
16776                    final int flags = StorageManager.FLAG_STORAGE_DE
16777                            | StorageManager.FLAG_STORAGE_CE;
16778                    // We're only clearing cache files, so we don't care if the
16779                    // app is unfrozen and still able to run
16780                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16781                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16782                }
16783                clearExternalStorageDataSync(packageName, userId, false);
16784                if (observer != null) {
16785                    try {
16786                        observer.onRemoveCompleted(packageName, true);
16787                    } catch (RemoteException e) {
16788                        Log.i(TAG, "Observer no longer exists.");
16789                    }
16790                }
16791            }
16792        });
16793    }
16794
16795    @Override
16796    public void getPackageSizeInfo(final String packageName, int userHandle,
16797            final IPackageStatsObserver observer) {
16798        mContext.enforceCallingOrSelfPermission(
16799                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16800        if (packageName == null) {
16801            throw new IllegalArgumentException("Attempt to get size of null packageName");
16802        }
16803
16804        PackageStats stats = new PackageStats(packageName, userHandle);
16805
16806        /*
16807         * Queue up an async operation since the package measurement may take a
16808         * little while.
16809         */
16810        Message msg = mHandler.obtainMessage(INIT_COPY);
16811        msg.obj = new MeasureParams(stats, observer);
16812        mHandler.sendMessage(msg);
16813    }
16814
16815    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16816        final PackageSetting ps;
16817        synchronized (mPackages) {
16818            ps = mSettings.mPackages.get(packageName);
16819            if (ps == null) {
16820                Slog.w(TAG, "Failed to find settings for " + packageName);
16821                return false;
16822            }
16823        }
16824
16825        final String[] packageNames = { packageName };
16826        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
16827        final String[] codePaths = { ps.codePathString };
16828
16829        try {
16830            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
16831                    ps.appId, ceDataInodes, codePaths, stats);
16832
16833            // For now, ignore code size of packages on system partition
16834            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16835                stats.codeSize = 0;
16836            }
16837
16838            // External clients expect these to be tracked separately
16839            stats.dataSize -= stats.cacheSize;
16840
16841        } catch (InstallerException e) {
16842            Slog.w(TAG, String.valueOf(e));
16843            return false;
16844        }
16845
16846        return true;
16847    }
16848
16849    private int getUidTargetSdkVersionLockedLPr(int uid) {
16850        Object obj = mSettings.getUserIdLPr(uid);
16851        if (obj instanceof SharedUserSetting) {
16852            final SharedUserSetting sus = (SharedUserSetting) obj;
16853            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16854            final Iterator<PackageSetting> it = sus.packages.iterator();
16855            while (it.hasNext()) {
16856                final PackageSetting ps = it.next();
16857                if (ps.pkg != null) {
16858                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16859                    if (v < vers) vers = v;
16860                }
16861            }
16862            return vers;
16863        } else if (obj instanceof PackageSetting) {
16864            final PackageSetting ps = (PackageSetting) obj;
16865            if (ps.pkg != null) {
16866                return ps.pkg.applicationInfo.targetSdkVersion;
16867            }
16868        }
16869        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16870    }
16871
16872    @Override
16873    public void addPreferredActivity(IntentFilter filter, int match,
16874            ComponentName[] set, ComponentName activity, int userId) {
16875        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16876                "Adding preferred");
16877    }
16878
16879    private void addPreferredActivityInternal(IntentFilter filter, int match,
16880            ComponentName[] set, ComponentName activity, boolean always, int userId,
16881            String opname) {
16882        // writer
16883        int callingUid = Binder.getCallingUid();
16884        enforceCrossUserPermission(callingUid, userId,
16885                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16886        if (filter.countActions() == 0) {
16887            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16888            return;
16889        }
16890        synchronized (mPackages) {
16891            if (mContext.checkCallingOrSelfPermission(
16892                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16893                    != PackageManager.PERMISSION_GRANTED) {
16894                if (getUidTargetSdkVersionLockedLPr(callingUid)
16895                        < Build.VERSION_CODES.FROYO) {
16896                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16897                            + callingUid);
16898                    return;
16899                }
16900                mContext.enforceCallingOrSelfPermission(
16901                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16902            }
16903
16904            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16905            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16906                    + userId + ":");
16907            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16908            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16909            scheduleWritePackageRestrictionsLocked(userId);
16910            postPreferredActivityChangedBroadcast(userId);
16911        }
16912    }
16913
16914    private void postPreferredActivityChangedBroadcast(int userId) {
16915        mHandler.post(() -> {
16916            final IActivityManager am = ActivityManagerNative.getDefault();
16917            if (am == null) {
16918                return;
16919            }
16920
16921            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16922            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16923            try {
16924                am.broadcastIntent(null, intent, null, null,
16925                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
16926                        null, false, false, userId);
16927            } catch (RemoteException e) {
16928            }
16929        });
16930    }
16931
16932    @Override
16933    public void replacePreferredActivity(IntentFilter filter, int match,
16934            ComponentName[] set, ComponentName activity, int userId) {
16935        if (filter.countActions() != 1) {
16936            throw new IllegalArgumentException(
16937                    "replacePreferredActivity expects filter to have only 1 action.");
16938        }
16939        if (filter.countDataAuthorities() != 0
16940                || filter.countDataPaths() != 0
16941                || filter.countDataSchemes() > 1
16942                || filter.countDataTypes() != 0) {
16943            throw new IllegalArgumentException(
16944                    "replacePreferredActivity expects filter to have no data authorities, " +
16945                    "paths, or types; and at most one scheme.");
16946        }
16947
16948        final int callingUid = Binder.getCallingUid();
16949        enforceCrossUserPermission(callingUid, userId,
16950                true /* requireFullPermission */, false /* checkShell */,
16951                "replace preferred activity");
16952        synchronized (mPackages) {
16953            if (mContext.checkCallingOrSelfPermission(
16954                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16955                    != PackageManager.PERMISSION_GRANTED) {
16956                if (getUidTargetSdkVersionLockedLPr(callingUid)
16957                        < Build.VERSION_CODES.FROYO) {
16958                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16959                            + Binder.getCallingUid());
16960                    return;
16961                }
16962                mContext.enforceCallingOrSelfPermission(
16963                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16964            }
16965
16966            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16967            if (pir != null) {
16968                // Get all of the existing entries that exactly match this filter.
16969                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16970                if (existing != null && existing.size() == 1) {
16971                    PreferredActivity cur = existing.get(0);
16972                    if (DEBUG_PREFERRED) {
16973                        Slog.i(TAG, "Checking replace of preferred:");
16974                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16975                        if (!cur.mPref.mAlways) {
16976                            Slog.i(TAG, "  -- CUR; not mAlways!");
16977                        } else {
16978                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16979                            Slog.i(TAG, "  -- CUR: mSet="
16980                                    + Arrays.toString(cur.mPref.mSetComponents));
16981                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16982                            Slog.i(TAG, "  -- NEW: mMatch="
16983                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16984                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16985                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16986                        }
16987                    }
16988                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16989                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16990                            && cur.mPref.sameSet(set)) {
16991                        // Setting the preferred activity to what it happens to be already
16992                        if (DEBUG_PREFERRED) {
16993                            Slog.i(TAG, "Replacing with same preferred activity "
16994                                    + cur.mPref.mShortComponent + " for user "
16995                                    + userId + ":");
16996                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16997                        }
16998                        return;
16999                    }
17000                }
17001
17002                if (existing != null) {
17003                    if (DEBUG_PREFERRED) {
17004                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17005                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17006                    }
17007                    for (int i = 0; i < existing.size(); i++) {
17008                        PreferredActivity pa = existing.get(i);
17009                        if (DEBUG_PREFERRED) {
17010                            Slog.i(TAG, "Removing existing preferred activity "
17011                                    + pa.mPref.mComponent + ":");
17012                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17013                        }
17014                        pir.removeFilter(pa);
17015                    }
17016                }
17017            }
17018            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17019                    "Replacing preferred");
17020        }
17021    }
17022
17023    @Override
17024    public void clearPackagePreferredActivities(String packageName) {
17025        final int uid = Binder.getCallingUid();
17026        // writer
17027        synchronized (mPackages) {
17028            PackageParser.Package pkg = mPackages.get(packageName);
17029            if (pkg == null || pkg.applicationInfo.uid != uid) {
17030                if (mContext.checkCallingOrSelfPermission(
17031                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17032                        != PackageManager.PERMISSION_GRANTED) {
17033                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17034                            < Build.VERSION_CODES.FROYO) {
17035                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17036                                + Binder.getCallingUid());
17037                        return;
17038                    }
17039                    mContext.enforceCallingOrSelfPermission(
17040                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17041                }
17042            }
17043
17044            int user = UserHandle.getCallingUserId();
17045            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17046                scheduleWritePackageRestrictionsLocked(user);
17047            }
17048        }
17049    }
17050
17051    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17052    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17053        ArrayList<PreferredActivity> removed = null;
17054        boolean changed = false;
17055        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17056            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17057            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17058            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17059                continue;
17060            }
17061            Iterator<PreferredActivity> it = pir.filterIterator();
17062            while (it.hasNext()) {
17063                PreferredActivity pa = it.next();
17064                // Mark entry for removal only if it matches the package name
17065                // and the entry is of type "always".
17066                if (packageName == null ||
17067                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17068                                && pa.mPref.mAlways)) {
17069                    if (removed == null) {
17070                        removed = new ArrayList<PreferredActivity>();
17071                    }
17072                    removed.add(pa);
17073                }
17074            }
17075            if (removed != null) {
17076                for (int j=0; j<removed.size(); j++) {
17077                    PreferredActivity pa = removed.get(j);
17078                    pir.removeFilter(pa);
17079                }
17080                changed = true;
17081            }
17082        }
17083        if (changed) {
17084            postPreferredActivityChangedBroadcast(userId);
17085        }
17086        return changed;
17087    }
17088
17089    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17090    private void clearIntentFilterVerificationsLPw(int userId) {
17091        final int packageCount = mPackages.size();
17092        for (int i = 0; i < packageCount; i++) {
17093            PackageParser.Package pkg = mPackages.valueAt(i);
17094            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17095        }
17096    }
17097
17098    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17099    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17100        if (userId == UserHandle.USER_ALL) {
17101            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17102                    sUserManager.getUserIds())) {
17103                for (int oneUserId : sUserManager.getUserIds()) {
17104                    scheduleWritePackageRestrictionsLocked(oneUserId);
17105                }
17106            }
17107        } else {
17108            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17109                scheduleWritePackageRestrictionsLocked(userId);
17110            }
17111        }
17112    }
17113
17114    void clearDefaultBrowserIfNeeded(String packageName) {
17115        for (int oneUserId : sUserManager.getUserIds()) {
17116            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17117            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17118            if (packageName.equals(defaultBrowserPackageName)) {
17119                setDefaultBrowserPackageName(null, oneUserId);
17120            }
17121        }
17122    }
17123
17124    @Override
17125    public void resetApplicationPreferences(int userId) {
17126        mContext.enforceCallingOrSelfPermission(
17127                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17128        final long identity = Binder.clearCallingIdentity();
17129        // writer
17130        try {
17131            synchronized (mPackages) {
17132                clearPackagePreferredActivitiesLPw(null, userId);
17133                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17134                // TODO: We have to reset the default SMS and Phone. This requires
17135                // significant refactoring to keep all default apps in the package
17136                // manager (cleaner but more work) or have the services provide
17137                // callbacks to the package manager to request a default app reset.
17138                applyFactoryDefaultBrowserLPw(userId);
17139                clearIntentFilterVerificationsLPw(userId);
17140                primeDomainVerificationsLPw(userId);
17141                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17142                scheduleWritePackageRestrictionsLocked(userId);
17143            }
17144            resetNetworkPolicies(userId);
17145        } finally {
17146            Binder.restoreCallingIdentity(identity);
17147        }
17148    }
17149
17150    @Override
17151    public int getPreferredActivities(List<IntentFilter> outFilters,
17152            List<ComponentName> outActivities, String packageName) {
17153
17154        int num = 0;
17155        final int userId = UserHandle.getCallingUserId();
17156        // reader
17157        synchronized (mPackages) {
17158            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17159            if (pir != null) {
17160                final Iterator<PreferredActivity> it = pir.filterIterator();
17161                while (it.hasNext()) {
17162                    final PreferredActivity pa = it.next();
17163                    if (packageName == null
17164                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17165                                    && pa.mPref.mAlways)) {
17166                        if (outFilters != null) {
17167                            outFilters.add(new IntentFilter(pa));
17168                        }
17169                        if (outActivities != null) {
17170                            outActivities.add(pa.mPref.mComponent);
17171                        }
17172                    }
17173                }
17174            }
17175        }
17176
17177        return num;
17178    }
17179
17180    @Override
17181    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17182            int userId) {
17183        int callingUid = Binder.getCallingUid();
17184        if (callingUid != Process.SYSTEM_UID) {
17185            throw new SecurityException(
17186                    "addPersistentPreferredActivity can only be run by the system");
17187        }
17188        if (filter.countActions() == 0) {
17189            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17190            return;
17191        }
17192        synchronized (mPackages) {
17193            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17194                    ":");
17195            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17196            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17197                    new PersistentPreferredActivity(filter, activity));
17198            scheduleWritePackageRestrictionsLocked(userId);
17199            postPreferredActivityChangedBroadcast(userId);
17200        }
17201    }
17202
17203    @Override
17204    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17205        int callingUid = Binder.getCallingUid();
17206        if (callingUid != Process.SYSTEM_UID) {
17207            throw new SecurityException(
17208                    "clearPackagePersistentPreferredActivities can only be run by the system");
17209        }
17210        ArrayList<PersistentPreferredActivity> removed = null;
17211        boolean changed = false;
17212        synchronized (mPackages) {
17213            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17214                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17215                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17216                        .valueAt(i);
17217                if (userId != thisUserId) {
17218                    continue;
17219                }
17220                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17221                while (it.hasNext()) {
17222                    PersistentPreferredActivity ppa = it.next();
17223                    // Mark entry for removal only if it matches the package name.
17224                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17225                        if (removed == null) {
17226                            removed = new ArrayList<PersistentPreferredActivity>();
17227                        }
17228                        removed.add(ppa);
17229                    }
17230                }
17231                if (removed != null) {
17232                    for (int j=0; j<removed.size(); j++) {
17233                        PersistentPreferredActivity ppa = removed.get(j);
17234                        ppir.removeFilter(ppa);
17235                    }
17236                    changed = true;
17237                }
17238            }
17239
17240            if (changed) {
17241                scheduleWritePackageRestrictionsLocked(userId);
17242                postPreferredActivityChangedBroadcast(userId);
17243            }
17244        }
17245    }
17246
17247    /**
17248     * Common machinery for picking apart a restored XML blob and passing
17249     * it to a caller-supplied functor to be applied to the running system.
17250     */
17251    private void restoreFromXml(XmlPullParser parser, int userId,
17252            String expectedStartTag, BlobXmlRestorer functor)
17253            throws IOException, XmlPullParserException {
17254        int type;
17255        while ((type = parser.next()) != XmlPullParser.START_TAG
17256                && type != XmlPullParser.END_DOCUMENT) {
17257        }
17258        if (type != XmlPullParser.START_TAG) {
17259            // oops didn't find a start tag?!
17260            if (DEBUG_BACKUP) {
17261                Slog.e(TAG, "Didn't find start tag during restore");
17262            }
17263            return;
17264        }
17265Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17266        // this is supposed to be TAG_PREFERRED_BACKUP
17267        if (!expectedStartTag.equals(parser.getName())) {
17268            if (DEBUG_BACKUP) {
17269                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17270            }
17271            return;
17272        }
17273
17274        // skip interfering stuff, then we're aligned with the backing implementation
17275        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17276Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17277        functor.apply(parser, userId);
17278    }
17279
17280    private interface BlobXmlRestorer {
17281        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17282    }
17283
17284    /**
17285     * Non-Binder method, support for the backup/restore mechanism: write the
17286     * full set of preferred activities in its canonical XML format.  Returns the
17287     * XML output as a byte array, or null if there is none.
17288     */
17289    @Override
17290    public byte[] getPreferredActivityBackup(int userId) {
17291        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17292            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17293        }
17294
17295        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17296        try {
17297            final XmlSerializer serializer = new FastXmlSerializer();
17298            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17299            serializer.startDocument(null, true);
17300            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17301
17302            synchronized (mPackages) {
17303                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17304            }
17305
17306            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17307            serializer.endDocument();
17308            serializer.flush();
17309        } catch (Exception e) {
17310            if (DEBUG_BACKUP) {
17311                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17312            }
17313            return null;
17314        }
17315
17316        return dataStream.toByteArray();
17317    }
17318
17319    @Override
17320    public void restorePreferredActivities(byte[] backup, int userId) {
17321        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17322            throw new SecurityException("Only the system may call restorePreferredActivities()");
17323        }
17324
17325        try {
17326            final XmlPullParser parser = Xml.newPullParser();
17327            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17328            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17329                    new BlobXmlRestorer() {
17330                        @Override
17331                        public void apply(XmlPullParser parser, int userId)
17332                                throws XmlPullParserException, IOException {
17333                            synchronized (mPackages) {
17334                                mSettings.readPreferredActivitiesLPw(parser, userId);
17335                            }
17336                        }
17337                    } );
17338        } catch (Exception e) {
17339            if (DEBUG_BACKUP) {
17340                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17341            }
17342        }
17343    }
17344
17345    /**
17346     * Non-Binder method, support for the backup/restore mechanism: write the
17347     * default browser (etc) settings in its canonical XML format.  Returns the default
17348     * browser XML representation as a byte array, or null if there is none.
17349     */
17350    @Override
17351    public byte[] getDefaultAppsBackup(int userId) {
17352        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17353            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17354        }
17355
17356        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17357        try {
17358            final XmlSerializer serializer = new FastXmlSerializer();
17359            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17360            serializer.startDocument(null, true);
17361            serializer.startTag(null, TAG_DEFAULT_APPS);
17362
17363            synchronized (mPackages) {
17364                mSettings.writeDefaultAppsLPr(serializer, userId);
17365            }
17366
17367            serializer.endTag(null, TAG_DEFAULT_APPS);
17368            serializer.endDocument();
17369            serializer.flush();
17370        } catch (Exception e) {
17371            if (DEBUG_BACKUP) {
17372                Slog.e(TAG, "Unable to write default apps for backup", e);
17373            }
17374            return null;
17375        }
17376
17377        return dataStream.toByteArray();
17378    }
17379
17380    @Override
17381    public void restoreDefaultApps(byte[] backup, int userId) {
17382        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17383            throw new SecurityException("Only the system may call restoreDefaultApps()");
17384        }
17385
17386        try {
17387            final XmlPullParser parser = Xml.newPullParser();
17388            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17389            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17390                    new BlobXmlRestorer() {
17391                        @Override
17392                        public void apply(XmlPullParser parser, int userId)
17393                                throws XmlPullParserException, IOException {
17394                            synchronized (mPackages) {
17395                                mSettings.readDefaultAppsLPw(parser, userId);
17396                            }
17397                        }
17398                    } );
17399        } catch (Exception e) {
17400            if (DEBUG_BACKUP) {
17401                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17402            }
17403        }
17404    }
17405
17406    @Override
17407    public byte[] getIntentFilterVerificationBackup(int userId) {
17408        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17409            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17410        }
17411
17412        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17413        try {
17414            final XmlSerializer serializer = new FastXmlSerializer();
17415            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17416            serializer.startDocument(null, true);
17417            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17418
17419            synchronized (mPackages) {
17420                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17421            }
17422
17423            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17424            serializer.endDocument();
17425            serializer.flush();
17426        } catch (Exception e) {
17427            if (DEBUG_BACKUP) {
17428                Slog.e(TAG, "Unable to write default apps for backup", e);
17429            }
17430            return null;
17431        }
17432
17433        return dataStream.toByteArray();
17434    }
17435
17436    @Override
17437    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17438        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17439            throw new SecurityException("Only the system may call restorePreferredActivities()");
17440        }
17441
17442        try {
17443            final XmlPullParser parser = Xml.newPullParser();
17444            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17445            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17446                    new BlobXmlRestorer() {
17447                        @Override
17448                        public void apply(XmlPullParser parser, int userId)
17449                                throws XmlPullParserException, IOException {
17450                            synchronized (mPackages) {
17451                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17452                                mSettings.writeLPr();
17453                            }
17454                        }
17455                    } );
17456        } catch (Exception e) {
17457            if (DEBUG_BACKUP) {
17458                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17459            }
17460        }
17461    }
17462
17463    @Override
17464    public byte[] getPermissionGrantBackup(int userId) {
17465        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17466            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17467        }
17468
17469        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17470        try {
17471            final XmlSerializer serializer = new FastXmlSerializer();
17472            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17473            serializer.startDocument(null, true);
17474            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17475
17476            synchronized (mPackages) {
17477                serializeRuntimePermissionGrantsLPr(serializer, userId);
17478            }
17479
17480            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17481            serializer.endDocument();
17482            serializer.flush();
17483        } catch (Exception e) {
17484            if (DEBUG_BACKUP) {
17485                Slog.e(TAG, "Unable to write default apps for backup", e);
17486            }
17487            return null;
17488        }
17489
17490        return dataStream.toByteArray();
17491    }
17492
17493    @Override
17494    public void restorePermissionGrants(byte[] backup, int userId) {
17495        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17496            throw new SecurityException("Only the system may call restorePermissionGrants()");
17497        }
17498
17499        try {
17500            final XmlPullParser parser = Xml.newPullParser();
17501            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17502            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17503                    new BlobXmlRestorer() {
17504                        @Override
17505                        public void apply(XmlPullParser parser, int userId)
17506                                throws XmlPullParserException, IOException {
17507                            synchronized (mPackages) {
17508                                processRestoredPermissionGrantsLPr(parser, userId);
17509                            }
17510                        }
17511                    } );
17512        } catch (Exception e) {
17513            if (DEBUG_BACKUP) {
17514                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17515            }
17516        }
17517    }
17518
17519    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17520            throws IOException {
17521        serializer.startTag(null, TAG_ALL_GRANTS);
17522
17523        final int N = mSettings.mPackages.size();
17524        for (int i = 0; i < N; i++) {
17525            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17526            boolean pkgGrantsKnown = false;
17527
17528            PermissionsState packagePerms = ps.getPermissionsState();
17529
17530            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17531                final int grantFlags = state.getFlags();
17532                // only look at grants that are not system/policy fixed
17533                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17534                    final boolean isGranted = state.isGranted();
17535                    // And only back up the user-twiddled state bits
17536                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17537                        final String packageName = mSettings.mPackages.keyAt(i);
17538                        if (!pkgGrantsKnown) {
17539                            serializer.startTag(null, TAG_GRANT);
17540                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17541                            pkgGrantsKnown = true;
17542                        }
17543
17544                        final boolean userSet =
17545                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17546                        final boolean userFixed =
17547                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17548                        final boolean revoke =
17549                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17550
17551                        serializer.startTag(null, TAG_PERMISSION);
17552                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17553                        if (isGranted) {
17554                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17555                        }
17556                        if (userSet) {
17557                            serializer.attribute(null, ATTR_USER_SET, "true");
17558                        }
17559                        if (userFixed) {
17560                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17561                        }
17562                        if (revoke) {
17563                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17564                        }
17565                        serializer.endTag(null, TAG_PERMISSION);
17566                    }
17567                }
17568            }
17569
17570            if (pkgGrantsKnown) {
17571                serializer.endTag(null, TAG_GRANT);
17572            }
17573        }
17574
17575        serializer.endTag(null, TAG_ALL_GRANTS);
17576    }
17577
17578    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17579            throws XmlPullParserException, IOException {
17580        String pkgName = null;
17581        int outerDepth = parser.getDepth();
17582        int type;
17583        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17584                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17585            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17586                continue;
17587            }
17588
17589            final String tagName = parser.getName();
17590            if (tagName.equals(TAG_GRANT)) {
17591                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17592                if (DEBUG_BACKUP) {
17593                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17594                }
17595            } else if (tagName.equals(TAG_PERMISSION)) {
17596
17597                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17598                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17599
17600                int newFlagSet = 0;
17601                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17602                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17603                }
17604                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17605                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17606                }
17607                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17608                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17609                }
17610                if (DEBUG_BACKUP) {
17611                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17612                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17613                }
17614                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17615                if (ps != null) {
17616                    // Already installed so we apply the grant immediately
17617                    if (DEBUG_BACKUP) {
17618                        Slog.v(TAG, "        + already installed; applying");
17619                    }
17620                    PermissionsState perms = ps.getPermissionsState();
17621                    BasePermission bp = mSettings.mPermissions.get(permName);
17622                    if (bp != null) {
17623                        if (isGranted) {
17624                            perms.grantRuntimePermission(bp, userId);
17625                        }
17626                        if (newFlagSet != 0) {
17627                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17628                        }
17629                    }
17630                } else {
17631                    // Need to wait for post-restore install to apply the grant
17632                    if (DEBUG_BACKUP) {
17633                        Slog.v(TAG, "        - not yet installed; saving for later");
17634                    }
17635                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17636                            isGranted, newFlagSet, userId);
17637                }
17638            } else {
17639                PackageManagerService.reportSettingsProblem(Log.WARN,
17640                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17641                XmlUtils.skipCurrentTag(parser);
17642            }
17643        }
17644
17645        scheduleWriteSettingsLocked();
17646        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17647    }
17648
17649    @Override
17650    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17651            int sourceUserId, int targetUserId, int flags) {
17652        mContext.enforceCallingOrSelfPermission(
17653                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17654        int callingUid = Binder.getCallingUid();
17655        enforceOwnerRights(ownerPackage, callingUid);
17656        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17657        if (intentFilter.countActions() == 0) {
17658            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17659            return;
17660        }
17661        synchronized (mPackages) {
17662            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17663                    ownerPackage, targetUserId, flags);
17664            CrossProfileIntentResolver resolver =
17665                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17666            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17667            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17668            if (existing != null) {
17669                int size = existing.size();
17670                for (int i = 0; i < size; i++) {
17671                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17672                        return;
17673                    }
17674                }
17675            }
17676            resolver.addFilter(newFilter);
17677            scheduleWritePackageRestrictionsLocked(sourceUserId);
17678        }
17679    }
17680
17681    @Override
17682    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17683        mContext.enforceCallingOrSelfPermission(
17684                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17685        int callingUid = Binder.getCallingUid();
17686        enforceOwnerRights(ownerPackage, callingUid);
17687        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17688        synchronized (mPackages) {
17689            CrossProfileIntentResolver resolver =
17690                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17691            ArraySet<CrossProfileIntentFilter> set =
17692                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17693            for (CrossProfileIntentFilter filter : set) {
17694                if (filter.getOwnerPackage().equals(ownerPackage)) {
17695                    resolver.removeFilter(filter);
17696                }
17697            }
17698            scheduleWritePackageRestrictionsLocked(sourceUserId);
17699        }
17700    }
17701
17702    // Enforcing that callingUid is owning pkg on userId
17703    private void enforceOwnerRights(String pkg, int callingUid) {
17704        // The system owns everything.
17705        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17706            return;
17707        }
17708        int callingUserId = UserHandle.getUserId(callingUid);
17709        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17710        if (pi == null) {
17711            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17712                    + callingUserId);
17713        }
17714        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17715            throw new SecurityException("Calling uid " + callingUid
17716                    + " does not own package " + pkg);
17717        }
17718    }
17719
17720    @Override
17721    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17722        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17723    }
17724
17725    private Intent getHomeIntent() {
17726        Intent intent = new Intent(Intent.ACTION_MAIN);
17727        intent.addCategory(Intent.CATEGORY_HOME);
17728        intent.addCategory(Intent.CATEGORY_DEFAULT);
17729        return intent;
17730    }
17731
17732    private IntentFilter getHomeFilter() {
17733        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17734        filter.addCategory(Intent.CATEGORY_HOME);
17735        filter.addCategory(Intent.CATEGORY_DEFAULT);
17736        return filter;
17737    }
17738
17739    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17740            int userId) {
17741        Intent intent  = getHomeIntent();
17742        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17743                PackageManager.GET_META_DATA, userId);
17744        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17745                true, false, false, userId);
17746
17747        allHomeCandidates.clear();
17748        if (list != null) {
17749            for (ResolveInfo ri : list) {
17750                allHomeCandidates.add(ri);
17751            }
17752        }
17753        return (preferred == null || preferred.activityInfo == null)
17754                ? null
17755                : new ComponentName(preferred.activityInfo.packageName,
17756                        preferred.activityInfo.name);
17757    }
17758
17759    @Override
17760    public void setHomeActivity(ComponentName comp, int userId) {
17761        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17762        getHomeActivitiesAsUser(homeActivities, userId);
17763
17764        boolean found = false;
17765
17766        final int size = homeActivities.size();
17767        final ComponentName[] set = new ComponentName[size];
17768        for (int i = 0; i < size; i++) {
17769            final ResolveInfo candidate = homeActivities.get(i);
17770            final ActivityInfo info = candidate.activityInfo;
17771            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17772            set[i] = activityName;
17773            if (!found && activityName.equals(comp)) {
17774                found = true;
17775            }
17776        }
17777        if (!found) {
17778            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17779                    + userId);
17780        }
17781        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17782                set, comp, userId);
17783    }
17784
17785    private @Nullable String getSetupWizardPackageName() {
17786        final Intent intent = new Intent(Intent.ACTION_MAIN);
17787        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17788
17789        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17790                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17791                        | MATCH_DISABLED_COMPONENTS,
17792                UserHandle.myUserId());
17793        if (matches.size() == 1) {
17794            return matches.get(0).getComponentInfo().packageName;
17795        } else {
17796            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17797                    + ": matches=" + matches);
17798            return null;
17799        }
17800    }
17801
17802    private @Nullable String getStorageManagerPackageName() {
17803        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17804
17805        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17806                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17807                        | MATCH_DISABLED_COMPONENTS,
17808                UserHandle.myUserId());
17809        if (matches.size() == 1) {
17810            return matches.get(0).getComponentInfo().packageName;
17811        } else {
17812            Slog.e(TAG, "There should probably be exactly one storage manager; found "
17813                    + matches.size() + ": matches=" + matches);
17814            return null;
17815        }
17816    }
17817
17818    @Override
17819    public void setApplicationEnabledSetting(String appPackageName,
17820            int newState, int flags, int userId, String callingPackage) {
17821        if (!sUserManager.exists(userId)) return;
17822        if (callingPackage == null) {
17823            callingPackage = Integer.toString(Binder.getCallingUid());
17824        }
17825        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17826    }
17827
17828    @Override
17829    public void setComponentEnabledSetting(ComponentName componentName,
17830            int newState, int flags, int userId) {
17831        if (!sUserManager.exists(userId)) return;
17832        setEnabledSetting(componentName.getPackageName(),
17833                componentName.getClassName(), newState, flags, userId, null);
17834    }
17835
17836    private void setEnabledSetting(final String packageName, String className, int newState,
17837            final int flags, int userId, String callingPackage) {
17838        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17839              || newState == COMPONENT_ENABLED_STATE_ENABLED
17840              || newState == COMPONENT_ENABLED_STATE_DISABLED
17841              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17842              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17843            throw new IllegalArgumentException("Invalid new component state: "
17844                    + newState);
17845        }
17846        PackageSetting pkgSetting;
17847        final int uid = Binder.getCallingUid();
17848        final int permission;
17849        if (uid == Process.SYSTEM_UID) {
17850            permission = PackageManager.PERMISSION_GRANTED;
17851        } else {
17852            permission = mContext.checkCallingOrSelfPermission(
17853                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17854        }
17855        enforceCrossUserPermission(uid, userId,
17856                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17857        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17858        boolean sendNow = false;
17859        boolean isApp = (className == null);
17860        String componentName = isApp ? packageName : className;
17861        int packageUid = -1;
17862        ArrayList<String> components;
17863
17864        // writer
17865        synchronized (mPackages) {
17866            pkgSetting = mSettings.mPackages.get(packageName);
17867            if (pkgSetting == null) {
17868                if (className == null) {
17869                    throw new IllegalArgumentException("Unknown package: " + packageName);
17870                }
17871                throw new IllegalArgumentException(
17872                        "Unknown component: " + packageName + "/" + className);
17873            }
17874        }
17875
17876        // Limit who can change which apps
17877        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17878            // Don't allow apps that don't have permission to modify other apps
17879            if (!allowedByPermission) {
17880                throw new SecurityException(
17881                        "Permission Denial: attempt to change component state from pid="
17882                        + Binder.getCallingPid()
17883                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17884            }
17885            // Don't allow changing protected packages.
17886            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17887                throw new SecurityException("Cannot disable a protected package: " + packageName);
17888            }
17889        }
17890
17891        synchronized (mPackages) {
17892            if (uid == Process.SHELL_UID) {
17893                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17894                int oldState = pkgSetting.getEnabled(userId);
17895                if (className == null
17896                    &&
17897                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17898                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17899                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17900                    &&
17901                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17902                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17903                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17904                    // ok
17905                } else {
17906                    throw new SecurityException(
17907                            "Shell cannot change component state for " + packageName + "/"
17908                            + className + " to " + newState);
17909                }
17910            }
17911            if (className == null) {
17912                // We're dealing with an application/package level state change
17913                if (pkgSetting.getEnabled(userId) == newState) {
17914                    // Nothing to do
17915                    return;
17916                }
17917                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17918                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17919                    // Don't care about who enables an app.
17920                    callingPackage = null;
17921                }
17922                pkgSetting.setEnabled(newState, userId, callingPackage);
17923                // pkgSetting.pkg.mSetEnabled = newState;
17924            } else {
17925                // We're dealing with a component level state change
17926                // First, verify that this is a valid class name.
17927                PackageParser.Package pkg = pkgSetting.pkg;
17928                if (pkg == null || !pkg.hasComponentClassName(className)) {
17929                    if (pkg != null &&
17930                            pkg.applicationInfo.targetSdkVersion >=
17931                                    Build.VERSION_CODES.JELLY_BEAN) {
17932                        throw new IllegalArgumentException("Component class " + className
17933                                + " does not exist in " + packageName);
17934                    } else {
17935                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17936                                + className + " does not exist in " + packageName);
17937                    }
17938                }
17939                switch (newState) {
17940                case COMPONENT_ENABLED_STATE_ENABLED:
17941                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17942                        return;
17943                    }
17944                    break;
17945                case COMPONENT_ENABLED_STATE_DISABLED:
17946                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17947                        return;
17948                    }
17949                    break;
17950                case COMPONENT_ENABLED_STATE_DEFAULT:
17951                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17952                        return;
17953                    }
17954                    break;
17955                default:
17956                    Slog.e(TAG, "Invalid new component state: " + newState);
17957                    return;
17958                }
17959            }
17960            scheduleWritePackageRestrictionsLocked(userId);
17961            components = mPendingBroadcasts.get(userId, packageName);
17962            final boolean newPackage = components == null;
17963            if (newPackage) {
17964                components = new ArrayList<String>();
17965            }
17966            if (!components.contains(componentName)) {
17967                components.add(componentName);
17968            }
17969            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17970                sendNow = true;
17971                // Purge entry from pending broadcast list if another one exists already
17972                // since we are sending one right away.
17973                mPendingBroadcasts.remove(userId, packageName);
17974            } else {
17975                if (newPackage) {
17976                    mPendingBroadcasts.put(userId, packageName, components);
17977                }
17978                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17979                    // Schedule a message
17980                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17981                }
17982            }
17983        }
17984
17985        long callingId = Binder.clearCallingIdentity();
17986        try {
17987            if (sendNow) {
17988                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17989                sendPackageChangedBroadcast(packageName,
17990                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17991            }
17992        } finally {
17993            Binder.restoreCallingIdentity(callingId);
17994        }
17995    }
17996
17997    @Override
17998    public void flushPackageRestrictionsAsUser(int userId) {
17999        if (!sUserManager.exists(userId)) {
18000            return;
18001        }
18002        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18003                false /* checkShell */, "flushPackageRestrictions");
18004        synchronized (mPackages) {
18005            mSettings.writePackageRestrictionsLPr(userId);
18006            mDirtyUsers.remove(userId);
18007            if (mDirtyUsers.isEmpty()) {
18008                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18009            }
18010        }
18011    }
18012
18013    private void sendPackageChangedBroadcast(String packageName,
18014            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18015        if (DEBUG_INSTALL)
18016            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18017                    + componentNames);
18018        Bundle extras = new Bundle(4);
18019        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18020        String nameList[] = new String[componentNames.size()];
18021        componentNames.toArray(nameList);
18022        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18023        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18024        extras.putInt(Intent.EXTRA_UID, packageUid);
18025        // If this is not reporting a change of the overall package, then only send it
18026        // to registered receivers.  We don't want to launch a swath of apps for every
18027        // little component state change.
18028        final int flags = !componentNames.contains(packageName)
18029                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18030        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18031                new int[] {UserHandle.getUserId(packageUid)});
18032    }
18033
18034    @Override
18035    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18036        if (!sUserManager.exists(userId)) return;
18037        final int uid = Binder.getCallingUid();
18038        final int permission = mContext.checkCallingOrSelfPermission(
18039                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18040        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18041        enforceCrossUserPermission(uid, userId,
18042                true /* requireFullPermission */, true /* checkShell */, "stop package");
18043        // writer
18044        synchronized (mPackages) {
18045            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18046                    allowedByPermission, uid, userId)) {
18047                scheduleWritePackageRestrictionsLocked(userId);
18048            }
18049        }
18050    }
18051
18052    @Override
18053    public String getInstallerPackageName(String packageName) {
18054        // reader
18055        synchronized (mPackages) {
18056            return mSettings.getInstallerPackageNameLPr(packageName);
18057        }
18058    }
18059
18060    public boolean isOrphaned(String packageName) {
18061        // reader
18062        synchronized (mPackages) {
18063            return mSettings.isOrphaned(packageName);
18064        }
18065    }
18066
18067    @Override
18068    public int getApplicationEnabledSetting(String packageName, int userId) {
18069        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18070        int uid = Binder.getCallingUid();
18071        enforceCrossUserPermission(uid, userId,
18072                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18073        // reader
18074        synchronized (mPackages) {
18075            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18076        }
18077    }
18078
18079    @Override
18080    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18081        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18082        int uid = Binder.getCallingUid();
18083        enforceCrossUserPermission(uid, userId,
18084                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18085        // reader
18086        synchronized (mPackages) {
18087            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18088        }
18089    }
18090
18091    @Override
18092    public void enterSafeMode() {
18093        enforceSystemOrRoot("Only the system can request entering safe mode");
18094
18095        if (!mSystemReady) {
18096            mSafeMode = true;
18097        }
18098    }
18099
18100    @Override
18101    public void systemReady() {
18102        mSystemReady = true;
18103
18104        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18105        // disabled after already being started.
18106        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18107                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18108
18109        // Read the compatibilty setting when the system is ready.
18110        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18111                mContext.getContentResolver(),
18112                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18113        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18114        if (DEBUG_SETTINGS) {
18115            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18116        }
18117
18118        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18119
18120        synchronized (mPackages) {
18121            // Verify that all of the preferred activity components actually
18122            // exist.  It is possible for applications to be updated and at
18123            // that point remove a previously declared activity component that
18124            // had been set as a preferred activity.  We try to clean this up
18125            // the next time we encounter that preferred activity, but it is
18126            // possible for the user flow to never be able to return to that
18127            // situation so here we do a sanity check to make sure we haven't
18128            // left any junk around.
18129            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18130            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18131                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18132                removed.clear();
18133                for (PreferredActivity pa : pir.filterSet()) {
18134                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18135                        removed.add(pa);
18136                    }
18137                }
18138                if (removed.size() > 0) {
18139                    for (int r=0; r<removed.size(); r++) {
18140                        PreferredActivity pa = removed.get(r);
18141                        Slog.w(TAG, "Removing dangling preferred activity: "
18142                                + pa.mPref.mComponent);
18143                        pir.removeFilter(pa);
18144                    }
18145                    mSettings.writePackageRestrictionsLPr(
18146                            mSettings.mPreferredActivities.keyAt(i));
18147                }
18148            }
18149
18150            for (int userId : UserManagerService.getInstance().getUserIds()) {
18151                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18152                    grantPermissionsUserIds = ArrayUtils.appendInt(
18153                            grantPermissionsUserIds, userId);
18154                }
18155            }
18156        }
18157        sUserManager.systemReady();
18158
18159        // If we upgraded grant all default permissions before kicking off.
18160        for (int userId : grantPermissionsUserIds) {
18161            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18162        }
18163
18164        // If we did not grant default permissions, we preload from this the
18165        // default permission exceptions lazily to ensure we don't hit the
18166        // disk on a new user creation.
18167        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18168            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18169        }
18170
18171        // Kick off any messages waiting for system ready
18172        if (mPostSystemReadyMessages != null) {
18173            for (Message msg : mPostSystemReadyMessages) {
18174                msg.sendToTarget();
18175            }
18176            mPostSystemReadyMessages = null;
18177        }
18178
18179        // Watch for external volumes that come and go over time
18180        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18181        storage.registerListener(mStorageListener);
18182
18183        mInstallerService.systemReady();
18184        mPackageDexOptimizer.systemReady();
18185
18186        MountServiceInternal mountServiceInternal = LocalServices.getService(
18187                MountServiceInternal.class);
18188        mountServiceInternal.addExternalStoragePolicy(
18189                new MountServiceInternal.ExternalStorageMountPolicy() {
18190            @Override
18191            public int getMountMode(int uid, String packageName) {
18192                if (Process.isIsolated(uid)) {
18193                    return Zygote.MOUNT_EXTERNAL_NONE;
18194                }
18195                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18196                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18197                }
18198                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18199                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18200                }
18201                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18202                    return Zygote.MOUNT_EXTERNAL_READ;
18203                }
18204                return Zygote.MOUNT_EXTERNAL_WRITE;
18205            }
18206
18207            @Override
18208            public boolean hasExternalStorage(int uid, String packageName) {
18209                return true;
18210            }
18211        });
18212
18213        // Now that we're mostly running, clean up stale users and apps
18214        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18215        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18216    }
18217
18218    @Override
18219    public boolean isSafeMode() {
18220        return mSafeMode;
18221    }
18222
18223    @Override
18224    public boolean hasSystemUidErrors() {
18225        return mHasSystemUidErrors;
18226    }
18227
18228    static String arrayToString(int[] array) {
18229        StringBuffer buf = new StringBuffer(128);
18230        buf.append('[');
18231        if (array != null) {
18232            for (int i=0; i<array.length; i++) {
18233                if (i > 0) buf.append(", ");
18234                buf.append(array[i]);
18235            }
18236        }
18237        buf.append(']');
18238        return buf.toString();
18239    }
18240
18241    static class DumpState {
18242        public static final int DUMP_LIBS = 1 << 0;
18243        public static final int DUMP_FEATURES = 1 << 1;
18244        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18245        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18246        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18247        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18248        public static final int DUMP_PERMISSIONS = 1 << 6;
18249        public static final int DUMP_PACKAGES = 1 << 7;
18250        public static final int DUMP_SHARED_USERS = 1 << 8;
18251        public static final int DUMP_MESSAGES = 1 << 9;
18252        public static final int DUMP_PROVIDERS = 1 << 10;
18253        public static final int DUMP_VERIFIERS = 1 << 11;
18254        public static final int DUMP_PREFERRED = 1 << 12;
18255        public static final int DUMP_PREFERRED_XML = 1 << 13;
18256        public static final int DUMP_KEYSETS = 1 << 14;
18257        public static final int DUMP_VERSION = 1 << 15;
18258        public static final int DUMP_INSTALLS = 1 << 16;
18259        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18260        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18261        public static final int DUMP_FROZEN = 1 << 19;
18262        public static final int DUMP_DEXOPT = 1 << 20;
18263        public static final int DUMP_COMPILER_STATS = 1 << 21;
18264
18265        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18266
18267        private int mTypes;
18268
18269        private int mOptions;
18270
18271        private boolean mTitlePrinted;
18272
18273        private SharedUserSetting mSharedUser;
18274
18275        public boolean isDumping(int type) {
18276            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18277                return true;
18278            }
18279
18280            return (mTypes & type) != 0;
18281        }
18282
18283        public void setDump(int type) {
18284            mTypes |= type;
18285        }
18286
18287        public boolean isOptionEnabled(int option) {
18288            return (mOptions & option) != 0;
18289        }
18290
18291        public void setOptionEnabled(int option) {
18292            mOptions |= option;
18293        }
18294
18295        public boolean onTitlePrinted() {
18296            final boolean printed = mTitlePrinted;
18297            mTitlePrinted = true;
18298            return printed;
18299        }
18300
18301        public boolean getTitlePrinted() {
18302            return mTitlePrinted;
18303        }
18304
18305        public void setTitlePrinted(boolean enabled) {
18306            mTitlePrinted = enabled;
18307        }
18308
18309        public SharedUserSetting getSharedUser() {
18310            return mSharedUser;
18311        }
18312
18313        public void setSharedUser(SharedUserSetting user) {
18314            mSharedUser = user;
18315        }
18316    }
18317
18318    @Override
18319    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18320            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18321        (new PackageManagerShellCommand(this)).exec(
18322                this, in, out, err, args, resultReceiver);
18323    }
18324
18325    @Override
18326    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18327        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18328                != PackageManager.PERMISSION_GRANTED) {
18329            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18330                    + Binder.getCallingPid()
18331                    + ", uid=" + Binder.getCallingUid()
18332                    + " without permission "
18333                    + android.Manifest.permission.DUMP);
18334            return;
18335        }
18336
18337        DumpState dumpState = new DumpState();
18338        boolean fullPreferred = false;
18339        boolean checkin = false;
18340
18341        String packageName = null;
18342        ArraySet<String> permissionNames = null;
18343
18344        int opti = 0;
18345        while (opti < args.length) {
18346            String opt = args[opti];
18347            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18348                break;
18349            }
18350            opti++;
18351
18352            if ("-a".equals(opt)) {
18353                // Right now we only know how to print all.
18354            } else if ("-h".equals(opt)) {
18355                pw.println("Package manager dump options:");
18356                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18357                pw.println("    --checkin: dump for a checkin");
18358                pw.println("    -f: print details of intent filters");
18359                pw.println("    -h: print this help");
18360                pw.println("  cmd may be one of:");
18361                pw.println("    l[ibraries]: list known shared libraries");
18362                pw.println("    f[eatures]: list device features");
18363                pw.println("    k[eysets]: print known keysets");
18364                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18365                pw.println("    perm[issions]: dump permissions");
18366                pw.println("    permission [name ...]: dump declaration and use of given permission");
18367                pw.println("    pref[erred]: print preferred package settings");
18368                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18369                pw.println("    prov[iders]: dump content providers");
18370                pw.println("    p[ackages]: dump installed packages");
18371                pw.println("    s[hared-users]: dump shared user IDs");
18372                pw.println("    m[essages]: print collected runtime messages");
18373                pw.println("    v[erifiers]: print package verifier info");
18374                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18375                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18376                pw.println("    version: print database version info");
18377                pw.println("    write: write current settings now");
18378                pw.println("    installs: details about install sessions");
18379                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18380                pw.println("    dexopt: dump dexopt state");
18381                pw.println("    compiler-stats: dump compiler statistics");
18382                pw.println("    <package.name>: info about given package");
18383                return;
18384            } else if ("--checkin".equals(opt)) {
18385                checkin = true;
18386            } else if ("-f".equals(opt)) {
18387                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18388            } else {
18389                pw.println("Unknown argument: " + opt + "; use -h for help");
18390            }
18391        }
18392
18393        // Is the caller requesting to dump a particular piece of data?
18394        if (opti < args.length) {
18395            String cmd = args[opti];
18396            opti++;
18397            // Is this a package name?
18398            if ("android".equals(cmd) || cmd.contains(".")) {
18399                packageName = cmd;
18400                // When dumping a single package, we always dump all of its
18401                // filter information since the amount of data will be reasonable.
18402                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18403            } else if ("check-permission".equals(cmd)) {
18404                if (opti >= args.length) {
18405                    pw.println("Error: check-permission missing permission argument");
18406                    return;
18407                }
18408                String perm = args[opti];
18409                opti++;
18410                if (opti >= args.length) {
18411                    pw.println("Error: check-permission missing package argument");
18412                    return;
18413                }
18414                String pkg = args[opti];
18415                opti++;
18416                int user = UserHandle.getUserId(Binder.getCallingUid());
18417                if (opti < args.length) {
18418                    try {
18419                        user = Integer.parseInt(args[opti]);
18420                    } catch (NumberFormatException e) {
18421                        pw.println("Error: check-permission user argument is not a number: "
18422                                + args[opti]);
18423                        return;
18424                    }
18425                }
18426                pw.println(checkPermission(perm, pkg, user));
18427                return;
18428            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18429                dumpState.setDump(DumpState.DUMP_LIBS);
18430            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18431                dumpState.setDump(DumpState.DUMP_FEATURES);
18432            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18433                if (opti >= args.length) {
18434                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18435                            | DumpState.DUMP_SERVICE_RESOLVERS
18436                            | DumpState.DUMP_RECEIVER_RESOLVERS
18437                            | DumpState.DUMP_CONTENT_RESOLVERS);
18438                } else {
18439                    while (opti < args.length) {
18440                        String name = args[opti];
18441                        if ("a".equals(name) || "activity".equals(name)) {
18442                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18443                        } else if ("s".equals(name) || "service".equals(name)) {
18444                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18445                        } else if ("r".equals(name) || "receiver".equals(name)) {
18446                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18447                        } else if ("c".equals(name) || "content".equals(name)) {
18448                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18449                        } else {
18450                            pw.println("Error: unknown resolver table type: " + name);
18451                            return;
18452                        }
18453                        opti++;
18454                    }
18455                }
18456            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18457                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18458            } else if ("permission".equals(cmd)) {
18459                if (opti >= args.length) {
18460                    pw.println("Error: permission requires permission name");
18461                    return;
18462                }
18463                permissionNames = new ArraySet<>();
18464                while (opti < args.length) {
18465                    permissionNames.add(args[opti]);
18466                    opti++;
18467                }
18468                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18469                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18470            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18471                dumpState.setDump(DumpState.DUMP_PREFERRED);
18472            } else if ("preferred-xml".equals(cmd)) {
18473                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18474                if (opti < args.length && "--full".equals(args[opti])) {
18475                    fullPreferred = true;
18476                    opti++;
18477                }
18478            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18479                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18480            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18481                dumpState.setDump(DumpState.DUMP_PACKAGES);
18482            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18483                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18484            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18485                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18486            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18487                dumpState.setDump(DumpState.DUMP_MESSAGES);
18488            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18489                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18490            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18491                    || "intent-filter-verifiers".equals(cmd)) {
18492                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18493            } else if ("version".equals(cmd)) {
18494                dumpState.setDump(DumpState.DUMP_VERSION);
18495            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18496                dumpState.setDump(DumpState.DUMP_KEYSETS);
18497            } else if ("installs".equals(cmd)) {
18498                dumpState.setDump(DumpState.DUMP_INSTALLS);
18499            } else if ("frozen".equals(cmd)) {
18500                dumpState.setDump(DumpState.DUMP_FROZEN);
18501            } else if ("dexopt".equals(cmd)) {
18502                dumpState.setDump(DumpState.DUMP_DEXOPT);
18503            } else if ("compiler-stats".equals(cmd)) {
18504                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18505            } else if ("write".equals(cmd)) {
18506                synchronized (mPackages) {
18507                    mSettings.writeLPr();
18508                    pw.println("Settings written.");
18509                    return;
18510                }
18511            }
18512        }
18513
18514        if (checkin) {
18515            pw.println("vers,1");
18516        }
18517
18518        // reader
18519        synchronized (mPackages) {
18520            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18521                if (!checkin) {
18522                    if (dumpState.onTitlePrinted())
18523                        pw.println();
18524                    pw.println("Database versions:");
18525                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18526                }
18527            }
18528
18529            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18530                if (!checkin) {
18531                    if (dumpState.onTitlePrinted())
18532                        pw.println();
18533                    pw.println("Verifiers:");
18534                    pw.print("  Required: ");
18535                    pw.print(mRequiredVerifierPackage);
18536                    pw.print(" (uid=");
18537                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18538                            UserHandle.USER_SYSTEM));
18539                    pw.println(")");
18540                } else if (mRequiredVerifierPackage != null) {
18541                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18542                    pw.print(",");
18543                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18544                            UserHandle.USER_SYSTEM));
18545                }
18546            }
18547
18548            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18549                    packageName == null) {
18550                if (mIntentFilterVerifierComponent != null) {
18551                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18552                    if (!checkin) {
18553                        if (dumpState.onTitlePrinted())
18554                            pw.println();
18555                        pw.println("Intent Filter Verifier:");
18556                        pw.print("  Using: ");
18557                        pw.print(verifierPackageName);
18558                        pw.print(" (uid=");
18559                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18560                                UserHandle.USER_SYSTEM));
18561                        pw.println(")");
18562                    } else if (verifierPackageName != null) {
18563                        pw.print("ifv,"); pw.print(verifierPackageName);
18564                        pw.print(",");
18565                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18566                                UserHandle.USER_SYSTEM));
18567                    }
18568                } else {
18569                    pw.println();
18570                    pw.println("No Intent Filter Verifier available!");
18571                }
18572            }
18573
18574            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18575                boolean printedHeader = false;
18576                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18577                while (it.hasNext()) {
18578                    String name = it.next();
18579                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18580                    if (!checkin) {
18581                        if (!printedHeader) {
18582                            if (dumpState.onTitlePrinted())
18583                                pw.println();
18584                            pw.println("Libraries:");
18585                            printedHeader = true;
18586                        }
18587                        pw.print("  ");
18588                    } else {
18589                        pw.print("lib,");
18590                    }
18591                    pw.print(name);
18592                    if (!checkin) {
18593                        pw.print(" -> ");
18594                    }
18595                    if (ent.path != null) {
18596                        if (!checkin) {
18597                            pw.print("(jar) ");
18598                            pw.print(ent.path);
18599                        } else {
18600                            pw.print(",jar,");
18601                            pw.print(ent.path);
18602                        }
18603                    } else {
18604                        if (!checkin) {
18605                            pw.print("(apk) ");
18606                            pw.print(ent.apk);
18607                        } else {
18608                            pw.print(",apk,");
18609                            pw.print(ent.apk);
18610                        }
18611                    }
18612                    pw.println();
18613                }
18614            }
18615
18616            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18617                if (dumpState.onTitlePrinted())
18618                    pw.println();
18619                if (!checkin) {
18620                    pw.println("Features:");
18621                }
18622
18623                for (FeatureInfo feat : mAvailableFeatures.values()) {
18624                    if (checkin) {
18625                        pw.print("feat,");
18626                        pw.print(feat.name);
18627                        pw.print(",");
18628                        pw.println(feat.version);
18629                    } else {
18630                        pw.print("  ");
18631                        pw.print(feat.name);
18632                        if (feat.version > 0) {
18633                            pw.print(" version=");
18634                            pw.print(feat.version);
18635                        }
18636                        pw.println();
18637                    }
18638                }
18639            }
18640
18641            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18642                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18643                        : "Activity Resolver Table:", "  ", packageName,
18644                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18645                    dumpState.setTitlePrinted(true);
18646                }
18647            }
18648            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18649                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18650                        : "Receiver Resolver Table:", "  ", packageName,
18651                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18652                    dumpState.setTitlePrinted(true);
18653                }
18654            }
18655            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18656                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18657                        : "Service Resolver Table:", "  ", packageName,
18658                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18659                    dumpState.setTitlePrinted(true);
18660                }
18661            }
18662            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18663                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18664                        : "Provider Resolver Table:", "  ", packageName,
18665                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18666                    dumpState.setTitlePrinted(true);
18667                }
18668            }
18669
18670            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18671                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18672                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18673                    int user = mSettings.mPreferredActivities.keyAt(i);
18674                    if (pir.dump(pw,
18675                            dumpState.getTitlePrinted()
18676                                ? "\nPreferred Activities User " + user + ":"
18677                                : "Preferred Activities User " + user + ":", "  ",
18678                            packageName, true, false)) {
18679                        dumpState.setTitlePrinted(true);
18680                    }
18681                }
18682            }
18683
18684            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18685                pw.flush();
18686                FileOutputStream fout = new FileOutputStream(fd);
18687                BufferedOutputStream str = new BufferedOutputStream(fout);
18688                XmlSerializer serializer = new FastXmlSerializer();
18689                try {
18690                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18691                    serializer.startDocument(null, true);
18692                    serializer.setFeature(
18693                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18694                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18695                    serializer.endDocument();
18696                    serializer.flush();
18697                } catch (IllegalArgumentException e) {
18698                    pw.println("Failed writing: " + e);
18699                } catch (IllegalStateException e) {
18700                    pw.println("Failed writing: " + e);
18701                } catch (IOException e) {
18702                    pw.println("Failed writing: " + e);
18703                }
18704            }
18705
18706            if (!checkin
18707                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18708                    && packageName == null) {
18709                pw.println();
18710                int count = mSettings.mPackages.size();
18711                if (count == 0) {
18712                    pw.println("No applications!");
18713                    pw.println();
18714                } else {
18715                    final String prefix = "  ";
18716                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18717                    if (allPackageSettings.size() == 0) {
18718                        pw.println("No domain preferred apps!");
18719                        pw.println();
18720                    } else {
18721                        pw.println("App verification status:");
18722                        pw.println();
18723                        count = 0;
18724                        for (PackageSetting ps : allPackageSettings) {
18725                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18726                            if (ivi == null || ivi.getPackageName() == null) continue;
18727                            pw.println(prefix + "Package: " + ivi.getPackageName());
18728                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18729                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18730                            pw.println();
18731                            count++;
18732                        }
18733                        if (count == 0) {
18734                            pw.println(prefix + "No app verification established.");
18735                            pw.println();
18736                        }
18737                        for (int userId : sUserManager.getUserIds()) {
18738                            pw.println("App linkages for user " + userId + ":");
18739                            pw.println();
18740                            count = 0;
18741                            for (PackageSetting ps : allPackageSettings) {
18742                                final long status = ps.getDomainVerificationStatusForUser(userId);
18743                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18744                                    continue;
18745                                }
18746                                pw.println(prefix + "Package: " + ps.name);
18747                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18748                                String statusStr = IntentFilterVerificationInfo.
18749                                        getStatusStringFromValue(status);
18750                                pw.println(prefix + "Status:  " + statusStr);
18751                                pw.println();
18752                                count++;
18753                            }
18754                            if (count == 0) {
18755                                pw.println(prefix + "No configured app linkages.");
18756                                pw.println();
18757                            }
18758                        }
18759                    }
18760                }
18761            }
18762
18763            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18764                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18765                if (packageName == null && permissionNames == null) {
18766                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18767                        if (iperm == 0) {
18768                            if (dumpState.onTitlePrinted())
18769                                pw.println();
18770                            pw.println("AppOp Permissions:");
18771                        }
18772                        pw.print("  AppOp Permission ");
18773                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18774                        pw.println(":");
18775                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18776                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18777                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18778                        }
18779                    }
18780                }
18781            }
18782
18783            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18784                boolean printedSomething = false;
18785                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18786                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18787                        continue;
18788                    }
18789                    if (!printedSomething) {
18790                        if (dumpState.onTitlePrinted())
18791                            pw.println();
18792                        pw.println("Registered ContentProviders:");
18793                        printedSomething = true;
18794                    }
18795                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18796                    pw.print("    "); pw.println(p.toString());
18797                }
18798                printedSomething = false;
18799                for (Map.Entry<String, PackageParser.Provider> entry :
18800                        mProvidersByAuthority.entrySet()) {
18801                    PackageParser.Provider p = entry.getValue();
18802                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18803                        continue;
18804                    }
18805                    if (!printedSomething) {
18806                        if (dumpState.onTitlePrinted())
18807                            pw.println();
18808                        pw.println("ContentProvider Authorities:");
18809                        printedSomething = true;
18810                    }
18811                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18812                    pw.print("    "); pw.println(p.toString());
18813                    if (p.info != null && p.info.applicationInfo != null) {
18814                        final String appInfo = p.info.applicationInfo.toString();
18815                        pw.print("      applicationInfo="); pw.println(appInfo);
18816                    }
18817                }
18818            }
18819
18820            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18821                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18822            }
18823
18824            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18825                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18826            }
18827
18828            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18829                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18830            }
18831
18832            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18833                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18834            }
18835
18836            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18837                // XXX should handle packageName != null by dumping only install data that
18838                // the given package is involved with.
18839                if (dumpState.onTitlePrinted()) pw.println();
18840                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18841            }
18842
18843            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18844                // XXX should handle packageName != null by dumping only install data that
18845                // the given package is involved with.
18846                if (dumpState.onTitlePrinted()) pw.println();
18847
18848                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18849                ipw.println();
18850                ipw.println("Frozen packages:");
18851                ipw.increaseIndent();
18852                if (mFrozenPackages.size() == 0) {
18853                    ipw.println("(none)");
18854                } else {
18855                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18856                        ipw.println(mFrozenPackages.valueAt(i));
18857                    }
18858                }
18859                ipw.decreaseIndent();
18860            }
18861
18862            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18863                if (dumpState.onTitlePrinted()) pw.println();
18864                dumpDexoptStateLPr(pw, packageName);
18865            }
18866
18867            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18868                if (dumpState.onTitlePrinted()) pw.println();
18869                dumpCompilerStatsLPr(pw, packageName);
18870            }
18871
18872            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18873                if (dumpState.onTitlePrinted()) pw.println();
18874                mSettings.dumpReadMessagesLPr(pw, dumpState);
18875
18876                pw.println();
18877                pw.println("Package warning messages:");
18878                BufferedReader in = null;
18879                String line = null;
18880                try {
18881                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18882                    while ((line = in.readLine()) != null) {
18883                        if (line.contains("ignored: updated version")) continue;
18884                        pw.println(line);
18885                    }
18886                } catch (IOException ignored) {
18887                } finally {
18888                    IoUtils.closeQuietly(in);
18889                }
18890            }
18891
18892            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18893                BufferedReader in = null;
18894                String line = null;
18895                try {
18896                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18897                    while ((line = in.readLine()) != null) {
18898                        if (line.contains("ignored: updated version")) continue;
18899                        pw.print("msg,");
18900                        pw.println(line);
18901                    }
18902                } catch (IOException ignored) {
18903                } finally {
18904                    IoUtils.closeQuietly(in);
18905                }
18906            }
18907        }
18908    }
18909
18910    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18911        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18912        ipw.println();
18913        ipw.println("Dexopt state:");
18914        ipw.increaseIndent();
18915        Collection<PackageParser.Package> packages = null;
18916        if (packageName != null) {
18917            PackageParser.Package targetPackage = mPackages.get(packageName);
18918            if (targetPackage != null) {
18919                packages = Collections.singletonList(targetPackage);
18920            } else {
18921                ipw.println("Unable to find package: " + packageName);
18922                return;
18923            }
18924        } else {
18925            packages = mPackages.values();
18926        }
18927
18928        for (PackageParser.Package pkg : packages) {
18929            ipw.println("[" + pkg.packageName + "]");
18930            ipw.increaseIndent();
18931            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18932            ipw.decreaseIndent();
18933        }
18934    }
18935
18936    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
18937        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18938        ipw.println();
18939        ipw.println("Compiler stats:");
18940        ipw.increaseIndent();
18941        Collection<PackageParser.Package> packages = null;
18942        if (packageName != null) {
18943            PackageParser.Package targetPackage = mPackages.get(packageName);
18944            if (targetPackage != null) {
18945                packages = Collections.singletonList(targetPackage);
18946            } else {
18947                ipw.println("Unable to find package: " + packageName);
18948                return;
18949            }
18950        } else {
18951            packages = mPackages.values();
18952        }
18953
18954        for (PackageParser.Package pkg : packages) {
18955            ipw.println("[" + pkg.packageName + "]");
18956            ipw.increaseIndent();
18957
18958            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
18959            if (stats == null) {
18960                ipw.println("(No recorded stats)");
18961            } else {
18962                stats.dump(ipw);
18963            }
18964            ipw.decreaseIndent();
18965        }
18966    }
18967
18968    private String dumpDomainString(String packageName) {
18969        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18970                .getList();
18971        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18972
18973        ArraySet<String> result = new ArraySet<>();
18974        if (iviList.size() > 0) {
18975            for (IntentFilterVerificationInfo ivi : iviList) {
18976                for (String host : ivi.getDomains()) {
18977                    result.add(host);
18978                }
18979            }
18980        }
18981        if (filters != null && filters.size() > 0) {
18982            for (IntentFilter filter : filters) {
18983                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18984                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18985                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18986                    result.addAll(filter.getHostsList());
18987                }
18988            }
18989        }
18990
18991        StringBuilder sb = new StringBuilder(result.size() * 16);
18992        for (String domain : result) {
18993            if (sb.length() > 0) sb.append(" ");
18994            sb.append(domain);
18995        }
18996        return sb.toString();
18997    }
18998
18999    // ------- apps on sdcard specific code -------
19000    static final boolean DEBUG_SD_INSTALL = false;
19001
19002    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19003
19004    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19005
19006    private boolean mMediaMounted = false;
19007
19008    static String getEncryptKey() {
19009        try {
19010            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19011                    SD_ENCRYPTION_KEYSTORE_NAME);
19012            if (sdEncKey == null) {
19013                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19014                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19015                if (sdEncKey == null) {
19016                    Slog.e(TAG, "Failed to create encryption keys");
19017                    return null;
19018                }
19019            }
19020            return sdEncKey;
19021        } catch (NoSuchAlgorithmException nsae) {
19022            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19023            return null;
19024        } catch (IOException ioe) {
19025            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19026            return null;
19027        }
19028    }
19029
19030    /*
19031     * Update media status on PackageManager.
19032     */
19033    @Override
19034    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19035        int callingUid = Binder.getCallingUid();
19036        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19037            throw new SecurityException("Media status can only be updated by the system");
19038        }
19039        // reader; this apparently protects mMediaMounted, but should probably
19040        // be a different lock in that case.
19041        synchronized (mPackages) {
19042            Log.i(TAG, "Updating external media status from "
19043                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19044                    + (mediaStatus ? "mounted" : "unmounted"));
19045            if (DEBUG_SD_INSTALL)
19046                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19047                        + ", mMediaMounted=" + mMediaMounted);
19048            if (mediaStatus == mMediaMounted) {
19049                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19050                        : 0, -1);
19051                mHandler.sendMessage(msg);
19052                return;
19053            }
19054            mMediaMounted = mediaStatus;
19055        }
19056        // Queue up an async operation since the package installation may take a
19057        // little while.
19058        mHandler.post(new Runnable() {
19059            public void run() {
19060                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19061            }
19062        });
19063    }
19064
19065    /**
19066     * Called by MountService when the initial ASECs to scan are available.
19067     * Should block until all the ASEC containers are finished being scanned.
19068     */
19069    public void scanAvailableAsecs() {
19070        updateExternalMediaStatusInner(true, false, false);
19071    }
19072
19073    /*
19074     * Collect information of applications on external media, map them against
19075     * existing containers and update information based on current mount status.
19076     * Please note that we always have to report status if reportStatus has been
19077     * set to true especially when unloading packages.
19078     */
19079    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19080            boolean externalStorage) {
19081        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19082        int[] uidArr = EmptyArray.INT;
19083
19084        final String[] list = PackageHelper.getSecureContainerList();
19085        if (ArrayUtils.isEmpty(list)) {
19086            Log.i(TAG, "No secure containers found");
19087        } else {
19088            // Process list of secure containers and categorize them
19089            // as active or stale based on their package internal state.
19090
19091            // reader
19092            synchronized (mPackages) {
19093                for (String cid : list) {
19094                    // Leave stages untouched for now; installer service owns them
19095                    if (PackageInstallerService.isStageName(cid)) continue;
19096
19097                    if (DEBUG_SD_INSTALL)
19098                        Log.i(TAG, "Processing container " + cid);
19099                    String pkgName = getAsecPackageName(cid);
19100                    if (pkgName == null) {
19101                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19102                        continue;
19103                    }
19104                    if (DEBUG_SD_INSTALL)
19105                        Log.i(TAG, "Looking for pkg : " + pkgName);
19106
19107                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19108                    if (ps == null) {
19109                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19110                        continue;
19111                    }
19112
19113                    /*
19114                     * Skip packages that are not external if we're unmounting
19115                     * external storage.
19116                     */
19117                    if (externalStorage && !isMounted && !isExternal(ps)) {
19118                        continue;
19119                    }
19120
19121                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19122                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19123                    // The package status is changed only if the code path
19124                    // matches between settings and the container id.
19125                    if (ps.codePathString != null
19126                            && ps.codePathString.startsWith(args.getCodePath())) {
19127                        if (DEBUG_SD_INSTALL) {
19128                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19129                                    + " at code path: " + ps.codePathString);
19130                        }
19131
19132                        // We do have a valid package installed on sdcard
19133                        processCids.put(args, ps.codePathString);
19134                        final int uid = ps.appId;
19135                        if (uid != -1) {
19136                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19137                        }
19138                    } else {
19139                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19140                                + ps.codePathString);
19141                    }
19142                }
19143            }
19144
19145            Arrays.sort(uidArr);
19146        }
19147
19148        // Process packages with valid entries.
19149        if (isMounted) {
19150            if (DEBUG_SD_INSTALL)
19151                Log.i(TAG, "Loading packages");
19152            loadMediaPackages(processCids, uidArr, externalStorage);
19153            startCleaningPackages();
19154            mInstallerService.onSecureContainersAvailable();
19155        } else {
19156            if (DEBUG_SD_INSTALL)
19157                Log.i(TAG, "Unloading packages");
19158            unloadMediaPackages(processCids, uidArr, reportStatus);
19159        }
19160    }
19161
19162    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19163            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19164        final int size = infos.size();
19165        final String[] packageNames = new String[size];
19166        final int[] packageUids = new int[size];
19167        for (int i = 0; i < size; i++) {
19168            final ApplicationInfo info = infos.get(i);
19169            packageNames[i] = info.packageName;
19170            packageUids[i] = info.uid;
19171        }
19172        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19173                finishedReceiver);
19174    }
19175
19176    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19177            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19178        sendResourcesChangedBroadcast(mediaStatus, replacing,
19179                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19180    }
19181
19182    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19183            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19184        int size = pkgList.length;
19185        if (size > 0) {
19186            // Send broadcasts here
19187            Bundle extras = new Bundle();
19188            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19189            if (uidArr != null) {
19190                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19191            }
19192            if (replacing) {
19193                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19194            }
19195            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19196                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19197            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19198        }
19199    }
19200
19201   /*
19202     * Look at potentially valid container ids from processCids If package
19203     * information doesn't match the one on record or package scanning fails,
19204     * the cid is added to list of removeCids. We currently don't delete stale
19205     * containers.
19206     */
19207    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19208            boolean externalStorage) {
19209        ArrayList<String> pkgList = new ArrayList<String>();
19210        Set<AsecInstallArgs> keys = processCids.keySet();
19211
19212        for (AsecInstallArgs args : keys) {
19213            String codePath = processCids.get(args);
19214            if (DEBUG_SD_INSTALL)
19215                Log.i(TAG, "Loading container : " + args.cid);
19216            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19217            try {
19218                // Make sure there are no container errors first.
19219                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19220                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19221                            + " when installing from sdcard");
19222                    continue;
19223                }
19224                // Check code path here.
19225                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19226                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19227                            + " does not match one in settings " + codePath);
19228                    continue;
19229                }
19230                // Parse package
19231                int parseFlags = mDefParseFlags;
19232                if (args.isExternalAsec()) {
19233                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19234                }
19235                if (args.isFwdLocked()) {
19236                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19237                }
19238
19239                synchronized (mInstallLock) {
19240                    PackageParser.Package pkg = null;
19241                    try {
19242                        // Sadly we don't know the package name yet to freeze it
19243                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19244                                SCAN_IGNORE_FROZEN, 0, null);
19245                    } catch (PackageManagerException e) {
19246                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19247                    }
19248                    // Scan the package
19249                    if (pkg != null) {
19250                        /*
19251                         * TODO why is the lock being held? doPostInstall is
19252                         * called in other places without the lock. This needs
19253                         * to be straightened out.
19254                         */
19255                        // writer
19256                        synchronized (mPackages) {
19257                            retCode = PackageManager.INSTALL_SUCCEEDED;
19258                            pkgList.add(pkg.packageName);
19259                            // Post process args
19260                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19261                                    pkg.applicationInfo.uid);
19262                        }
19263                    } else {
19264                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19265                    }
19266                }
19267
19268            } finally {
19269                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19270                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19271                }
19272            }
19273        }
19274        // writer
19275        synchronized (mPackages) {
19276            // If the platform SDK has changed since the last time we booted,
19277            // we need to re-grant app permission to catch any new ones that
19278            // appear. This is really a hack, and means that apps can in some
19279            // cases get permissions that the user didn't initially explicitly
19280            // allow... it would be nice to have some better way to handle
19281            // this situation.
19282            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19283                    : mSettings.getInternalVersion();
19284            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19285                    : StorageManager.UUID_PRIVATE_INTERNAL;
19286
19287            int updateFlags = UPDATE_PERMISSIONS_ALL;
19288            if (ver.sdkVersion != mSdkVersion) {
19289                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19290                        + mSdkVersion + "; regranting permissions for external");
19291                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19292            }
19293            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19294
19295            // Yay, everything is now upgraded
19296            ver.forceCurrent();
19297
19298            // can downgrade to reader
19299            // Persist settings
19300            mSettings.writeLPr();
19301        }
19302        // Send a broadcast to let everyone know we are done processing
19303        if (pkgList.size() > 0) {
19304            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19305        }
19306    }
19307
19308   /*
19309     * Utility method to unload a list of specified containers
19310     */
19311    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19312        // Just unmount all valid containers.
19313        for (AsecInstallArgs arg : cidArgs) {
19314            synchronized (mInstallLock) {
19315                arg.doPostDeleteLI(false);
19316           }
19317       }
19318   }
19319
19320    /*
19321     * Unload packages mounted on external media. This involves deleting package
19322     * data from internal structures, sending broadcasts about disabled packages,
19323     * gc'ing to free up references, unmounting all secure containers
19324     * corresponding to packages on external media, and posting a
19325     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19326     * that we always have to post this message if status has been requested no
19327     * matter what.
19328     */
19329    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19330            final boolean reportStatus) {
19331        if (DEBUG_SD_INSTALL)
19332            Log.i(TAG, "unloading media packages");
19333        ArrayList<String> pkgList = new ArrayList<String>();
19334        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19335        final Set<AsecInstallArgs> keys = processCids.keySet();
19336        for (AsecInstallArgs args : keys) {
19337            String pkgName = args.getPackageName();
19338            if (DEBUG_SD_INSTALL)
19339                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19340            // Delete package internally
19341            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19342            synchronized (mInstallLock) {
19343                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19344                final boolean res;
19345                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19346                        "unloadMediaPackages")) {
19347                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19348                            null);
19349                }
19350                if (res) {
19351                    pkgList.add(pkgName);
19352                } else {
19353                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19354                    failedList.add(args);
19355                }
19356            }
19357        }
19358
19359        // reader
19360        synchronized (mPackages) {
19361            // We didn't update the settings after removing each package;
19362            // write them now for all packages.
19363            mSettings.writeLPr();
19364        }
19365
19366        // We have to absolutely send UPDATED_MEDIA_STATUS only
19367        // after confirming that all the receivers processed the ordered
19368        // broadcast when packages get disabled, force a gc to clean things up.
19369        // and unload all the containers.
19370        if (pkgList.size() > 0) {
19371            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19372                    new IIntentReceiver.Stub() {
19373                public void performReceive(Intent intent, int resultCode, String data,
19374                        Bundle extras, boolean ordered, boolean sticky,
19375                        int sendingUser) throws RemoteException {
19376                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19377                            reportStatus ? 1 : 0, 1, keys);
19378                    mHandler.sendMessage(msg);
19379                }
19380            });
19381        } else {
19382            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19383                    keys);
19384            mHandler.sendMessage(msg);
19385        }
19386    }
19387
19388    private void loadPrivatePackages(final VolumeInfo vol) {
19389        mHandler.post(new Runnable() {
19390            @Override
19391            public void run() {
19392                loadPrivatePackagesInner(vol);
19393            }
19394        });
19395    }
19396
19397    private void loadPrivatePackagesInner(VolumeInfo vol) {
19398        final String volumeUuid = vol.fsUuid;
19399        if (TextUtils.isEmpty(volumeUuid)) {
19400            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19401            return;
19402        }
19403
19404        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19405        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19406        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19407
19408        final VersionInfo ver;
19409        final List<PackageSetting> packages;
19410        synchronized (mPackages) {
19411            ver = mSettings.findOrCreateVersion(volumeUuid);
19412            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19413        }
19414
19415        for (PackageSetting ps : packages) {
19416            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19417            synchronized (mInstallLock) {
19418                final PackageParser.Package pkg;
19419                try {
19420                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19421                    loaded.add(pkg.applicationInfo);
19422
19423                } catch (PackageManagerException e) {
19424                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19425                }
19426
19427                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19428                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19429                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19430                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19431                }
19432            }
19433        }
19434
19435        // Reconcile app data for all started/unlocked users
19436        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19437        final UserManager um = mContext.getSystemService(UserManager.class);
19438        UserManagerInternal umInternal = getUserManagerInternal();
19439        for (UserInfo user : um.getUsers()) {
19440            final int flags;
19441            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19442                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19443            } else if (umInternal.isUserRunning(user.id)) {
19444                flags = StorageManager.FLAG_STORAGE_DE;
19445            } else {
19446                continue;
19447            }
19448
19449            try {
19450                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19451                synchronized (mInstallLock) {
19452                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19453                }
19454            } catch (IllegalStateException e) {
19455                // Device was probably ejected, and we'll process that event momentarily
19456                Slog.w(TAG, "Failed to prepare storage: " + e);
19457            }
19458        }
19459
19460        synchronized (mPackages) {
19461            int updateFlags = UPDATE_PERMISSIONS_ALL;
19462            if (ver.sdkVersion != mSdkVersion) {
19463                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19464                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19465                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19466            }
19467            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19468
19469            // Yay, everything is now upgraded
19470            ver.forceCurrent();
19471
19472            mSettings.writeLPr();
19473        }
19474
19475        for (PackageFreezer freezer : freezers) {
19476            freezer.close();
19477        }
19478
19479        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19480        sendResourcesChangedBroadcast(true, false, loaded, null);
19481    }
19482
19483    private void unloadPrivatePackages(final VolumeInfo vol) {
19484        mHandler.post(new Runnable() {
19485            @Override
19486            public void run() {
19487                unloadPrivatePackagesInner(vol);
19488            }
19489        });
19490    }
19491
19492    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19493        final String volumeUuid = vol.fsUuid;
19494        if (TextUtils.isEmpty(volumeUuid)) {
19495            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19496            return;
19497        }
19498
19499        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19500        synchronized (mInstallLock) {
19501        synchronized (mPackages) {
19502            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19503            for (PackageSetting ps : packages) {
19504                if (ps.pkg == null) continue;
19505
19506                final ApplicationInfo info = ps.pkg.applicationInfo;
19507                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19508                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19509
19510                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19511                        "unloadPrivatePackagesInner")) {
19512                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19513                            false, null)) {
19514                        unloaded.add(info);
19515                    } else {
19516                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19517                    }
19518                }
19519
19520                // Try very hard to release any references to this package
19521                // so we don't risk the system server being killed due to
19522                // open FDs
19523                AttributeCache.instance().removePackage(ps.name);
19524            }
19525
19526            mSettings.writeLPr();
19527        }
19528        }
19529
19530        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19531        sendResourcesChangedBroadcast(false, false, unloaded, null);
19532
19533        // Try very hard to release any references to this path so we don't risk
19534        // the system server being killed due to open FDs
19535        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19536
19537        for (int i = 0; i < 3; i++) {
19538            System.gc();
19539            System.runFinalization();
19540        }
19541    }
19542
19543    /**
19544     * Prepare storage areas for given user on all mounted devices.
19545     */
19546    void prepareUserData(int userId, int userSerial, int flags) {
19547        synchronized (mInstallLock) {
19548            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19549            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19550                final String volumeUuid = vol.getFsUuid();
19551                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19552            }
19553        }
19554    }
19555
19556    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19557            boolean allowRecover) {
19558        // Prepare storage and verify that serial numbers are consistent; if
19559        // there's a mismatch we need to destroy to avoid leaking data
19560        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19561        try {
19562            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19563
19564            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19565                UserManagerService.enforceSerialNumber(
19566                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19567                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19568                    UserManagerService.enforceSerialNumber(
19569                            Environment.getDataSystemDeDirectory(userId), userSerial);
19570                }
19571            }
19572            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19573                UserManagerService.enforceSerialNumber(
19574                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19575                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19576                    UserManagerService.enforceSerialNumber(
19577                            Environment.getDataSystemCeDirectory(userId), userSerial);
19578                }
19579            }
19580
19581            synchronized (mInstallLock) {
19582                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19583            }
19584        } catch (Exception e) {
19585            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19586                    + " because we failed to prepare: " + e);
19587            destroyUserDataLI(volumeUuid, userId,
19588                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19589
19590            if (allowRecover) {
19591                // Try one last time; if we fail again we're really in trouble
19592                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19593            }
19594        }
19595    }
19596
19597    /**
19598     * Destroy storage areas for given user on all mounted devices.
19599     */
19600    void destroyUserData(int userId, int flags) {
19601        synchronized (mInstallLock) {
19602            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19603            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19604                final String volumeUuid = vol.getFsUuid();
19605                destroyUserDataLI(volumeUuid, userId, flags);
19606            }
19607        }
19608    }
19609
19610    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19611        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19612        try {
19613            // Clean up app data, profile data, and media data
19614            mInstaller.destroyUserData(volumeUuid, userId, flags);
19615
19616            // Clean up system data
19617            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19618                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19619                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19620                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19621                }
19622                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19623                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19624                }
19625            }
19626
19627            // Data with special labels is now gone, so finish the job
19628            storage.destroyUserStorage(volumeUuid, userId, flags);
19629
19630        } catch (Exception e) {
19631            logCriticalInfo(Log.WARN,
19632                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19633        }
19634    }
19635
19636    /**
19637     * Examine all users present on given mounted volume, and destroy data
19638     * belonging to users that are no longer valid, or whose user ID has been
19639     * recycled.
19640     */
19641    private void reconcileUsers(String volumeUuid) {
19642        final List<File> files = new ArrayList<>();
19643        Collections.addAll(files, FileUtils
19644                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19645        Collections.addAll(files, FileUtils
19646                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19647        Collections.addAll(files, FileUtils
19648                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19649        Collections.addAll(files, FileUtils
19650                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19651        for (File file : files) {
19652            if (!file.isDirectory()) continue;
19653
19654            final int userId;
19655            final UserInfo info;
19656            try {
19657                userId = Integer.parseInt(file.getName());
19658                info = sUserManager.getUserInfo(userId);
19659            } catch (NumberFormatException e) {
19660                Slog.w(TAG, "Invalid user directory " + file);
19661                continue;
19662            }
19663
19664            boolean destroyUser = false;
19665            if (info == null) {
19666                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19667                        + " because no matching user was found");
19668                destroyUser = true;
19669            } else if (!mOnlyCore) {
19670                try {
19671                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19672                } catch (IOException e) {
19673                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19674                            + " because we failed to enforce serial number: " + e);
19675                    destroyUser = true;
19676                }
19677            }
19678
19679            if (destroyUser) {
19680                synchronized (mInstallLock) {
19681                    destroyUserDataLI(volumeUuid, userId,
19682                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19683                }
19684            }
19685        }
19686    }
19687
19688    private void assertPackageKnown(String volumeUuid, String packageName)
19689            throws PackageManagerException {
19690        synchronized (mPackages) {
19691            final PackageSetting ps = mSettings.mPackages.get(packageName);
19692            if (ps == null) {
19693                throw new PackageManagerException("Package " + packageName + " is unknown");
19694            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19695                throw new PackageManagerException(
19696                        "Package " + packageName + " found on unknown volume " + volumeUuid
19697                                + "; expected volume " + ps.volumeUuid);
19698            }
19699        }
19700    }
19701
19702    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19703            throws PackageManagerException {
19704        synchronized (mPackages) {
19705            final PackageSetting ps = mSettings.mPackages.get(packageName);
19706            if (ps == null) {
19707                throw new PackageManagerException("Package " + packageName + " is unknown");
19708            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19709                throw new PackageManagerException(
19710                        "Package " + packageName + " found on unknown volume " + volumeUuid
19711                                + "; expected volume " + ps.volumeUuid);
19712            } else if (!ps.getInstalled(userId)) {
19713                throw new PackageManagerException(
19714                        "Package " + packageName + " not installed for user " + userId);
19715            }
19716        }
19717    }
19718
19719    /**
19720     * Examine all apps present on given mounted volume, and destroy apps that
19721     * aren't expected, either due to uninstallation or reinstallation on
19722     * another volume.
19723     */
19724    private void reconcileApps(String volumeUuid) {
19725        final File[] files = FileUtils
19726                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19727        for (File file : files) {
19728            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19729                    && !PackageInstallerService.isStageName(file.getName());
19730            if (!isPackage) {
19731                // Ignore entries which are not packages
19732                continue;
19733            }
19734
19735            try {
19736                final PackageLite pkg = PackageParser.parsePackageLite(file,
19737                        PackageParser.PARSE_MUST_BE_APK);
19738                assertPackageKnown(volumeUuid, pkg.packageName);
19739
19740            } catch (PackageParserException | PackageManagerException e) {
19741                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19742                synchronized (mInstallLock) {
19743                    removeCodePathLI(file);
19744                }
19745            }
19746        }
19747    }
19748
19749    /**
19750     * Reconcile all app data for the given user.
19751     * <p>
19752     * Verifies that directories exist and that ownership and labeling is
19753     * correct for all installed apps on all mounted volumes.
19754     */
19755    void reconcileAppsData(int userId, int flags) {
19756        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19757        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19758            final String volumeUuid = vol.getFsUuid();
19759            synchronized (mInstallLock) {
19760                reconcileAppsDataLI(volumeUuid, userId, flags);
19761            }
19762        }
19763    }
19764
19765    /**
19766     * Reconcile all app data on given mounted volume.
19767     * <p>
19768     * Destroys app data that isn't expected, either due to uninstallation or
19769     * reinstallation on another volume.
19770     * <p>
19771     * Verifies that directories exist and that ownership and labeling is
19772     * correct for all installed apps.
19773     */
19774    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19775        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19776                + Integer.toHexString(flags));
19777
19778        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19779        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19780
19781        // First look for stale data that doesn't belong, and check if things
19782        // have changed since we did our last restorecon
19783        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19784            if (StorageManager.isFileEncryptedNativeOrEmulated()
19785                    && !StorageManager.isUserKeyUnlocked(userId)) {
19786                throw new RuntimeException(
19787                        "Yikes, someone asked us to reconcile CE storage while " + userId
19788                                + " was still locked; this would have caused massive data loss!");
19789            }
19790
19791            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19792            for (File file : files) {
19793                final String packageName = file.getName();
19794                try {
19795                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19796                } catch (PackageManagerException e) {
19797                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19798                    try {
19799                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19800                                StorageManager.FLAG_STORAGE_CE, 0);
19801                    } catch (InstallerException e2) {
19802                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19803                    }
19804                }
19805            }
19806        }
19807        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19808            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19809            for (File file : files) {
19810                final String packageName = file.getName();
19811                try {
19812                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19813                } catch (PackageManagerException e) {
19814                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19815                    try {
19816                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19817                                StorageManager.FLAG_STORAGE_DE, 0);
19818                    } catch (InstallerException e2) {
19819                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19820                    }
19821                }
19822            }
19823        }
19824
19825        // Ensure that data directories are ready to roll for all packages
19826        // installed for this volume and user
19827        final List<PackageSetting> packages;
19828        synchronized (mPackages) {
19829            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19830        }
19831        int preparedCount = 0;
19832        for (PackageSetting ps : packages) {
19833            final String packageName = ps.name;
19834            if (ps.pkg == null) {
19835                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19836                // TODO: might be due to legacy ASEC apps; we should circle back
19837                // and reconcile again once they're scanned
19838                continue;
19839            }
19840
19841            if (ps.getInstalled(userId)) {
19842                prepareAppDataLIF(ps.pkg, userId, flags);
19843
19844                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19845                    // We may have just shuffled around app data directories, so
19846                    // prepare them one more time
19847                    prepareAppDataLIF(ps.pkg, userId, flags);
19848                }
19849
19850                preparedCount++;
19851            }
19852        }
19853
19854        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
19855    }
19856
19857    /**
19858     * Prepare app data for the given app just after it was installed or
19859     * upgraded. This method carefully only touches users that it's installed
19860     * for, and it forces a restorecon to handle any seinfo changes.
19861     * <p>
19862     * Verifies that directories exist and that ownership and labeling is
19863     * correct for all installed apps. If there is an ownership mismatch, it
19864     * will try recovering system apps by wiping data; third-party app data is
19865     * left intact.
19866     * <p>
19867     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19868     */
19869    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19870        final PackageSetting ps;
19871        synchronized (mPackages) {
19872            ps = mSettings.mPackages.get(pkg.packageName);
19873            mSettings.writeKernelMappingLPr(ps);
19874        }
19875
19876        final UserManager um = mContext.getSystemService(UserManager.class);
19877        UserManagerInternal umInternal = getUserManagerInternal();
19878        for (UserInfo user : um.getUsers()) {
19879            final int flags;
19880            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19881                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19882            } else if (umInternal.isUserRunning(user.id)) {
19883                flags = StorageManager.FLAG_STORAGE_DE;
19884            } else {
19885                continue;
19886            }
19887
19888            if (ps.getInstalled(user.id)) {
19889                // TODO: when user data is locked, mark that we're still dirty
19890                prepareAppDataLIF(pkg, user.id, flags);
19891            }
19892        }
19893    }
19894
19895    /**
19896     * Prepare app data for the given app.
19897     * <p>
19898     * Verifies that directories exist and that ownership and labeling is
19899     * correct for all installed apps. If there is an ownership mismatch, this
19900     * will try recovering system apps by wiping data; third-party app data is
19901     * left intact.
19902     */
19903    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
19904        if (pkg == null) {
19905            Slog.wtf(TAG, "Package was null!", new Throwable());
19906            return;
19907        }
19908        prepareAppDataLeafLIF(pkg, userId, flags);
19909        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19910        for (int i = 0; i < childCount; i++) {
19911            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
19912        }
19913    }
19914
19915    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19916        if (DEBUG_APP_DATA) {
19917            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19918                    + Integer.toHexString(flags));
19919        }
19920
19921        final String volumeUuid = pkg.volumeUuid;
19922        final String packageName = pkg.packageName;
19923        final ApplicationInfo app = pkg.applicationInfo;
19924        final int appId = UserHandle.getAppId(app.uid);
19925
19926        Preconditions.checkNotNull(app.seinfo);
19927
19928        long ceDataInode = -1;
19929        try {
19930            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19931                    appId, app.seinfo, app.targetSdkVersion);
19932        } catch (InstallerException e) {
19933            if (app.isSystemApp()) {
19934                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19935                        + ", but trying to recover: " + e);
19936                destroyAppDataLeafLIF(pkg, userId, flags);
19937                try {
19938                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19939                            appId, app.seinfo, app.targetSdkVersion);
19940                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19941                } catch (InstallerException e2) {
19942                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19943                }
19944            } else {
19945                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19946            }
19947        }
19948
19949        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
19950            // TODO: mark this structure as dirty so we persist it!
19951            synchronized (mPackages) {
19952                final PackageSetting ps = mSettings.mPackages.get(packageName);
19953                if (ps != null) {
19954                    ps.setCeDataInode(ceDataInode, userId);
19955                }
19956            }
19957        }
19958
19959        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19960    }
19961
19962    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19963        if (pkg == null) {
19964            Slog.wtf(TAG, "Package was null!", new Throwable());
19965            return;
19966        }
19967        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19968        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19969        for (int i = 0; i < childCount; i++) {
19970            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19971        }
19972    }
19973
19974    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19975        final String volumeUuid = pkg.volumeUuid;
19976        final String packageName = pkg.packageName;
19977        final ApplicationInfo app = pkg.applicationInfo;
19978
19979        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19980            // Create a native library symlink only if we have native libraries
19981            // and if the native libraries are 32 bit libraries. We do not provide
19982            // this symlink for 64 bit libraries.
19983            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19984                final String nativeLibPath = app.nativeLibraryDir;
19985                try {
19986                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19987                            nativeLibPath, userId);
19988                } catch (InstallerException e) {
19989                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19990                }
19991            }
19992        }
19993    }
19994
19995    /**
19996     * For system apps on non-FBE devices, this method migrates any existing
19997     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19998     * requested by the app.
19999     */
20000    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20001        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20002                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20003            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20004                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20005            try {
20006                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20007                        storageTarget);
20008            } catch (InstallerException e) {
20009                logCriticalInfo(Log.WARN,
20010                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20011            }
20012            return true;
20013        } else {
20014            return false;
20015        }
20016    }
20017
20018    public PackageFreezer freezePackage(String packageName, String killReason) {
20019        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20020    }
20021
20022    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20023        return new PackageFreezer(packageName, userId, killReason);
20024    }
20025
20026    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20027            String killReason) {
20028        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20029    }
20030
20031    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20032            String killReason) {
20033        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20034            return new PackageFreezer();
20035        } else {
20036            return freezePackage(packageName, userId, killReason);
20037        }
20038    }
20039
20040    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20041            String killReason) {
20042        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20043    }
20044
20045    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20046            String killReason) {
20047        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20048            return new PackageFreezer();
20049        } else {
20050            return freezePackage(packageName, userId, killReason);
20051        }
20052    }
20053
20054    /**
20055     * Class that freezes and kills the given package upon creation, and
20056     * unfreezes it upon closing. This is typically used when doing surgery on
20057     * app code/data to prevent the app from running while you're working.
20058     */
20059    private class PackageFreezer implements AutoCloseable {
20060        private final String mPackageName;
20061        private final PackageFreezer[] mChildren;
20062
20063        private final boolean mWeFroze;
20064
20065        private final AtomicBoolean mClosed = new AtomicBoolean();
20066        private final CloseGuard mCloseGuard = CloseGuard.get();
20067
20068        /**
20069         * Create and return a stub freezer that doesn't actually do anything,
20070         * typically used when someone requested
20071         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20072         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20073         */
20074        public PackageFreezer() {
20075            mPackageName = null;
20076            mChildren = null;
20077            mWeFroze = false;
20078            mCloseGuard.open("close");
20079        }
20080
20081        public PackageFreezer(String packageName, int userId, String killReason) {
20082            synchronized (mPackages) {
20083                mPackageName = packageName;
20084                mWeFroze = mFrozenPackages.add(mPackageName);
20085
20086                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20087                if (ps != null) {
20088                    killApplication(ps.name, ps.appId, userId, killReason);
20089                }
20090
20091                final PackageParser.Package p = mPackages.get(packageName);
20092                if (p != null && p.childPackages != null) {
20093                    final int N = p.childPackages.size();
20094                    mChildren = new PackageFreezer[N];
20095                    for (int i = 0; i < N; i++) {
20096                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20097                                userId, killReason);
20098                    }
20099                } else {
20100                    mChildren = null;
20101                }
20102            }
20103            mCloseGuard.open("close");
20104        }
20105
20106        @Override
20107        protected void finalize() throws Throwable {
20108            try {
20109                mCloseGuard.warnIfOpen();
20110                close();
20111            } finally {
20112                super.finalize();
20113            }
20114        }
20115
20116        @Override
20117        public void close() {
20118            mCloseGuard.close();
20119            if (mClosed.compareAndSet(false, true)) {
20120                synchronized (mPackages) {
20121                    if (mWeFroze) {
20122                        mFrozenPackages.remove(mPackageName);
20123                    }
20124
20125                    if (mChildren != null) {
20126                        for (PackageFreezer freezer : mChildren) {
20127                            freezer.close();
20128                        }
20129                    }
20130                }
20131            }
20132        }
20133    }
20134
20135    /**
20136     * Verify that given package is currently frozen.
20137     */
20138    private void checkPackageFrozen(String packageName) {
20139        synchronized (mPackages) {
20140            if (!mFrozenPackages.contains(packageName)) {
20141                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20142            }
20143        }
20144    }
20145
20146    @Override
20147    public int movePackage(final String packageName, final String volumeUuid) {
20148        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20149
20150        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20151        final int moveId = mNextMoveId.getAndIncrement();
20152        mHandler.post(new Runnable() {
20153            @Override
20154            public void run() {
20155                try {
20156                    movePackageInternal(packageName, volumeUuid, moveId, user);
20157                } catch (PackageManagerException e) {
20158                    Slog.w(TAG, "Failed to move " + packageName, e);
20159                    mMoveCallbacks.notifyStatusChanged(moveId,
20160                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20161                }
20162            }
20163        });
20164        return moveId;
20165    }
20166
20167    private void movePackageInternal(final String packageName, final String volumeUuid,
20168            final int moveId, UserHandle user) throws PackageManagerException {
20169        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20170        final PackageManager pm = mContext.getPackageManager();
20171
20172        final boolean currentAsec;
20173        final String currentVolumeUuid;
20174        final File codeFile;
20175        final String installerPackageName;
20176        final String packageAbiOverride;
20177        final int appId;
20178        final String seinfo;
20179        final String label;
20180        final int targetSdkVersion;
20181        final PackageFreezer freezer;
20182        final int[] installedUserIds;
20183
20184        // reader
20185        synchronized (mPackages) {
20186            final PackageParser.Package pkg = mPackages.get(packageName);
20187            final PackageSetting ps = mSettings.mPackages.get(packageName);
20188            if (pkg == null || ps == null) {
20189                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20190            }
20191
20192            if (pkg.applicationInfo.isSystemApp()) {
20193                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20194                        "Cannot move system application");
20195            }
20196
20197            if (pkg.applicationInfo.isExternalAsec()) {
20198                currentAsec = true;
20199                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20200            } else if (pkg.applicationInfo.isForwardLocked()) {
20201                currentAsec = true;
20202                currentVolumeUuid = "forward_locked";
20203            } else {
20204                currentAsec = false;
20205                currentVolumeUuid = ps.volumeUuid;
20206
20207                final File probe = new File(pkg.codePath);
20208                final File probeOat = new File(probe, "oat");
20209                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20210                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20211                            "Move only supported for modern cluster style installs");
20212                }
20213            }
20214
20215            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20216                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20217                        "Package already moved to " + volumeUuid);
20218            }
20219            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20220                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20221                        "Device admin cannot be moved");
20222            }
20223
20224            if (mFrozenPackages.contains(packageName)) {
20225                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20226                        "Failed to move already frozen package");
20227            }
20228
20229            codeFile = new File(pkg.codePath);
20230            installerPackageName = ps.installerPackageName;
20231            packageAbiOverride = ps.cpuAbiOverrideString;
20232            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20233            seinfo = pkg.applicationInfo.seinfo;
20234            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20235            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20236            freezer = freezePackage(packageName, "movePackageInternal");
20237            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20238        }
20239
20240        final Bundle extras = new Bundle();
20241        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20242        extras.putString(Intent.EXTRA_TITLE, label);
20243        mMoveCallbacks.notifyCreated(moveId, extras);
20244
20245        int installFlags;
20246        final boolean moveCompleteApp;
20247        final File measurePath;
20248
20249        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20250            installFlags = INSTALL_INTERNAL;
20251            moveCompleteApp = !currentAsec;
20252            measurePath = Environment.getDataAppDirectory(volumeUuid);
20253        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20254            installFlags = INSTALL_EXTERNAL;
20255            moveCompleteApp = false;
20256            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20257        } else {
20258            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20259            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20260                    || !volume.isMountedWritable()) {
20261                freezer.close();
20262                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20263                        "Move location not mounted private volume");
20264            }
20265
20266            Preconditions.checkState(!currentAsec);
20267
20268            installFlags = INSTALL_INTERNAL;
20269            moveCompleteApp = true;
20270            measurePath = Environment.getDataAppDirectory(volumeUuid);
20271        }
20272
20273        final PackageStats stats = new PackageStats(null, -1);
20274        synchronized (mInstaller) {
20275            for (int userId : installedUserIds) {
20276                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20277                    freezer.close();
20278                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20279                            "Failed to measure package size");
20280                }
20281            }
20282        }
20283
20284        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20285                + stats.dataSize);
20286
20287        final long startFreeBytes = measurePath.getFreeSpace();
20288        final long sizeBytes;
20289        if (moveCompleteApp) {
20290            sizeBytes = stats.codeSize + stats.dataSize;
20291        } else {
20292            sizeBytes = stats.codeSize;
20293        }
20294
20295        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20296            freezer.close();
20297            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20298                    "Not enough free space to move");
20299        }
20300
20301        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20302
20303        final CountDownLatch installedLatch = new CountDownLatch(1);
20304        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20305            @Override
20306            public void onUserActionRequired(Intent intent) throws RemoteException {
20307                throw new IllegalStateException();
20308            }
20309
20310            @Override
20311            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20312                    Bundle extras) throws RemoteException {
20313                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20314                        + PackageManager.installStatusToString(returnCode, msg));
20315
20316                installedLatch.countDown();
20317                freezer.close();
20318
20319                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20320                switch (status) {
20321                    case PackageInstaller.STATUS_SUCCESS:
20322                        mMoveCallbacks.notifyStatusChanged(moveId,
20323                                PackageManager.MOVE_SUCCEEDED);
20324                        break;
20325                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20326                        mMoveCallbacks.notifyStatusChanged(moveId,
20327                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20328                        break;
20329                    default:
20330                        mMoveCallbacks.notifyStatusChanged(moveId,
20331                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20332                        break;
20333                }
20334            }
20335        };
20336
20337        final MoveInfo move;
20338        if (moveCompleteApp) {
20339            // Kick off a thread to report progress estimates
20340            new Thread() {
20341                @Override
20342                public void run() {
20343                    while (true) {
20344                        try {
20345                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20346                                break;
20347                            }
20348                        } catch (InterruptedException ignored) {
20349                        }
20350
20351                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20352                        final int progress = 10 + (int) MathUtils.constrain(
20353                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20354                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20355                    }
20356                }
20357            }.start();
20358
20359            final String dataAppName = codeFile.getName();
20360            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20361                    dataAppName, appId, seinfo, targetSdkVersion);
20362        } else {
20363            move = null;
20364        }
20365
20366        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20367
20368        final Message msg = mHandler.obtainMessage(INIT_COPY);
20369        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20370        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20371                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20372                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20373        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20374        msg.obj = params;
20375
20376        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20377                System.identityHashCode(msg.obj));
20378        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20379                System.identityHashCode(msg.obj));
20380
20381        mHandler.sendMessage(msg);
20382    }
20383
20384    @Override
20385    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20386        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20387
20388        final int realMoveId = mNextMoveId.getAndIncrement();
20389        final Bundle extras = new Bundle();
20390        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20391        mMoveCallbacks.notifyCreated(realMoveId, extras);
20392
20393        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20394            @Override
20395            public void onCreated(int moveId, Bundle extras) {
20396                // Ignored
20397            }
20398
20399            @Override
20400            public void onStatusChanged(int moveId, int status, long estMillis) {
20401                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20402            }
20403        };
20404
20405        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20406        storage.setPrimaryStorageUuid(volumeUuid, callback);
20407        return realMoveId;
20408    }
20409
20410    @Override
20411    public int getMoveStatus(int moveId) {
20412        mContext.enforceCallingOrSelfPermission(
20413                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20414        return mMoveCallbacks.mLastStatus.get(moveId);
20415    }
20416
20417    @Override
20418    public void registerMoveCallback(IPackageMoveObserver callback) {
20419        mContext.enforceCallingOrSelfPermission(
20420                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20421        mMoveCallbacks.register(callback);
20422    }
20423
20424    @Override
20425    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20426        mContext.enforceCallingOrSelfPermission(
20427                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20428        mMoveCallbacks.unregister(callback);
20429    }
20430
20431    @Override
20432    public boolean setInstallLocation(int loc) {
20433        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20434                null);
20435        if (getInstallLocation() == loc) {
20436            return true;
20437        }
20438        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20439                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20440            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20441                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20442            return true;
20443        }
20444        return false;
20445   }
20446
20447    @Override
20448    public int getInstallLocation() {
20449        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20450                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20451                PackageHelper.APP_INSTALL_AUTO);
20452    }
20453
20454    /** Called by UserManagerService */
20455    void cleanUpUser(UserManagerService userManager, int userHandle) {
20456        synchronized (mPackages) {
20457            mDirtyUsers.remove(userHandle);
20458            mUserNeedsBadging.delete(userHandle);
20459            mSettings.removeUserLPw(userHandle);
20460            mPendingBroadcasts.remove(userHandle);
20461            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20462            removeUnusedPackagesLPw(userManager, userHandle);
20463        }
20464    }
20465
20466    /**
20467     * We're removing userHandle and would like to remove any downloaded packages
20468     * that are no longer in use by any other user.
20469     * @param userHandle the user being removed
20470     */
20471    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20472        final boolean DEBUG_CLEAN_APKS = false;
20473        int [] users = userManager.getUserIds();
20474        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20475        while (psit.hasNext()) {
20476            PackageSetting ps = psit.next();
20477            if (ps.pkg == null) {
20478                continue;
20479            }
20480            final String packageName = ps.pkg.packageName;
20481            // Skip over if system app
20482            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20483                continue;
20484            }
20485            if (DEBUG_CLEAN_APKS) {
20486                Slog.i(TAG, "Checking package " + packageName);
20487            }
20488            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20489            if (keep) {
20490                if (DEBUG_CLEAN_APKS) {
20491                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20492                }
20493            } else {
20494                for (int i = 0; i < users.length; i++) {
20495                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20496                        keep = true;
20497                        if (DEBUG_CLEAN_APKS) {
20498                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20499                                    + users[i]);
20500                        }
20501                        break;
20502                    }
20503                }
20504            }
20505            if (!keep) {
20506                if (DEBUG_CLEAN_APKS) {
20507                    Slog.i(TAG, "  Removing package " + packageName);
20508                }
20509                mHandler.post(new Runnable() {
20510                    public void run() {
20511                        deletePackageX(packageName, userHandle, 0);
20512                    } //end run
20513                });
20514            }
20515        }
20516    }
20517
20518    /** Called by UserManagerService */
20519    void createNewUser(int userId) {
20520        synchronized (mInstallLock) {
20521            mSettings.createNewUserLI(this, mInstaller, userId);
20522        }
20523        synchronized (mPackages) {
20524            scheduleWritePackageRestrictionsLocked(userId);
20525            scheduleWritePackageListLocked(userId);
20526            applyFactoryDefaultBrowserLPw(userId);
20527            primeDomainVerificationsLPw(userId);
20528        }
20529    }
20530
20531    void onNewUserCreated(final int userId) {
20532        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20533        // If permission review for legacy apps is required, we represent
20534        // dagerous permissions for such apps as always granted runtime
20535        // permissions to keep per user flag state whether review is needed.
20536        // Hence, if a new user is added we have to propagate dangerous
20537        // permission grants for these legacy apps.
20538        if (mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) {
20539            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20540                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20541        }
20542    }
20543
20544    @Override
20545    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20546        mContext.enforceCallingOrSelfPermission(
20547                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20548                "Only package verification agents can read the verifier device identity");
20549
20550        synchronized (mPackages) {
20551            return mSettings.getVerifierDeviceIdentityLPw();
20552        }
20553    }
20554
20555    @Override
20556    public void setPermissionEnforced(String permission, boolean enforced) {
20557        // TODO: Now that we no longer change GID for storage, this should to away.
20558        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20559                "setPermissionEnforced");
20560        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20561            synchronized (mPackages) {
20562                if (mSettings.mReadExternalStorageEnforced == null
20563                        || mSettings.mReadExternalStorageEnforced != enforced) {
20564                    mSettings.mReadExternalStorageEnforced = enforced;
20565                    mSettings.writeLPr();
20566                }
20567            }
20568            // kill any non-foreground processes so we restart them and
20569            // grant/revoke the GID.
20570            final IActivityManager am = ActivityManagerNative.getDefault();
20571            if (am != null) {
20572                final long token = Binder.clearCallingIdentity();
20573                try {
20574                    am.killProcessesBelowForeground("setPermissionEnforcement");
20575                } catch (RemoteException e) {
20576                } finally {
20577                    Binder.restoreCallingIdentity(token);
20578                }
20579            }
20580        } else {
20581            throw new IllegalArgumentException("No selective enforcement for " + permission);
20582        }
20583    }
20584
20585    @Override
20586    @Deprecated
20587    public boolean isPermissionEnforced(String permission) {
20588        return true;
20589    }
20590
20591    @Override
20592    public boolean isStorageLow() {
20593        final long token = Binder.clearCallingIdentity();
20594        try {
20595            final DeviceStorageMonitorInternal
20596                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20597            if (dsm != null) {
20598                return dsm.isMemoryLow();
20599            } else {
20600                return false;
20601            }
20602        } finally {
20603            Binder.restoreCallingIdentity(token);
20604        }
20605    }
20606
20607    @Override
20608    public IPackageInstaller getPackageInstaller() {
20609        return mInstallerService;
20610    }
20611
20612    private boolean userNeedsBadging(int userId) {
20613        int index = mUserNeedsBadging.indexOfKey(userId);
20614        if (index < 0) {
20615            final UserInfo userInfo;
20616            final long token = Binder.clearCallingIdentity();
20617            try {
20618                userInfo = sUserManager.getUserInfo(userId);
20619            } finally {
20620                Binder.restoreCallingIdentity(token);
20621            }
20622            final boolean b;
20623            if (userInfo != null && userInfo.isManagedProfile()) {
20624                b = true;
20625            } else {
20626                b = false;
20627            }
20628            mUserNeedsBadging.put(userId, b);
20629            return b;
20630        }
20631        return mUserNeedsBadging.valueAt(index);
20632    }
20633
20634    @Override
20635    public KeySet getKeySetByAlias(String packageName, String alias) {
20636        if (packageName == null || alias == null) {
20637            return null;
20638        }
20639        synchronized(mPackages) {
20640            final PackageParser.Package pkg = mPackages.get(packageName);
20641            if (pkg == null) {
20642                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20643                throw new IllegalArgumentException("Unknown package: " + packageName);
20644            }
20645            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20646            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20647        }
20648    }
20649
20650    @Override
20651    public KeySet getSigningKeySet(String packageName) {
20652        if (packageName == null) {
20653            return null;
20654        }
20655        synchronized(mPackages) {
20656            final PackageParser.Package pkg = mPackages.get(packageName);
20657            if (pkg == null) {
20658                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20659                throw new IllegalArgumentException("Unknown package: " + packageName);
20660            }
20661            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20662                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20663                throw new SecurityException("May not access signing KeySet of other apps.");
20664            }
20665            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20666            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20667        }
20668    }
20669
20670    @Override
20671    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20672        if (packageName == null || ks == null) {
20673            return false;
20674        }
20675        synchronized(mPackages) {
20676            final PackageParser.Package pkg = mPackages.get(packageName);
20677            if (pkg == null) {
20678                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20679                throw new IllegalArgumentException("Unknown package: " + packageName);
20680            }
20681            IBinder ksh = ks.getToken();
20682            if (ksh instanceof KeySetHandle) {
20683                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20684                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20685            }
20686            return false;
20687        }
20688    }
20689
20690    @Override
20691    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20692        if (packageName == null || ks == null) {
20693            return false;
20694        }
20695        synchronized(mPackages) {
20696            final PackageParser.Package pkg = mPackages.get(packageName);
20697            if (pkg == null) {
20698                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20699                throw new IllegalArgumentException("Unknown package: " + packageName);
20700            }
20701            IBinder ksh = ks.getToken();
20702            if (ksh instanceof KeySetHandle) {
20703                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20704                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20705            }
20706            return false;
20707        }
20708    }
20709
20710    private void deletePackageIfUnusedLPr(final String packageName) {
20711        PackageSetting ps = mSettings.mPackages.get(packageName);
20712        if (ps == null) {
20713            return;
20714        }
20715        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20716            // TODO Implement atomic delete if package is unused
20717            // It is currently possible that the package will be deleted even if it is installed
20718            // after this method returns.
20719            mHandler.post(new Runnable() {
20720                public void run() {
20721                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20722                }
20723            });
20724        }
20725    }
20726
20727    /**
20728     * Check and throw if the given before/after packages would be considered a
20729     * downgrade.
20730     */
20731    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20732            throws PackageManagerException {
20733        if (after.versionCode < before.mVersionCode) {
20734            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20735                    "Update version code " + after.versionCode + " is older than current "
20736                    + before.mVersionCode);
20737        } else if (after.versionCode == before.mVersionCode) {
20738            if (after.baseRevisionCode < before.baseRevisionCode) {
20739                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20740                        "Update base revision code " + after.baseRevisionCode
20741                        + " is older than current " + before.baseRevisionCode);
20742            }
20743
20744            if (!ArrayUtils.isEmpty(after.splitNames)) {
20745                for (int i = 0; i < after.splitNames.length; i++) {
20746                    final String splitName = after.splitNames[i];
20747                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20748                    if (j != -1) {
20749                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20750                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20751                                    "Update split " + splitName + " revision code "
20752                                    + after.splitRevisionCodes[i] + " is older than current "
20753                                    + before.splitRevisionCodes[j]);
20754                        }
20755                    }
20756                }
20757            }
20758        }
20759    }
20760
20761    private static class MoveCallbacks extends Handler {
20762        private static final int MSG_CREATED = 1;
20763        private static final int MSG_STATUS_CHANGED = 2;
20764
20765        private final RemoteCallbackList<IPackageMoveObserver>
20766                mCallbacks = new RemoteCallbackList<>();
20767
20768        private final SparseIntArray mLastStatus = new SparseIntArray();
20769
20770        public MoveCallbacks(Looper looper) {
20771            super(looper);
20772        }
20773
20774        public void register(IPackageMoveObserver callback) {
20775            mCallbacks.register(callback);
20776        }
20777
20778        public void unregister(IPackageMoveObserver callback) {
20779            mCallbacks.unregister(callback);
20780        }
20781
20782        @Override
20783        public void handleMessage(Message msg) {
20784            final SomeArgs args = (SomeArgs) msg.obj;
20785            final int n = mCallbacks.beginBroadcast();
20786            for (int i = 0; i < n; i++) {
20787                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20788                try {
20789                    invokeCallback(callback, msg.what, args);
20790                } catch (RemoteException ignored) {
20791                }
20792            }
20793            mCallbacks.finishBroadcast();
20794            args.recycle();
20795        }
20796
20797        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20798                throws RemoteException {
20799            switch (what) {
20800                case MSG_CREATED: {
20801                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20802                    break;
20803                }
20804                case MSG_STATUS_CHANGED: {
20805                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20806                    break;
20807                }
20808            }
20809        }
20810
20811        private void notifyCreated(int moveId, Bundle extras) {
20812            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20813
20814            final SomeArgs args = SomeArgs.obtain();
20815            args.argi1 = moveId;
20816            args.arg2 = extras;
20817            obtainMessage(MSG_CREATED, args).sendToTarget();
20818        }
20819
20820        private void notifyStatusChanged(int moveId, int status) {
20821            notifyStatusChanged(moveId, status, -1);
20822        }
20823
20824        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20825            Slog.v(TAG, "Move " + moveId + " status " + status);
20826
20827            final SomeArgs args = SomeArgs.obtain();
20828            args.argi1 = moveId;
20829            args.argi2 = status;
20830            args.arg3 = estMillis;
20831            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20832
20833            synchronized (mLastStatus) {
20834                mLastStatus.put(moveId, status);
20835            }
20836        }
20837    }
20838
20839    private final static class OnPermissionChangeListeners extends Handler {
20840        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20841
20842        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20843                new RemoteCallbackList<>();
20844
20845        public OnPermissionChangeListeners(Looper looper) {
20846            super(looper);
20847        }
20848
20849        @Override
20850        public void handleMessage(Message msg) {
20851            switch (msg.what) {
20852                case MSG_ON_PERMISSIONS_CHANGED: {
20853                    final int uid = msg.arg1;
20854                    handleOnPermissionsChanged(uid);
20855                } break;
20856            }
20857        }
20858
20859        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20860            mPermissionListeners.register(listener);
20861
20862        }
20863
20864        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20865            mPermissionListeners.unregister(listener);
20866        }
20867
20868        public void onPermissionsChanged(int uid) {
20869            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20870                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20871            }
20872        }
20873
20874        private void handleOnPermissionsChanged(int uid) {
20875            final int count = mPermissionListeners.beginBroadcast();
20876            try {
20877                for (int i = 0; i < count; i++) {
20878                    IOnPermissionsChangeListener callback = mPermissionListeners
20879                            .getBroadcastItem(i);
20880                    try {
20881                        callback.onPermissionsChanged(uid);
20882                    } catch (RemoteException e) {
20883                        Log.e(TAG, "Permission listener is dead", e);
20884                    }
20885                }
20886            } finally {
20887                mPermissionListeners.finishBroadcast();
20888            }
20889        }
20890    }
20891
20892    private class PackageManagerInternalImpl extends PackageManagerInternal {
20893        @Override
20894        public void setLocationPackagesProvider(PackagesProvider provider) {
20895            synchronized (mPackages) {
20896                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20897            }
20898        }
20899
20900        @Override
20901        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20902            synchronized (mPackages) {
20903                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20904            }
20905        }
20906
20907        @Override
20908        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20909            synchronized (mPackages) {
20910                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20911            }
20912        }
20913
20914        @Override
20915        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20916            synchronized (mPackages) {
20917                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20918            }
20919        }
20920
20921        @Override
20922        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20923            synchronized (mPackages) {
20924                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20925            }
20926        }
20927
20928        @Override
20929        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20930            synchronized (mPackages) {
20931                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20932            }
20933        }
20934
20935        @Override
20936        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20937            synchronized (mPackages) {
20938                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20939                        packageName, userId);
20940            }
20941        }
20942
20943        @Override
20944        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20945            synchronized (mPackages) {
20946                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20947                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20948                        packageName, userId);
20949            }
20950        }
20951
20952        @Override
20953        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20954            synchronized (mPackages) {
20955                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20956                        packageName, userId);
20957            }
20958        }
20959
20960        @Override
20961        public void setKeepUninstalledPackages(final List<String> packageList) {
20962            Preconditions.checkNotNull(packageList);
20963            List<String> removedFromList = null;
20964            synchronized (mPackages) {
20965                if (mKeepUninstalledPackages != null) {
20966                    final int packagesCount = mKeepUninstalledPackages.size();
20967                    for (int i = 0; i < packagesCount; i++) {
20968                        String oldPackage = mKeepUninstalledPackages.get(i);
20969                        if (packageList != null && packageList.contains(oldPackage)) {
20970                            continue;
20971                        }
20972                        if (removedFromList == null) {
20973                            removedFromList = new ArrayList<>();
20974                        }
20975                        removedFromList.add(oldPackage);
20976                    }
20977                }
20978                mKeepUninstalledPackages = new ArrayList<>(packageList);
20979                if (removedFromList != null) {
20980                    final int removedCount = removedFromList.size();
20981                    for (int i = 0; i < removedCount; i++) {
20982                        deletePackageIfUnusedLPr(removedFromList.get(i));
20983                    }
20984                }
20985            }
20986        }
20987
20988        @Override
20989        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20990            synchronized (mPackages) {
20991                // If we do not support permission review, done.
20992                if (!mPermissionReviewRequired && !Build.PERMISSIONS_REVIEW_REQUIRED) {
20993                    return false;
20994                }
20995
20996                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20997                if (packageSetting == null) {
20998                    return false;
20999                }
21000
21001                // Permission review applies only to apps not supporting the new permission model.
21002                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21003                    return false;
21004                }
21005
21006                // Legacy apps have the permission and get user consent on launch.
21007                PermissionsState permissionsState = packageSetting.getPermissionsState();
21008                return permissionsState.isPermissionReviewRequired(userId);
21009            }
21010        }
21011
21012        @Override
21013        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21014            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21015        }
21016
21017        @Override
21018        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21019                int userId) {
21020            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21021        }
21022
21023        @Override
21024        public void setDeviceAndProfileOwnerPackages(
21025                int deviceOwnerUserId, String deviceOwnerPackage,
21026                SparseArray<String> profileOwnerPackages) {
21027            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21028                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21029        }
21030
21031        @Override
21032        public boolean isPackageDataProtected(int userId, String packageName) {
21033            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21034        }
21035
21036        @Override
21037        public boolean wasPackageEverLaunched(String packageName, int userId) {
21038            synchronized (mPackages) {
21039                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21040            }
21041        }
21042    }
21043
21044    @Override
21045    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21046        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21047        synchronized (mPackages) {
21048            final long identity = Binder.clearCallingIdentity();
21049            try {
21050                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21051                        packageNames, userId);
21052            } finally {
21053                Binder.restoreCallingIdentity(identity);
21054            }
21055        }
21056    }
21057
21058    @Override
21059    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
21060        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
21061        synchronized (mPackages) {
21062            final long identity = Binder.clearCallingIdentity();
21063            try {
21064                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
21065                        packageNames, userId);
21066            } finally {
21067                Binder.restoreCallingIdentity(identity);
21068            }
21069        }
21070    }
21071
21072    private static void enforceSystemOrPhoneCaller(String tag) {
21073        int callingUid = Binder.getCallingUid();
21074        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21075            throw new SecurityException(
21076                    "Cannot call " + tag + " from UID " + callingUid);
21077        }
21078    }
21079
21080    boolean isHistoricalPackageUsageAvailable() {
21081        return mPackageUsage.isHistoricalPackageUsageAvailable();
21082    }
21083
21084    /**
21085     * Return a <b>copy</b> of the collection of packages known to the package manager.
21086     * @return A copy of the values of mPackages.
21087     */
21088    Collection<PackageParser.Package> getPackages() {
21089        synchronized (mPackages) {
21090            return new ArrayList<>(mPackages.values());
21091        }
21092    }
21093
21094    /**
21095     * Logs process start information (including base APK hash) to the security log.
21096     * @hide
21097     */
21098    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21099            String apkFile, int pid) {
21100        if (!SecurityLog.isLoggingEnabled()) {
21101            return;
21102        }
21103        Bundle data = new Bundle();
21104        data.putLong("startTimestamp", System.currentTimeMillis());
21105        data.putString("processName", processName);
21106        data.putInt("uid", uid);
21107        data.putString("seinfo", seinfo);
21108        data.putString("apkFile", apkFile);
21109        data.putInt("pid", pid);
21110        Message msg = mProcessLoggingHandler.obtainMessage(
21111                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21112        msg.setData(data);
21113        mProcessLoggingHandler.sendMessage(msg);
21114    }
21115
21116    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21117        return mCompilerStats.getPackageStats(pkgName);
21118    }
21119
21120    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21121        return getOrCreateCompilerPackageStats(pkg.packageName);
21122    }
21123
21124    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21125        return mCompilerStats.getOrCreatePackageStats(pkgName);
21126    }
21127
21128    public void deleteCompilerPackageStats(String pkgName) {
21129        mCompilerStats.deletePackageStats(pkgName);
21130    }
21131}
21132