PackageManagerService.java revision ff35e661724952664c48282de42d9063a7c7444a
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.ShellCallback;
189import android.os.SystemClock;
190import android.os.SystemProperties;
191import android.os.Trace;
192import android.os.UserHandle;
193import android.os.UserManager;
194import android.os.UserManagerInternal;
195import android.os.storage.IMountService;
196import android.os.storage.MountServiceInternal;
197import android.os.storage.StorageEventListener;
198import android.os.storage.StorageManager;
199import android.os.storage.VolumeInfo;
200import android.os.storage.VolumeRecord;
201import android.provider.Settings.Global;
202import android.provider.Settings.Secure;
203import android.security.KeyStore;
204import android.security.SystemKeyStore;
205import android.system.ErrnoException;
206import android.system.Os;
207import android.text.TextUtils;
208import android.text.format.DateUtils;
209import android.util.ArrayMap;
210import android.util.ArraySet;
211import android.util.DisplayMetrics;
212import android.util.EventLog;
213import android.util.ExceptionUtils;
214import android.util.Log;
215import android.util.LogPrinter;
216import android.util.MathUtils;
217import android.util.Pair;
218import android.util.PrintStreamPrinter;
219import android.util.Slog;
220import android.util.SparseArray;
221import android.util.SparseBooleanArray;
222import android.util.SparseIntArray;
223import android.util.Xml;
224import android.util.jar.StrictJarFile;
225import android.view.Display;
226
227import com.android.internal.R;
228import com.android.internal.annotations.GuardedBy;
229import com.android.internal.app.IMediaContainerService;
230import com.android.internal.app.ResolverActivity;
231import com.android.internal.content.NativeLibraryHelper;
232import com.android.internal.content.PackageHelper;
233import com.android.internal.logging.MetricsLogger;
234import com.android.internal.os.IParcelFileDescriptorFactory;
235import com.android.internal.os.InstallerConnection.InstallerException;
236import com.android.internal.os.SomeArgs;
237import com.android.internal.os.Zygote;
238import com.android.internal.telephony.CarrierAppUtils;
239import com.android.internal.util.ArrayUtils;
240import com.android.internal.util.FastPrintWriter;
241import com.android.internal.util.FastXmlSerializer;
242import com.android.internal.util.IndentingPrintWriter;
243import com.android.internal.util.Preconditions;
244import com.android.internal.util.XmlUtils;
245import com.android.server.AttributeCache;
246import com.android.server.EventLogTags;
247import com.android.server.FgThread;
248import com.android.server.IntentResolver;
249import com.android.server.LocalServices;
250import com.android.server.ServiceThread;
251import com.android.server.SystemConfig;
252import com.android.server.Watchdog;
253import com.android.server.net.NetworkPolicyManagerInternal;
254import com.android.server.pm.PermissionsState.PermissionState;
255import com.android.server.pm.Settings.DatabaseVersion;
256import com.android.server.pm.Settings.VersionInfo;
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.Iterator;
300import java.util.List;
301import java.util.Map;
302import java.util.Objects;
303import java.util.Set;
304import java.util.concurrent.CountDownLatch;
305import java.util.concurrent.TimeUnit;
306import java.util.concurrent.atomic.AtomicBoolean;
307import java.util.concurrent.atomic.AtomicInteger;
308
309/**
310 * Keep track of all those APKs everywhere.
311 * <p>
312 * Internally there are two important locks:
313 * <ul>
314 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
315 * and other related state. It is a fine-grained lock that should only be held
316 * momentarily, as it's one of the most contended locks in the system.
317 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
318 * operations typically involve heavy lifting of application data on disk. Since
319 * {@code installd} is single-threaded, and it's operations can often be slow,
320 * this lock should never be acquired while already holding {@link #mPackages}.
321 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
322 * holding {@link #mInstallLock}.
323 * </ul>
324 * Many internal methods rely on the caller to hold the appropriate locks, and
325 * this contract is expressed through method name suffixes:
326 * <ul>
327 * <li>fooLI(): the caller must hold {@link #mInstallLock}
328 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
329 * being modified must be frozen
330 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
331 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
332 * </ul>
333 * <p>
334 * Because this class is very central to the platform's security; please run all
335 * CTS and unit tests whenever making modifications:
336 *
337 * <pre>
338 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
339 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
340 * </pre>
341 */
342public class PackageManagerService extends IPackageManager.Stub {
343    static final String TAG = "PackageManager";
344    static final boolean DEBUG_SETTINGS = false;
345    static final boolean DEBUG_PREFERRED = false;
346    static final boolean DEBUG_UPGRADE = false;
347    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
348    private static final boolean DEBUG_BACKUP = false;
349    private static final boolean DEBUG_INSTALL = false;
350    private static final boolean DEBUG_REMOVE = false;
351    private static final boolean DEBUG_BROADCASTS = false;
352    private static final boolean DEBUG_SHOW_INFO = false;
353    private static final boolean DEBUG_PACKAGE_INFO = false;
354    private static final boolean DEBUG_INTENT_MATCHING = false;
355    private static final boolean DEBUG_PACKAGE_SCANNING = false;
356    private static final boolean DEBUG_VERIFY = false;
357    private static final boolean DEBUG_FILTERS = false;
358
359    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
360    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
361    // user, but by default initialize to this.
362    static final boolean DEBUG_DEXOPT = false;
363
364    private static final boolean DEBUG_ABI_SELECTION = false;
365    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
366    private static final boolean DEBUG_TRIAGED_MISSING = false;
367    private static final boolean DEBUG_APP_DATA = false;
368
369    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
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 int RADIO_UID = Process.PHONE_UID;
376    private static final int LOG_UID = Process.LOG_UID;
377    private static final int NFC_UID = Process.NFC_UID;
378    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
379    private static final int SHELL_UID = Process.SHELL_UID;
380
381    // Cap the size of permission trees that 3rd party apps can define
382    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
383
384    // Suffix used during package installation when copying/moving
385    // package apks to install directory.
386    private static final String INSTALL_PACKAGE_SUFFIX = "-";
387
388    static final int SCAN_NO_DEX = 1<<1;
389    static final int SCAN_FORCE_DEX = 1<<2;
390    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
391    static final int SCAN_NEW_INSTALL = 1<<4;
392    static final int SCAN_NO_PATHS = 1<<5;
393    static final int SCAN_UPDATE_TIME = 1<<6;
394    static final int SCAN_DEFER_DEX = 1<<7;
395    static final int SCAN_BOOTING = 1<<8;
396    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
397    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
398    static final int SCAN_REPLACING = 1<<11;
399    static final int SCAN_REQUIRE_KNOWN = 1<<12;
400    static final int SCAN_MOVE = 1<<13;
401    static final int SCAN_INITIAL = 1<<14;
402    static final int SCAN_CHECK_ONLY = 1<<15;
403    static final int SCAN_DONT_KILL_APP = 1<<17;
404    static final int SCAN_IGNORE_FROZEN = 1<<18;
405
406    static final int REMOVE_CHATTY = 1<<16;
407
408    private static final int[] EMPTY_INT_ARRAY = new int[0];
409
410    /**
411     * Timeout (in milliseconds) after which the watchdog should declare that
412     * our handler thread is wedged.  The usual default for such things is one
413     * minute but we sometimes do very lengthy I/O operations on this thread,
414     * such as installing multi-gigabyte applications, so ours needs to be longer.
415     */
416    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
417
418    /**
419     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
420     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
421     * settings entry if available, otherwise we use the hardcoded default.  If it's been
422     * more than this long since the last fstrim, we force one during the boot sequence.
423     *
424     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
425     * one gets run at the next available charging+idle time.  This final mandatory
426     * no-fstrim check kicks in only of the other scheduling criteria is never met.
427     */
428    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
429
430    /**
431     * Whether verification is enabled by default.
432     */
433    private static final boolean DEFAULT_VERIFY_ENABLE = true;
434
435    /**
436     * The default maximum time to wait for the verification agent to return in
437     * milliseconds.
438     */
439    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
440
441    /**
442     * The default response for package verification timeout.
443     *
444     * This can be either PackageManager.VERIFICATION_ALLOW or
445     * PackageManager.VERIFICATION_REJECT.
446     */
447    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
448
449    static final String PLATFORM_PACKAGE_NAME = "android";
450
451    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
452
453    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
454            DEFAULT_CONTAINER_PACKAGE,
455            "com.android.defcontainer.DefaultContainerService");
456
457    private static final String KILL_APP_REASON_GIDS_CHANGED =
458            "permission grant or revoke changed gids";
459
460    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
461            "permissions revoked";
462
463    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
464
465    private static final String PACKAGE_SCHEME = "package";
466
467    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
468    /**
469     * If VENDOR_OVERLAY_SKU_PROPERTY is set, search for runtime resource overlay APKs in
470     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_SKU_PROPERTY> rather than in
471     * VENDOR_OVERLAY_DIR.
472     */
473    private static final String VENDOR_OVERLAY_SKU_PROPERTY = "ro.boot.vendor.overlay.sku";
474
475    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
476    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
477
478    /** Permission grant: not grant the permission. */
479    private static final int GRANT_DENIED = 1;
480
481    /** Permission grant: grant the permission as an install permission. */
482    private static final int GRANT_INSTALL = 2;
483
484    /** Permission grant: grant the permission as a runtime one. */
485    private static final int GRANT_RUNTIME = 3;
486
487    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
488    private static final int GRANT_UPGRADE = 4;
489
490    /** Canonical intent used to identify what counts as a "web browser" app */
491    private static final Intent sBrowserIntent;
492    static {
493        sBrowserIntent = new Intent();
494        sBrowserIntent.setAction(Intent.ACTION_VIEW);
495        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
496        sBrowserIntent.setData(Uri.parse("http:"));
497    }
498
499    /**
500     * The set of all protected actions [i.e. those actions for which a high priority
501     * intent filter is disallowed].
502     */
503    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
504    static {
505        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
506        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
507        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
508        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
509    }
510
511    // Compilation reasons.
512    public static final int REASON_FIRST_BOOT = 0;
513    public static final int REASON_BOOT = 1;
514    public static final int REASON_INSTALL = 2;
515    public static final int REASON_BACKGROUND_DEXOPT = 3;
516    public static final int REASON_AB_OTA = 4;
517    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
518    public static final int REASON_SHARED_APK = 6;
519    public static final int REASON_FORCED_DEXOPT = 7;
520    public static final int REASON_CORE_APP = 8;
521
522    public static final int REASON_LAST = REASON_CORE_APP;
523
524    /** Special library name that skips shared libraries check during compilation. */
525    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
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
715    private AtomicInteger mNextMoveId = new AtomicInteger();
716    private final MoveCallbacks mMoveCallbacks;
717
718    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
719
720    // Cache of users who need badging.
721    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
722
723    /** Token for keys in mPendingVerification. */
724    private int mPendingVerificationToken = 0;
725
726    volatile boolean mSystemReady;
727    volatile boolean mSafeMode;
728    volatile boolean mHasSystemUidErrors;
729
730    ApplicationInfo mAndroidApplication;
731    final ActivityInfo mResolveActivity = new ActivityInfo();
732    final ResolveInfo mResolveInfo = new ResolveInfo();
733    ComponentName mResolveComponentName;
734    PackageParser.Package mPlatformPackage;
735    ComponentName mCustomResolverComponentName;
736
737    boolean mResolverReplaced = false;
738
739    private final @Nullable ComponentName mIntentFilterVerifierComponent;
740    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
741
742    private int mIntentFilterVerificationToken = 0;
743
744    /** Component that knows whether or not an ephemeral application exists */
745    final ComponentName mEphemeralResolverComponent;
746    /** The service connection to the ephemeral resolver */
747    final EphemeralResolverConnection mEphemeralResolverConnection;
748
749    /** Component used to install ephemeral applications */
750    final ComponentName mEphemeralInstallerComponent;
751    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
752    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
753
754    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
755            = new SparseArray<IntentFilterVerificationState>();
756
757    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
758
759    // List of packages names to keep cached, even if they are uninstalled for all users
760    private List<String> mKeepUninstalledPackages;
761
762    private UserManagerInternal mUserManagerInternal;
763
764    private static class IFVerificationParams {
765        PackageParser.Package pkg;
766        boolean replacing;
767        int userId;
768        int verifierUid;
769
770        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
771                int _userId, int _verifierUid) {
772            pkg = _pkg;
773            replacing = _replacing;
774            userId = _userId;
775            replacing = _replacing;
776            verifierUid = _verifierUid;
777        }
778    }
779
780    private interface IntentFilterVerifier<T extends IntentFilter> {
781        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
782                                               T filter, String packageName);
783        void startVerifications(int userId);
784        void receiveVerificationResponse(int verificationId);
785    }
786
787    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
788        private Context mContext;
789        private ComponentName mIntentFilterVerifierComponent;
790        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
791
792        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
793            mContext = context;
794            mIntentFilterVerifierComponent = verifierComponent;
795        }
796
797        private String getDefaultScheme() {
798            return IntentFilter.SCHEME_HTTPS;
799        }
800
801        @Override
802        public void startVerifications(int userId) {
803            // Launch verifications requests
804            int count = mCurrentIntentFilterVerifications.size();
805            for (int n=0; n<count; n++) {
806                int verificationId = mCurrentIntentFilterVerifications.get(n);
807                final IntentFilterVerificationState ivs =
808                        mIntentFilterVerificationStates.get(verificationId);
809
810                String packageName = ivs.getPackageName();
811
812                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
813                final int filterCount = filters.size();
814                ArraySet<String> domainsSet = new ArraySet<>();
815                for (int m=0; m<filterCount; m++) {
816                    PackageParser.ActivityIntentInfo filter = filters.get(m);
817                    domainsSet.addAll(filter.getHostsList());
818                }
819                synchronized (mPackages) {
820                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
821                            packageName, domainsSet) != null) {
822                        scheduleWriteSettingsLocked();
823                    }
824                }
825                sendVerificationRequest(userId, verificationId, ivs);
826            }
827            mCurrentIntentFilterVerifications.clear();
828        }
829
830        private void sendVerificationRequest(int userId, int verificationId,
831                IntentFilterVerificationState ivs) {
832
833            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
834            verificationIntent.putExtra(
835                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
836                    verificationId);
837            verificationIntent.putExtra(
838                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
839                    getDefaultScheme());
840            verificationIntent.putExtra(
841                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
842                    ivs.getHostsString());
843            verificationIntent.putExtra(
844                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
845                    ivs.getPackageName());
846            verificationIntent.setComponent(mIntentFilterVerifierComponent);
847            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
848
849            UserHandle user = new UserHandle(userId);
850            mContext.sendBroadcastAsUser(verificationIntent, user);
851            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
852                    "Sending IntentFilter verification broadcast");
853        }
854
855        public void receiveVerificationResponse(int verificationId) {
856            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
857
858            final boolean verified = ivs.isVerified();
859
860            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
861            final int count = filters.size();
862            if (DEBUG_DOMAIN_VERIFICATION) {
863                Slog.i(TAG, "Received verification response " + verificationId
864                        + " for " + count + " filters, verified=" + verified);
865            }
866            for (int n=0; n<count; n++) {
867                PackageParser.ActivityIntentInfo filter = filters.get(n);
868                filter.setVerified(verified);
869
870                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
871                        + " verified with result:" + verified + " and hosts:"
872                        + ivs.getHostsString());
873            }
874
875            mIntentFilterVerificationStates.remove(verificationId);
876
877            final String packageName = ivs.getPackageName();
878            IntentFilterVerificationInfo ivi = null;
879
880            synchronized (mPackages) {
881                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
882            }
883            if (ivi == null) {
884                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
885                        + verificationId + " packageName:" + packageName);
886                return;
887            }
888            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
889                    "Updating IntentFilterVerificationInfo for package " + packageName
890                            +" verificationId:" + verificationId);
891
892            synchronized (mPackages) {
893                if (verified) {
894                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
895                } else {
896                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
897                }
898                scheduleWriteSettingsLocked();
899
900                final int userId = ivs.getUserId();
901                if (userId != UserHandle.USER_ALL) {
902                    final int userStatus =
903                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
904
905                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
906                    boolean needUpdate = false;
907
908                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
909                    // already been set by the User thru the Disambiguation dialog
910                    switch (userStatus) {
911                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
912                            if (verified) {
913                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
914                            } else {
915                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
916                            }
917                            needUpdate = true;
918                            break;
919
920                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
921                            if (verified) {
922                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
923                                needUpdate = true;
924                            }
925                            break;
926
927                        default:
928                            // Nothing to do
929                    }
930
931                    if (needUpdate) {
932                        mSettings.updateIntentFilterVerificationStatusLPw(
933                                packageName, updatedStatus, userId);
934                        scheduleWritePackageRestrictionsLocked(userId);
935                    }
936                }
937            }
938        }
939
940        @Override
941        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
942                    ActivityIntentInfo filter, String packageName) {
943            if (!hasValidDomains(filter)) {
944                return false;
945            }
946            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
947            if (ivs == null) {
948                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
949                        packageName);
950            }
951            if (DEBUG_DOMAIN_VERIFICATION) {
952                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
953            }
954            ivs.addFilter(filter);
955            return true;
956        }
957
958        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
959                int userId, int verificationId, String packageName) {
960            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
961                    verifierUid, userId, packageName);
962            ivs.setPendingState();
963            synchronized (mPackages) {
964                mIntentFilterVerificationStates.append(verificationId, ivs);
965                mCurrentIntentFilterVerifications.add(verificationId);
966            }
967            return ivs;
968        }
969    }
970
971    private static boolean hasValidDomains(ActivityIntentInfo filter) {
972        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
973                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
974                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
975    }
976
977    // Set of pending broadcasts for aggregating enable/disable of components.
978    static class PendingPackageBroadcasts {
979        // for each user id, a map of <package name -> components within that package>
980        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
981
982        public PendingPackageBroadcasts() {
983            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
984        }
985
986        public ArrayList<String> get(int userId, String packageName) {
987            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
988            return packages.get(packageName);
989        }
990
991        public void put(int userId, String packageName, ArrayList<String> components) {
992            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
993            packages.put(packageName, components);
994        }
995
996        public void remove(int userId, String packageName) {
997            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
998            if (packages != null) {
999                packages.remove(packageName);
1000            }
1001        }
1002
1003        public void remove(int userId) {
1004            mUidMap.remove(userId);
1005        }
1006
1007        public int userIdCount() {
1008            return mUidMap.size();
1009        }
1010
1011        public int userIdAt(int n) {
1012            return mUidMap.keyAt(n);
1013        }
1014
1015        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1016            return mUidMap.get(userId);
1017        }
1018
1019        public int size() {
1020            // total number of pending broadcast entries across all userIds
1021            int num = 0;
1022            for (int i = 0; i< mUidMap.size(); i++) {
1023                num += mUidMap.valueAt(i).size();
1024            }
1025            return num;
1026        }
1027
1028        public void clear() {
1029            mUidMap.clear();
1030        }
1031
1032        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1033            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1034            if (map == null) {
1035                map = new ArrayMap<String, ArrayList<String>>();
1036                mUidMap.put(userId, map);
1037            }
1038            return map;
1039        }
1040    }
1041    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1042
1043    // Service Connection to remote media container service to copy
1044    // package uri's from external media onto secure containers
1045    // or internal storage.
1046    private IMediaContainerService mContainerService = null;
1047
1048    static final int SEND_PENDING_BROADCAST = 1;
1049    static final int MCS_BOUND = 3;
1050    static final int END_COPY = 4;
1051    static final int INIT_COPY = 5;
1052    static final int MCS_UNBIND = 6;
1053    static final int START_CLEANING_PACKAGE = 7;
1054    static final int FIND_INSTALL_LOC = 8;
1055    static final int POST_INSTALL = 9;
1056    static final int MCS_RECONNECT = 10;
1057    static final int MCS_GIVE_UP = 11;
1058    static final int UPDATED_MEDIA_STATUS = 12;
1059    static final int WRITE_SETTINGS = 13;
1060    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1061    static final int PACKAGE_VERIFIED = 15;
1062    static final int CHECK_PENDING_VERIFICATION = 16;
1063    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1064    static final int INTENT_FILTER_VERIFIED = 18;
1065    static final int WRITE_PACKAGE_LIST = 19;
1066
1067    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1068
1069    // Delay time in millisecs
1070    static final int BROADCAST_DELAY = 10 * 1000;
1071
1072    static UserManagerService sUserManager;
1073
1074    // Stores a list of users whose package restrictions file needs to be updated
1075    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1076
1077    final private DefaultContainerConnection mDefContainerConn =
1078            new DefaultContainerConnection();
1079    class DefaultContainerConnection implements ServiceConnection {
1080        public void onServiceConnected(ComponentName name, IBinder service) {
1081            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1082            IMediaContainerService imcs =
1083                IMediaContainerService.Stub.asInterface(service);
1084            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1085        }
1086
1087        public void onServiceDisconnected(ComponentName name) {
1088            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1089        }
1090    }
1091
1092    // Recordkeeping of restore-after-install operations that are currently in flight
1093    // between the Package Manager and the Backup Manager
1094    static class PostInstallData {
1095        public InstallArgs args;
1096        public PackageInstalledInfo res;
1097
1098        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1099            args = _a;
1100            res = _r;
1101        }
1102    }
1103
1104    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1105    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1106
1107    // XML tags for backup/restore of various bits of state
1108    private static final String TAG_PREFERRED_BACKUP = "pa";
1109    private static final String TAG_DEFAULT_APPS = "da";
1110    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1111
1112    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1113    private static final String TAG_ALL_GRANTS = "rt-grants";
1114    private static final String TAG_GRANT = "grant";
1115    private static final String ATTR_PACKAGE_NAME = "pkg";
1116
1117    private static final String TAG_PERMISSION = "perm";
1118    private static final String ATTR_PERMISSION_NAME = "name";
1119    private static final String ATTR_IS_GRANTED = "g";
1120    private static final String ATTR_USER_SET = "set";
1121    private static final String ATTR_USER_FIXED = "fixed";
1122    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1123
1124    // System/policy permission grants are not backed up
1125    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1126            FLAG_PERMISSION_POLICY_FIXED
1127            | FLAG_PERMISSION_SYSTEM_FIXED
1128            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1129
1130    // And we back up these user-adjusted states
1131    private static final int USER_RUNTIME_GRANT_MASK =
1132            FLAG_PERMISSION_USER_SET
1133            | FLAG_PERMISSION_USER_FIXED
1134            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1135
1136    final @Nullable String mRequiredVerifierPackage;
1137    final @NonNull String mRequiredInstallerPackage;
1138    final @NonNull String mRequiredUninstallerPackage;
1139    final @Nullable String mSetupWizardPackage;
1140    final @Nullable String mStorageManagerPackage;
1141    final @NonNull String mServicesSystemSharedLibraryPackageName;
1142    final @NonNull String mSharedSystemSharedLibraryPackageName;
1143
1144    final boolean mPermissionReviewRequired;
1145
1146    private final PackageUsage mPackageUsage = new PackageUsage();
1147    private final CompilerStats mCompilerStats = new CompilerStats();
1148
1149    class PackageHandler extends Handler {
1150        private boolean mBound = false;
1151        final ArrayList<HandlerParams> mPendingInstalls =
1152            new ArrayList<HandlerParams>();
1153
1154        private boolean connectToService() {
1155            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1156                    " DefaultContainerService");
1157            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1158            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1159            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1160                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1161                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1162                mBound = true;
1163                return true;
1164            }
1165            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1166            return false;
1167        }
1168
1169        private void disconnectService() {
1170            mContainerService = null;
1171            mBound = false;
1172            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1173            mContext.unbindService(mDefContainerConn);
1174            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1175        }
1176
1177        PackageHandler(Looper looper) {
1178            super(looper);
1179        }
1180
1181        public void handleMessage(Message msg) {
1182            try {
1183                doHandleMessage(msg);
1184            } finally {
1185                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1186            }
1187        }
1188
1189        void doHandleMessage(Message msg) {
1190            switch (msg.what) {
1191                case INIT_COPY: {
1192                    HandlerParams params = (HandlerParams) msg.obj;
1193                    int idx = mPendingInstalls.size();
1194                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1195                    // If a bind was already initiated we dont really
1196                    // need to do anything. The pending install
1197                    // will be processed later on.
1198                    if (!mBound) {
1199                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1200                                System.identityHashCode(mHandler));
1201                        // If this is the only one pending we might
1202                        // have to bind to the service again.
1203                        if (!connectToService()) {
1204                            Slog.e(TAG, "Failed to bind to media container service");
1205                            params.serviceError();
1206                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1207                                    System.identityHashCode(mHandler));
1208                            if (params.traceMethod != null) {
1209                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1210                                        params.traceCookie);
1211                            }
1212                            return;
1213                        } else {
1214                            // Once we bind to the service, the first
1215                            // pending request will be processed.
1216                            mPendingInstalls.add(idx, params);
1217                        }
1218                    } else {
1219                        mPendingInstalls.add(idx, params);
1220                        // Already bound to the service. Just make
1221                        // sure we trigger off processing the first request.
1222                        if (idx == 0) {
1223                            mHandler.sendEmptyMessage(MCS_BOUND);
1224                        }
1225                    }
1226                    break;
1227                }
1228                case MCS_BOUND: {
1229                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1230                    if (msg.obj != null) {
1231                        mContainerService = (IMediaContainerService) msg.obj;
1232                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1233                                System.identityHashCode(mHandler));
1234                    }
1235                    if (mContainerService == null) {
1236                        if (!mBound) {
1237                            // Something seriously wrong since we are not bound and we are not
1238                            // waiting for connection. Bail out.
1239                            Slog.e(TAG, "Cannot bind to media container service");
1240                            for (HandlerParams params : mPendingInstalls) {
1241                                // Indicate service bind error
1242                                params.serviceError();
1243                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1244                                        System.identityHashCode(params));
1245                                if (params.traceMethod != null) {
1246                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1247                                            params.traceMethod, params.traceCookie);
1248                                }
1249                                return;
1250                            }
1251                            mPendingInstalls.clear();
1252                        } else {
1253                            Slog.w(TAG, "Waiting to connect to media container service");
1254                        }
1255                    } else if (mPendingInstalls.size() > 0) {
1256                        HandlerParams params = mPendingInstalls.get(0);
1257                        if (params != null) {
1258                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1259                                    System.identityHashCode(params));
1260                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1261                            if (params.startCopy()) {
1262                                // We are done...  look for more work or to
1263                                // go idle.
1264                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1265                                        "Checking for more work or unbind...");
1266                                // Delete pending install
1267                                if (mPendingInstalls.size() > 0) {
1268                                    mPendingInstalls.remove(0);
1269                                }
1270                                if (mPendingInstalls.size() == 0) {
1271                                    if (mBound) {
1272                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1273                                                "Posting delayed MCS_UNBIND");
1274                                        removeMessages(MCS_UNBIND);
1275                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1276                                        // Unbind after a little delay, to avoid
1277                                        // continual thrashing.
1278                                        sendMessageDelayed(ubmsg, 10000);
1279                                    }
1280                                } else {
1281                                    // There are more pending requests in queue.
1282                                    // Just post MCS_BOUND message to trigger processing
1283                                    // of next pending install.
1284                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1285                                            "Posting MCS_BOUND for next work");
1286                                    mHandler.sendEmptyMessage(MCS_BOUND);
1287                                }
1288                            }
1289                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1290                        }
1291                    } else {
1292                        // Should never happen ideally.
1293                        Slog.w(TAG, "Empty queue");
1294                    }
1295                    break;
1296                }
1297                case MCS_RECONNECT: {
1298                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1299                    if (mPendingInstalls.size() > 0) {
1300                        if (mBound) {
1301                            disconnectService();
1302                        }
1303                        if (!connectToService()) {
1304                            Slog.e(TAG, "Failed to bind to media container service");
1305                            for (HandlerParams params : mPendingInstalls) {
1306                                // Indicate service bind error
1307                                params.serviceError();
1308                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1309                                        System.identityHashCode(params));
1310                            }
1311                            mPendingInstalls.clear();
1312                        }
1313                    }
1314                    break;
1315                }
1316                case MCS_UNBIND: {
1317                    // If there is no actual work left, then time to unbind.
1318                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1319
1320                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1321                        if (mBound) {
1322                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1323
1324                            disconnectService();
1325                        }
1326                    } else if (mPendingInstalls.size() > 0) {
1327                        // There are more pending requests in queue.
1328                        // Just post MCS_BOUND message to trigger processing
1329                        // of next pending install.
1330                        mHandler.sendEmptyMessage(MCS_BOUND);
1331                    }
1332
1333                    break;
1334                }
1335                case MCS_GIVE_UP: {
1336                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1337                    HandlerParams params = mPendingInstalls.remove(0);
1338                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1339                            System.identityHashCode(params));
1340                    break;
1341                }
1342                case SEND_PENDING_BROADCAST: {
1343                    String packages[];
1344                    ArrayList<String> components[];
1345                    int size = 0;
1346                    int uids[];
1347                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1348                    synchronized (mPackages) {
1349                        if (mPendingBroadcasts == null) {
1350                            return;
1351                        }
1352                        size = mPendingBroadcasts.size();
1353                        if (size <= 0) {
1354                            // Nothing to be done. Just return
1355                            return;
1356                        }
1357                        packages = new String[size];
1358                        components = new ArrayList[size];
1359                        uids = new int[size];
1360                        int i = 0;  // filling out the above arrays
1361
1362                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1363                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1364                            Iterator<Map.Entry<String, ArrayList<String>>> it
1365                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1366                                            .entrySet().iterator();
1367                            while (it.hasNext() && i < size) {
1368                                Map.Entry<String, ArrayList<String>> ent = it.next();
1369                                packages[i] = ent.getKey();
1370                                components[i] = ent.getValue();
1371                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1372                                uids[i] = (ps != null)
1373                                        ? UserHandle.getUid(packageUserId, ps.appId)
1374                                        : -1;
1375                                i++;
1376                            }
1377                        }
1378                        size = i;
1379                        mPendingBroadcasts.clear();
1380                    }
1381                    // Send broadcasts
1382                    for (int i = 0; i < size; i++) {
1383                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1384                    }
1385                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1386                    break;
1387                }
1388                case START_CLEANING_PACKAGE: {
1389                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1390                    final String packageName = (String)msg.obj;
1391                    final int userId = msg.arg1;
1392                    final boolean andCode = msg.arg2 != 0;
1393                    synchronized (mPackages) {
1394                        if (userId == UserHandle.USER_ALL) {
1395                            int[] users = sUserManager.getUserIds();
1396                            for (int user : users) {
1397                                mSettings.addPackageToCleanLPw(
1398                                        new PackageCleanItem(user, packageName, andCode));
1399                            }
1400                        } else {
1401                            mSettings.addPackageToCleanLPw(
1402                                    new PackageCleanItem(userId, packageName, andCode));
1403                        }
1404                    }
1405                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1406                    startCleaningPackages();
1407                } break;
1408                case POST_INSTALL: {
1409                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1410
1411                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1412                    final boolean didRestore = (msg.arg2 != 0);
1413                    mRunningInstalls.delete(msg.arg1);
1414
1415                    if (data != null) {
1416                        InstallArgs args = data.args;
1417                        PackageInstalledInfo parentRes = data.res;
1418
1419                        final boolean grantPermissions = (args.installFlags
1420                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1421                        final boolean killApp = (args.installFlags
1422                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1423                        final String[] grantedPermissions = args.installGrantPermissions;
1424
1425                        // Handle the parent package
1426                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1427                                grantedPermissions, didRestore, args.installerPackageName,
1428                                args.observer);
1429
1430                        // Handle the child packages
1431                        final int childCount = (parentRes.addedChildPackages != null)
1432                                ? parentRes.addedChildPackages.size() : 0;
1433                        for (int i = 0; i < childCount; i++) {
1434                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1435                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1436                                    grantedPermissions, false, args.installerPackageName,
1437                                    args.observer);
1438                        }
1439
1440                        // Log tracing if needed
1441                        if (args.traceMethod != null) {
1442                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1443                                    args.traceCookie);
1444                        }
1445                    } else {
1446                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1447                    }
1448
1449                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1450                } break;
1451                case UPDATED_MEDIA_STATUS: {
1452                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1453                    boolean reportStatus = msg.arg1 == 1;
1454                    boolean doGc = msg.arg2 == 1;
1455                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1456                    if (doGc) {
1457                        // Force a gc to clear up stale containers.
1458                        Runtime.getRuntime().gc();
1459                    }
1460                    if (msg.obj != null) {
1461                        @SuppressWarnings("unchecked")
1462                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1463                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1464                        // Unload containers
1465                        unloadAllContainers(args);
1466                    }
1467                    if (reportStatus) {
1468                        try {
1469                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1470                            PackageHelper.getMountService().finishMediaUpdate();
1471                        } catch (RemoteException e) {
1472                            Log.e(TAG, "MountService not running?");
1473                        }
1474                    }
1475                } break;
1476                case WRITE_SETTINGS: {
1477                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1478                    synchronized (mPackages) {
1479                        removeMessages(WRITE_SETTINGS);
1480                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1481                        mSettings.writeLPr();
1482                        mDirtyUsers.clear();
1483                    }
1484                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1485                } break;
1486                case WRITE_PACKAGE_RESTRICTIONS: {
1487                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1488                    synchronized (mPackages) {
1489                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1490                        for (int userId : mDirtyUsers) {
1491                            mSettings.writePackageRestrictionsLPr(userId);
1492                        }
1493                        mDirtyUsers.clear();
1494                    }
1495                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1496                } break;
1497                case WRITE_PACKAGE_LIST: {
1498                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1499                    synchronized (mPackages) {
1500                        removeMessages(WRITE_PACKAGE_LIST);
1501                        mSettings.writePackageListLPr(msg.arg1);
1502                    }
1503                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1504                } break;
1505                case CHECK_PENDING_VERIFICATION: {
1506                    final int verificationId = msg.arg1;
1507                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1508
1509                    if ((state != null) && !state.timeoutExtended()) {
1510                        final InstallArgs args = state.getInstallArgs();
1511                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1512
1513                        Slog.i(TAG, "Verification timed out for " + originUri);
1514                        mPendingVerification.remove(verificationId);
1515
1516                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1517
1518                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1519                            Slog.i(TAG, "Continuing with installation of " + originUri);
1520                            state.setVerifierResponse(Binder.getCallingUid(),
1521                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1522                            broadcastPackageVerified(verificationId, originUri,
1523                                    PackageManager.VERIFICATION_ALLOW,
1524                                    state.getInstallArgs().getUser());
1525                            try {
1526                                ret = args.copyApk(mContainerService, true);
1527                            } catch (RemoteException e) {
1528                                Slog.e(TAG, "Could not contact the ContainerService");
1529                            }
1530                        } else {
1531                            broadcastPackageVerified(verificationId, originUri,
1532                                    PackageManager.VERIFICATION_REJECT,
1533                                    state.getInstallArgs().getUser());
1534                        }
1535
1536                        Trace.asyncTraceEnd(
1537                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1538
1539                        processPendingInstall(args, ret);
1540                        mHandler.sendEmptyMessage(MCS_UNBIND);
1541                    }
1542                    break;
1543                }
1544                case PACKAGE_VERIFIED: {
1545                    final int verificationId = msg.arg1;
1546
1547                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1548                    if (state == null) {
1549                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1550                        break;
1551                    }
1552
1553                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1554
1555                    state.setVerifierResponse(response.callerUid, response.code);
1556
1557                    if (state.isVerificationComplete()) {
1558                        mPendingVerification.remove(verificationId);
1559
1560                        final InstallArgs args = state.getInstallArgs();
1561                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1562
1563                        int ret;
1564                        if (state.isInstallAllowed()) {
1565                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1566                            broadcastPackageVerified(verificationId, originUri,
1567                                    response.code, state.getInstallArgs().getUser());
1568                            try {
1569                                ret = args.copyApk(mContainerService, true);
1570                            } catch (RemoteException e) {
1571                                Slog.e(TAG, "Could not contact the ContainerService");
1572                            }
1573                        } else {
1574                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1575                        }
1576
1577                        Trace.asyncTraceEnd(
1578                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1579
1580                        processPendingInstall(args, ret);
1581                        mHandler.sendEmptyMessage(MCS_UNBIND);
1582                    }
1583
1584                    break;
1585                }
1586                case START_INTENT_FILTER_VERIFICATIONS: {
1587                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1588                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1589                            params.replacing, params.pkg);
1590                    break;
1591                }
1592                case INTENT_FILTER_VERIFIED: {
1593                    final int verificationId = msg.arg1;
1594
1595                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1596                            verificationId);
1597                    if (state == null) {
1598                        Slog.w(TAG, "Invalid IntentFilter verification token "
1599                                + verificationId + " received");
1600                        break;
1601                    }
1602
1603                    final int userId = state.getUserId();
1604
1605                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1606                            "Processing IntentFilter verification with token:"
1607                            + verificationId + " and userId:" + userId);
1608
1609                    final IntentFilterVerificationResponse response =
1610                            (IntentFilterVerificationResponse) msg.obj;
1611
1612                    state.setVerifierResponse(response.callerUid, response.code);
1613
1614                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1615                            "IntentFilter verification with token:" + verificationId
1616                            + " and userId:" + userId
1617                            + " is settings verifier response with response code:"
1618                            + response.code);
1619
1620                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1621                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1622                                + response.getFailedDomainsString());
1623                    }
1624
1625                    if (state.isVerificationComplete()) {
1626                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1627                    } else {
1628                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1629                                "IntentFilter verification with token:" + verificationId
1630                                + " was not said to be complete");
1631                    }
1632
1633                    break;
1634                }
1635            }
1636        }
1637    }
1638
1639    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1640            boolean killApp, String[] grantedPermissions,
1641            boolean launchedForRestore, String installerPackage,
1642            IPackageInstallObserver2 installObserver) {
1643        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1644            // Send the removed broadcasts
1645            if (res.removedInfo != null) {
1646                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1647            }
1648
1649            // Now that we successfully installed the package, grant runtime
1650            // permissions if requested before broadcasting the install.
1651            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1652                    >= Build.VERSION_CODES.M) {
1653                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1654            }
1655
1656            final boolean update = res.removedInfo != null
1657                    && res.removedInfo.removedPackage != null;
1658
1659            // If this is the first time we have child packages for a disabled privileged
1660            // app that had no children, we grant requested runtime permissions to the new
1661            // children if the parent on the system image had them already granted.
1662            if (res.pkg.parentPackage != null) {
1663                synchronized (mPackages) {
1664                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1665                }
1666            }
1667
1668            synchronized (mPackages) {
1669                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1670            }
1671
1672            final String packageName = res.pkg.applicationInfo.packageName;
1673            Bundle extras = new Bundle(1);
1674            extras.putInt(Intent.EXTRA_UID, res.uid);
1675
1676            // Determine the set of users who are adding this package for
1677            // the first time vs. those who are seeing an update.
1678            int[] firstUsers = EMPTY_INT_ARRAY;
1679            int[] updateUsers = EMPTY_INT_ARRAY;
1680            if (res.origUsers == null || res.origUsers.length == 0) {
1681                firstUsers = res.newUsers;
1682            } else {
1683                for (int newUser : res.newUsers) {
1684                    boolean isNew = true;
1685                    for (int origUser : res.origUsers) {
1686                        if (origUser == newUser) {
1687                            isNew = false;
1688                            break;
1689                        }
1690                    }
1691                    if (isNew) {
1692                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1693                    } else {
1694                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1695                    }
1696                }
1697            }
1698
1699            // Send installed broadcasts if the install/update is not ephemeral
1700            if (!isEphemeral(res.pkg)) {
1701                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1702
1703                // Send added for users that see the package for the first time
1704                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1705                        extras, 0 /*flags*/, null /*targetPackage*/,
1706                        null /*finishedReceiver*/, firstUsers);
1707
1708                // Send added for users that don't see the package for the first time
1709                if (update) {
1710                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1711                }
1712                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1713                        extras, 0 /*flags*/, null /*targetPackage*/,
1714                        null /*finishedReceiver*/, updateUsers);
1715
1716                // Send replaced for users that don't see the package for the first time
1717                if (update) {
1718                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1719                            packageName, extras, 0 /*flags*/,
1720                            null /*targetPackage*/, null /*finishedReceiver*/,
1721                            updateUsers);
1722                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1723                            null /*package*/, null /*extras*/, 0 /*flags*/,
1724                            packageName /*targetPackage*/,
1725                            null /*finishedReceiver*/, updateUsers);
1726                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1727                    // First-install and we did a restore, so we're responsible for the
1728                    // first-launch broadcast.
1729                    if (DEBUG_BACKUP) {
1730                        Slog.i(TAG, "Post-restore of " + packageName
1731                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1732                    }
1733                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1734                }
1735
1736                // Send broadcast package appeared if forward locked/external for all users
1737                // treat asec-hosted packages like removable media on upgrade
1738                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1739                    if (DEBUG_INSTALL) {
1740                        Slog.i(TAG, "upgrading pkg " + res.pkg
1741                                + " is ASEC-hosted -> AVAILABLE");
1742                    }
1743                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1744                    ArrayList<String> pkgList = new ArrayList<>(1);
1745                    pkgList.add(packageName);
1746                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1747                }
1748            }
1749
1750            // Work that needs to happen on first install within each user
1751            if (firstUsers != null && firstUsers.length > 0) {
1752                synchronized (mPackages) {
1753                    for (int userId : firstUsers) {
1754                        // If this app is a browser and it's newly-installed for some
1755                        // users, clear any default-browser state in those users. The
1756                        // app's nature doesn't depend on the user, so we can just check
1757                        // its browser nature in any user and generalize.
1758                        if (packageIsBrowser(packageName, userId)) {
1759                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1760                        }
1761
1762                        // We may also need to apply pending (restored) runtime
1763                        // permission grants within these users.
1764                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1765                    }
1766                }
1767            }
1768
1769            // Log current value of "unknown sources" setting
1770            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1771                    getUnknownSourcesSettings());
1772
1773            // Force a gc to clear up things
1774            Runtime.getRuntime().gc();
1775
1776            // Remove the replaced package's older resources safely now
1777            // We delete after a gc for applications  on sdcard.
1778            if (res.removedInfo != null && res.removedInfo.args != null) {
1779                synchronized (mInstallLock) {
1780                    res.removedInfo.args.doPostDeleteLI(true);
1781                }
1782            }
1783        }
1784
1785        // If someone is watching installs - notify them
1786        if (installObserver != null) {
1787            try {
1788                Bundle extras = extrasForInstallResult(res);
1789                installObserver.onPackageInstalled(res.name, res.returnCode,
1790                        res.returnMsg, extras);
1791            } catch (RemoteException e) {
1792                Slog.i(TAG, "Observer no longer exists.");
1793            }
1794        }
1795    }
1796
1797    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1798            PackageParser.Package pkg) {
1799        if (pkg.parentPackage == null) {
1800            return;
1801        }
1802        if (pkg.requestedPermissions == null) {
1803            return;
1804        }
1805        final PackageSetting disabledSysParentPs = mSettings
1806                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1807        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1808                || !disabledSysParentPs.isPrivileged()
1809                || (disabledSysParentPs.childPackageNames != null
1810                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1811            return;
1812        }
1813        final int[] allUserIds = sUserManager.getUserIds();
1814        final int permCount = pkg.requestedPermissions.size();
1815        for (int i = 0; i < permCount; i++) {
1816            String permission = pkg.requestedPermissions.get(i);
1817            BasePermission bp = mSettings.mPermissions.get(permission);
1818            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1819                continue;
1820            }
1821            for (int userId : allUserIds) {
1822                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1823                        permission, userId)) {
1824                    grantRuntimePermission(pkg.packageName, permission, userId);
1825                }
1826            }
1827        }
1828    }
1829
1830    private StorageEventListener mStorageListener = new StorageEventListener() {
1831        @Override
1832        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1833            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1834                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1835                    final String volumeUuid = vol.getFsUuid();
1836
1837                    // Clean up any users or apps that were removed or recreated
1838                    // while this volume was missing
1839                    reconcileUsers(volumeUuid);
1840                    reconcileApps(volumeUuid);
1841
1842                    // Clean up any install sessions that expired or were
1843                    // cancelled while this volume was missing
1844                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1845
1846                    loadPrivatePackages(vol);
1847
1848                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1849                    unloadPrivatePackages(vol);
1850                }
1851            }
1852
1853            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1854                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1855                    updateExternalMediaStatus(true, false);
1856                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1857                    updateExternalMediaStatus(false, false);
1858                }
1859            }
1860        }
1861
1862        @Override
1863        public void onVolumeForgotten(String fsUuid) {
1864            if (TextUtils.isEmpty(fsUuid)) {
1865                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1866                return;
1867            }
1868
1869            // Remove any apps installed on the forgotten volume
1870            synchronized (mPackages) {
1871                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1872                for (PackageSetting ps : packages) {
1873                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1874                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1875                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1876                }
1877
1878                mSettings.onVolumeForgotten(fsUuid);
1879                mSettings.writeLPr();
1880            }
1881        }
1882    };
1883
1884    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1885            String[] grantedPermissions) {
1886        for (int userId : userIds) {
1887            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1888        }
1889
1890        // We could have touched GID membership, so flush out packages.list
1891        synchronized (mPackages) {
1892            mSettings.writePackageListLPr();
1893        }
1894    }
1895
1896    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1897            String[] grantedPermissions) {
1898        SettingBase sb = (SettingBase) pkg.mExtras;
1899        if (sb == null) {
1900            return;
1901        }
1902
1903        PermissionsState permissionsState = sb.getPermissionsState();
1904
1905        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1906                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1907
1908        for (String permission : pkg.requestedPermissions) {
1909            final BasePermission bp;
1910            synchronized (mPackages) {
1911                bp = mSettings.mPermissions.get(permission);
1912            }
1913            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1914                    && (grantedPermissions == null
1915                           || ArrayUtils.contains(grantedPermissions, permission))) {
1916                final int flags = permissionsState.getPermissionFlags(permission, userId);
1917                // Installer cannot change immutable permissions.
1918                if ((flags & immutableFlags) == 0) {
1919                    grantRuntimePermission(pkg.packageName, permission, userId);
1920                }
1921            }
1922        }
1923    }
1924
1925    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1926        Bundle extras = null;
1927        switch (res.returnCode) {
1928            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1929                extras = new Bundle();
1930                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1931                        res.origPermission);
1932                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1933                        res.origPackage);
1934                break;
1935            }
1936            case PackageManager.INSTALL_SUCCEEDED: {
1937                extras = new Bundle();
1938                extras.putBoolean(Intent.EXTRA_REPLACING,
1939                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1940                break;
1941            }
1942        }
1943        return extras;
1944    }
1945
1946    void scheduleWriteSettingsLocked() {
1947        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1948            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1949        }
1950    }
1951
1952    void scheduleWritePackageListLocked(int userId) {
1953        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1954            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1955            msg.arg1 = userId;
1956            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1957        }
1958    }
1959
1960    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1961        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1962        scheduleWritePackageRestrictionsLocked(userId);
1963    }
1964
1965    void scheduleWritePackageRestrictionsLocked(int userId) {
1966        final int[] userIds = (userId == UserHandle.USER_ALL)
1967                ? sUserManager.getUserIds() : new int[]{userId};
1968        for (int nextUserId : userIds) {
1969            if (!sUserManager.exists(nextUserId)) return;
1970            mDirtyUsers.add(nextUserId);
1971            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1972                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1973            }
1974        }
1975    }
1976
1977    public static PackageManagerService main(Context context, Installer installer,
1978            boolean factoryTest, boolean onlyCore) {
1979        // Self-check for initial settings.
1980        PackageManagerServiceCompilerMapping.checkProperties();
1981
1982        PackageManagerService m = new PackageManagerService(context, installer,
1983                factoryTest, onlyCore);
1984        m.enableSystemUserPackages();
1985        ServiceManager.addService("package", m);
1986        return m;
1987    }
1988
1989    private void enableSystemUserPackages() {
1990        if (!UserManager.isSplitSystemUser()) {
1991            return;
1992        }
1993        // For system user, enable apps based on the following conditions:
1994        // - app is whitelisted or belong to one of these groups:
1995        //   -- system app which has no launcher icons
1996        //   -- system app which has INTERACT_ACROSS_USERS permission
1997        //   -- system IME app
1998        // - app is not in the blacklist
1999        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2000        Set<String> enableApps = new ArraySet<>();
2001        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2002                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2003                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2004        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2005        enableApps.addAll(wlApps);
2006        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2007                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2008        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2009        enableApps.removeAll(blApps);
2010        Log.i(TAG, "Applications installed for system user: " + enableApps);
2011        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2012                UserHandle.SYSTEM);
2013        final int allAppsSize = allAps.size();
2014        synchronized (mPackages) {
2015            for (int i = 0; i < allAppsSize; i++) {
2016                String pName = allAps.get(i);
2017                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2018                // Should not happen, but we shouldn't be failing if it does
2019                if (pkgSetting == null) {
2020                    continue;
2021                }
2022                boolean install = enableApps.contains(pName);
2023                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2024                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2025                            + " for system user");
2026                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2027                }
2028            }
2029        }
2030    }
2031
2032    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2033        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2034                Context.DISPLAY_SERVICE);
2035        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2036    }
2037
2038    /**
2039     * Requests that files preopted on a secondary system partition be copied to the data partition
2040     * if possible.  Note that the actual copying of the files is accomplished by init for security
2041     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2042     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2043     */
2044    private static void requestCopyPreoptedFiles() {
2045        final int WAIT_TIME_MS = 100;
2046        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2047        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2048            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2049            // We will wait for up to 100 seconds.
2050            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2051            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2052                try {
2053                    Thread.sleep(WAIT_TIME_MS);
2054                } catch (InterruptedException e) {
2055                    // Do nothing
2056                }
2057                if (SystemClock.uptimeMillis() > timeEnd) {
2058                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2059                    Slog.wtf(TAG, "cppreopt did not finish!");
2060                    break;
2061                }
2062            }
2063        }
2064    }
2065
2066    public PackageManagerService(Context context, Installer installer,
2067            boolean factoryTest, boolean onlyCore) {
2068        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2069        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2070                SystemClock.uptimeMillis());
2071
2072        if (mSdkVersion <= 0) {
2073            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2074        }
2075
2076        mContext = context;
2077
2078        mPermissionReviewRequired = context.getResources().getBoolean(
2079                R.bool.config_permissionReviewRequired);
2080
2081        mFactoryTest = factoryTest;
2082        mOnlyCore = onlyCore;
2083        mMetrics = new DisplayMetrics();
2084        mSettings = new Settings(mPackages);
2085        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2086                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2087        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2088                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2089        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2090                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2091        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2092                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2093        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2094                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2095        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2096                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2097
2098        String separateProcesses = SystemProperties.get("debug.separate_processes");
2099        if (separateProcesses != null && separateProcesses.length() > 0) {
2100            if ("*".equals(separateProcesses)) {
2101                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2102                mSeparateProcesses = null;
2103                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2104            } else {
2105                mDefParseFlags = 0;
2106                mSeparateProcesses = separateProcesses.split(",");
2107                Slog.w(TAG, "Running with debug.separate_processes: "
2108                        + separateProcesses);
2109            }
2110        } else {
2111            mDefParseFlags = 0;
2112            mSeparateProcesses = null;
2113        }
2114
2115        mInstaller = installer;
2116        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2117                "*dexopt*");
2118        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2119
2120        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2121                FgThread.get().getLooper());
2122
2123        getDefaultDisplayMetrics(context, mMetrics);
2124
2125        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2126        SystemConfig systemConfig = SystemConfig.getInstance();
2127        mGlobalGids = systemConfig.getGlobalGids();
2128        mSystemPermissions = systemConfig.getSystemPermissions();
2129        mAvailableFeatures = systemConfig.getAvailableFeatures();
2130        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2131
2132        mProtectedPackages = new ProtectedPackages(mContext);
2133
2134        synchronized (mInstallLock) {
2135        // writer
2136        synchronized (mPackages) {
2137            mHandlerThread = new ServiceThread(TAG,
2138                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2139            mHandlerThread.start();
2140            mHandler = new PackageHandler(mHandlerThread.getLooper());
2141            mProcessLoggingHandler = new ProcessLoggingHandler();
2142            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2143
2144            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2145
2146            File dataDir = Environment.getDataDirectory();
2147            mAppInstallDir = new File(dataDir, "app");
2148            mAppLib32InstallDir = new File(dataDir, "app-lib");
2149            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2150            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2151            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2152
2153            sUserManager = new UserManagerService(context, this, mPackages);
2154
2155            // Propagate permission configuration in to package manager.
2156            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2157                    = systemConfig.getPermissions();
2158            for (int i=0; i<permConfig.size(); i++) {
2159                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2160                BasePermission bp = mSettings.mPermissions.get(perm.name);
2161                if (bp == null) {
2162                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2163                    mSettings.mPermissions.put(perm.name, bp);
2164                }
2165                if (perm.gids != null) {
2166                    bp.setGids(perm.gids, perm.perUser);
2167                }
2168            }
2169
2170            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2171            for (int i=0; i<libConfig.size(); i++) {
2172                mSharedLibraries.put(libConfig.keyAt(i),
2173                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2174            }
2175
2176            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2177
2178            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2179            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2180            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2181
2182            if (mFirstBoot) {
2183                requestCopyPreoptedFiles();
2184            }
2185
2186            String customResolverActivity = Resources.getSystem().getString(
2187                    R.string.config_customResolverActivity);
2188            if (TextUtils.isEmpty(customResolverActivity)) {
2189                customResolverActivity = null;
2190            } else {
2191                mCustomResolverComponentName = ComponentName.unflattenFromString(
2192                        customResolverActivity);
2193            }
2194
2195            long startTime = SystemClock.uptimeMillis();
2196
2197            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2198                    startTime);
2199
2200            // Set flag to monitor and not change apk file paths when
2201            // scanning install directories.
2202            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2203
2204            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2205            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2206
2207            if (bootClassPath == null) {
2208                Slog.w(TAG, "No BOOTCLASSPATH found!");
2209            }
2210
2211            if (systemServerClassPath == null) {
2212                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2213            }
2214
2215            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2216            final String[] dexCodeInstructionSets =
2217                    getDexCodeInstructionSets(
2218                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2219
2220            /**
2221             * Ensure all external libraries have had dexopt run on them.
2222             */
2223            if (mSharedLibraries.size() > 0) {
2224                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2225                // NOTE: For now, we're compiling these system "shared libraries"
2226                // (and framework jars) into all available architectures. It's possible
2227                // to compile them only when we come across an app that uses them (there's
2228                // already logic for that in scanPackageLI) but that adds some complexity.
2229                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2230                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2231                        final String lib = libEntry.path;
2232                        if (lib == null) {
2233                            continue;
2234                        }
2235
2236                        try {
2237                            // Shared libraries do not have profiles so we perform a full
2238                            // AOT compilation (if needed).
2239                            int dexoptNeeded = DexFile.getDexOptNeeded(
2240                                    lib, dexCodeInstructionSet,
2241                                    getCompilerFilterForReason(REASON_SHARED_APK),
2242                                    false /* newProfile */);
2243                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2244                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2245                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2246                                        getCompilerFilterForReason(REASON_SHARED_APK),
2247                                        StorageManager.UUID_PRIVATE_INTERNAL,
2248                                        SKIP_SHARED_LIBRARY_CHECK);
2249                            }
2250                        } catch (FileNotFoundException e) {
2251                            Slog.w(TAG, "Library not found: " + lib);
2252                        } catch (IOException | InstallerException e) {
2253                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2254                                    + e.getMessage());
2255                        }
2256                    }
2257                }
2258                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2259            }
2260
2261            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2262
2263            final VersionInfo ver = mSettings.getInternalVersion();
2264            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2265
2266            // when upgrading from pre-M, promote system app permissions from install to runtime
2267            mPromoteSystemApps =
2268                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2269
2270            // When upgrading from pre-N, we need to handle package extraction like first boot,
2271            // as there is no profiling data available.
2272            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2273
2274            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2275
2276            // save off the names of pre-existing system packages prior to scanning; we don't
2277            // want to automatically grant runtime permissions for new system apps
2278            if (mPromoteSystemApps) {
2279                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2280                while (pkgSettingIter.hasNext()) {
2281                    PackageSetting ps = pkgSettingIter.next();
2282                    if (isSystemApp(ps)) {
2283                        mExistingSystemPackages.add(ps.name);
2284                    }
2285                }
2286            }
2287
2288            // Collect vendor overlay packages.
2289            // (Do this before scanning any apps.)
2290            // For security and version matching reason, only consider
2291            // overlay packages if they reside in the right directory.
2292            File vendorOverlayDir;
2293            String overlaySkuDir = SystemProperties.get(VENDOR_OVERLAY_SKU_PROPERTY);
2294            if (!overlaySkuDir.isEmpty()) {
2295                vendorOverlayDir = new File(VENDOR_OVERLAY_DIR, overlaySkuDir);
2296            } else {
2297                vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2298            }
2299            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2300                    | PackageParser.PARSE_IS_SYSTEM
2301                    | PackageParser.PARSE_IS_SYSTEM_DIR
2302                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2303
2304            // Find base frameworks (resource packages without code).
2305            scanDirTracedLI(frameworkDir, mDefParseFlags
2306                    | PackageParser.PARSE_IS_SYSTEM
2307                    | PackageParser.PARSE_IS_SYSTEM_DIR
2308                    | PackageParser.PARSE_IS_PRIVILEGED,
2309                    scanFlags | SCAN_NO_DEX, 0);
2310
2311            // Collected privileged system packages.
2312            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2313            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2314                    | PackageParser.PARSE_IS_SYSTEM
2315                    | PackageParser.PARSE_IS_SYSTEM_DIR
2316                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2317
2318            // Collect ordinary system packages.
2319            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2320            scanDirTracedLI(systemAppDir, mDefParseFlags
2321                    | PackageParser.PARSE_IS_SYSTEM
2322                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2323
2324            // Collect all vendor packages.
2325            File vendorAppDir = new File("/vendor/app");
2326            try {
2327                vendorAppDir = vendorAppDir.getCanonicalFile();
2328            } catch (IOException e) {
2329                // failed to look up canonical path, continue with original one
2330            }
2331            scanDirTracedLI(vendorAppDir, mDefParseFlags
2332                    | PackageParser.PARSE_IS_SYSTEM
2333                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2334
2335            // Collect all OEM packages.
2336            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2337            scanDirTracedLI(oemAppDir, mDefParseFlags
2338                    | PackageParser.PARSE_IS_SYSTEM
2339                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2340
2341            // Prune any system packages that no longer exist.
2342            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2343            if (!mOnlyCore) {
2344                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2345                while (psit.hasNext()) {
2346                    PackageSetting ps = psit.next();
2347
2348                    /*
2349                     * If this is not a system app, it can't be a
2350                     * disable system app.
2351                     */
2352                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2353                        continue;
2354                    }
2355
2356                    /*
2357                     * If the package is scanned, it's not erased.
2358                     */
2359                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2360                    if (scannedPkg != null) {
2361                        /*
2362                         * If the system app is both scanned and in the
2363                         * disabled packages list, then it must have been
2364                         * added via OTA. Remove it from the currently
2365                         * scanned package so the previously user-installed
2366                         * application can be scanned.
2367                         */
2368                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2369                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2370                                    + ps.name + "; removing system app.  Last known codePath="
2371                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2372                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2373                                    + scannedPkg.mVersionCode);
2374                            removePackageLI(scannedPkg, true);
2375                            mExpectingBetter.put(ps.name, ps.codePath);
2376                        }
2377
2378                        continue;
2379                    }
2380
2381                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2382                        psit.remove();
2383                        logCriticalInfo(Log.WARN, "System package " + ps.name
2384                                + " no longer exists; it's data will be wiped");
2385                        // Actual deletion of code and data will be handled by later
2386                        // reconciliation step
2387                    } else {
2388                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2389                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2390                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2391                        }
2392                    }
2393                }
2394            }
2395
2396            //look for any incomplete package installations
2397            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2398            for (int i = 0; i < deletePkgsList.size(); i++) {
2399                // Actual deletion of code and data will be handled by later
2400                // reconciliation step
2401                final String packageName = deletePkgsList.get(i).name;
2402                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2403                synchronized (mPackages) {
2404                    mSettings.removePackageLPw(packageName);
2405                }
2406            }
2407
2408            //delete tmp files
2409            deleteTempPackageFiles();
2410
2411            // Remove any shared userIDs that have no associated packages
2412            mSettings.pruneSharedUsersLPw();
2413
2414            if (!mOnlyCore) {
2415                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2416                        SystemClock.uptimeMillis());
2417                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2418
2419                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2420                        | PackageParser.PARSE_FORWARD_LOCK,
2421                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2422
2423                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2424                        | PackageParser.PARSE_IS_EPHEMERAL,
2425                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2426
2427                /**
2428                 * Remove disable package settings for any updated system
2429                 * apps that were removed via an OTA. If they're not a
2430                 * previously-updated app, remove them completely.
2431                 * Otherwise, just revoke their system-level permissions.
2432                 */
2433                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2434                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2435                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2436
2437                    String msg;
2438                    if (deletedPkg == null) {
2439                        msg = "Updated system package " + deletedAppName
2440                                + " no longer exists; it's data will be wiped";
2441                        // Actual deletion of code and data will be handled by later
2442                        // reconciliation step
2443                    } else {
2444                        msg = "Updated system app + " + deletedAppName
2445                                + " no longer present; removing system privileges for "
2446                                + deletedAppName;
2447
2448                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2449
2450                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2451                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2452                    }
2453                    logCriticalInfo(Log.WARN, msg);
2454                }
2455
2456                /**
2457                 * Make sure all system apps that we expected to appear on
2458                 * the userdata partition actually showed up. If they never
2459                 * appeared, crawl back and revive the system version.
2460                 */
2461                for (int i = 0; i < mExpectingBetter.size(); i++) {
2462                    final String packageName = mExpectingBetter.keyAt(i);
2463                    if (!mPackages.containsKey(packageName)) {
2464                        final File scanFile = mExpectingBetter.valueAt(i);
2465
2466                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2467                                + " but never showed up; reverting to system");
2468
2469                        int reparseFlags = mDefParseFlags;
2470                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2471                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2472                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2473                                    | PackageParser.PARSE_IS_PRIVILEGED;
2474                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2475                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2476                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2477                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2478                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2479                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2480                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2481                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2482                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2483                        } else {
2484                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2485                            continue;
2486                        }
2487
2488                        mSettings.enableSystemPackageLPw(packageName);
2489
2490                        try {
2491                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2492                        } catch (PackageManagerException e) {
2493                            Slog.e(TAG, "Failed to parse original system package: "
2494                                    + e.getMessage());
2495                        }
2496                    }
2497                }
2498            }
2499            mExpectingBetter.clear();
2500
2501            // Resolve the storage manager.
2502            mStorageManagerPackage = getStorageManagerPackageName();
2503
2504            // Resolve protected action filters. Only the setup wizard is allowed to
2505            // have a high priority filter for these actions.
2506            mSetupWizardPackage = getSetupWizardPackageName();
2507            if (mProtectedFilters.size() > 0) {
2508                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2509                    Slog.i(TAG, "No setup wizard;"
2510                        + " All protected intents capped to priority 0");
2511                }
2512                for (ActivityIntentInfo filter : mProtectedFilters) {
2513                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2514                        if (DEBUG_FILTERS) {
2515                            Slog.i(TAG, "Found setup wizard;"
2516                                + " allow priority " + filter.getPriority() + ";"
2517                                + " package: " + filter.activity.info.packageName
2518                                + " activity: " + filter.activity.className
2519                                + " priority: " + filter.getPriority());
2520                        }
2521                        // skip setup wizard; allow it to keep the high priority filter
2522                        continue;
2523                    }
2524                    Slog.w(TAG, "Protected action; cap priority to 0;"
2525                            + " package: " + filter.activity.info.packageName
2526                            + " activity: " + filter.activity.className
2527                            + " origPrio: " + filter.getPriority());
2528                    filter.setPriority(0);
2529                }
2530            }
2531            mDeferProtectedFilters = false;
2532            mProtectedFilters.clear();
2533
2534            // Now that we know all of the shared libraries, update all clients to have
2535            // the correct library paths.
2536            updateAllSharedLibrariesLPw();
2537
2538            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2539                // NOTE: We ignore potential failures here during a system scan (like
2540                // the rest of the commands above) because there's precious little we
2541                // can do about it. A settings error is reported, though.
2542                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2543            }
2544
2545            // Now that we know all the packages we are keeping,
2546            // read and update their last usage times.
2547            mPackageUsage.read(mPackages);
2548            mCompilerStats.read();
2549
2550            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2551                    SystemClock.uptimeMillis());
2552            Slog.i(TAG, "Time to scan packages: "
2553                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2554                    + " seconds");
2555
2556            // If the platform SDK has changed since the last time we booted,
2557            // we need to re-grant app permission to catch any new ones that
2558            // appear.  This is really a hack, and means that apps can in some
2559            // cases get permissions that the user didn't initially explicitly
2560            // allow...  it would be nice to have some better way to handle
2561            // this situation.
2562            int updateFlags = UPDATE_PERMISSIONS_ALL;
2563            if (ver.sdkVersion != mSdkVersion) {
2564                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2565                        + mSdkVersion + "; regranting permissions for internal storage");
2566                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2567            }
2568            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2569            ver.sdkVersion = mSdkVersion;
2570
2571            // If this is the first boot or an update from pre-M, and it is a normal
2572            // boot, then we need to initialize the default preferred apps across
2573            // all defined users.
2574            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2575                for (UserInfo user : sUserManager.getUsers(true)) {
2576                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2577                    applyFactoryDefaultBrowserLPw(user.id);
2578                    primeDomainVerificationsLPw(user.id);
2579                }
2580            }
2581
2582            // Prepare storage for system user really early during boot,
2583            // since core system apps like SettingsProvider and SystemUI
2584            // can't wait for user to start
2585            final int storageFlags;
2586            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2587                storageFlags = StorageManager.FLAG_STORAGE_DE;
2588            } else {
2589                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2590            }
2591            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2592                    storageFlags, true /* migrateAppData */);
2593
2594            // If this is first boot after an OTA, and a normal boot, then
2595            // we need to clear code cache directories.
2596            // Note that we do *not* clear the application profiles. These remain valid
2597            // across OTAs and are used to drive profile verification (post OTA) and
2598            // profile compilation (without waiting to collect a fresh set of profiles).
2599            if (mIsUpgrade && !onlyCore) {
2600                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2601                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2602                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2603                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2604                        // No apps are running this early, so no need to freeze
2605                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2606                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2607                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2608                    }
2609                }
2610                ver.fingerprint = Build.FINGERPRINT;
2611            }
2612
2613            checkDefaultBrowser();
2614
2615            // clear only after permissions and other defaults have been updated
2616            mExistingSystemPackages.clear();
2617            mPromoteSystemApps = false;
2618
2619            // All the changes are done during package scanning.
2620            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2621
2622            // can downgrade to reader
2623            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2624            mSettings.writeLPr();
2625            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2626
2627            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2628            // early on (before the package manager declares itself as early) because other
2629            // components in the system server might ask for package contexts for these apps.
2630            //
2631            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2632            // (i.e, that the data partition is unavailable).
2633            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2634                long start = System.nanoTime();
2635                List<PackageParser.Package> coreApps = new ArrayList<>();
2636                for (PackageParser.Package pkg : mPackages.values()) {
2637                    if (pkg.coreApp) {
2638                        coreApps.add(pkg);
2639                    }
2640                }
2641
2642                int[] stats = performDexOptUpgrade(coreApps, false,
2643                        getCompilerFilterForReason(REASON_CORE_APP));
2644
2645                final int elapsedTimeSeconds =
2646                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2647                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2648
2649                if (DEBUG_DEXOPT) {
2650                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2651                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2652                }
2653
2654
2655                // TODO: Should we log these stats to tron too ?
2656                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2657                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2658                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2659                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2660            }
2661
2662            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2663                    SystemClock.uptimeMillis());
2664
2665            if (!mOnlyCore) {
2666                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2667                mRequiredInstallerPackage = getRequiredInstallerLPr();
2668                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2669                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2670                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2671                        mIntentFilterVerifierComponent);
2672                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2673                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2674                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2675                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2676            } else {
2677                mRequiredVerifierPackage = null;
2678                mRequiredInstallerPackage = null;
2679                mRequiredUninstallerPackage = null;
2680                mIntentFilterVerifierComponent = null;
2681                mIntentFilterVerifier = null;
2682                mServicesSystemSharedLibraryPackageName = null;
2683                mSharedSystemSharedLibraryPackageName = null;
2684            }
2685
2686            mInstallerService = new PackageInstallerService(context, this);
2687
2688            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2689            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2690            // both the installer and resolver must be present to enable ephemeral
2691            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2692                if (DEBUG_EPHEMERAL) {
2693                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2694                            + " installer:" + ephemeralInstallerComponent);
2695                }
2696                mEphemeralResolverComponent = ephemeralResolverComponent;
2697                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2698                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2699                mEphemeralResolverConnection =
2700                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2701            } else {
2702                if (DEBUG_EPHEMERAL) {
2703                    final String missingComponent =
2704                            (ephemeralResolverComponent == null)
2705                            ? (ephemeralInstallerComponent == null)
2706                                    ? "resolver and installer"
2707                                    : "resolver"
2708                            : "installer";
2709                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2710                }
2711                mEphemeralResolverComponent = null;
2712                mEphemeralInstallerComponent = null;
2713                mEphemeralResolverConnection = null;
2714            }
2715
2716            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2717        } // synchronized (mPackages)
2718        } // synchronized (mInstallLock)
2719
2720        // Now after opening every single application zip, make sure they
2721        // are all flushed.  Not really needed, but keeps things nice and
2722        // tidy.
2723        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2724        Runtime.getRuntime().gc();
2725        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2726
2727        // The initial scanning above does many calls into installd while
2728        // holding the mPackages lock, but we're mostly interested in yelling
2729        // once we have a booted system.
2730        mInstaller.setWarnIfHeld(mPackages);
2731
2732        // Expose private service for system components to use.
2733        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2734        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2735    }
2736
2737    @Override
2738    public boolean isFirstBoot() {
2739        return mFirstBoot;
2740    }
2741
2742    @Override
2743    public boolean isOnlyCoreApps() {
2744        return mOnlyCore;
2745    }
2746
2747    @Override
2748    public boolean isUpgrade() {
2749        return mIsUpgrade;
2750    }
2751
2752    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2753        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2754
2755        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2756                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2757                UserHandle.USER_SYSTEM);
2758        if (matches.size() == 1) {
2759            return matches.get(0).getComponentInfo().packageName;
2760        } else if (matches.size() == 0) {
2761            Log.e(TAG, "There should probably be a verifier, but, none were found");
2762            return null;
2763        }
2764        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2765    }
2766
2767    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2768        synchronized (mPackages) {
2769            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2770            if (libraryEntry == null) {
2771                throw new IllegalStateException("Missing required shared library:" + libraryName);
2772            }
2773            return libraryEntry.apk;
2774        }
2775    }
2776
2777    private @NonNull String getRequiredInstallerLPr() {
2778        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2779        intent.addCategory(Intent.CATEGORY_DEFAULT);
2780        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2781
2782        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2783                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2784                UserHandle.USER_SYSTEM);
2785        if (matches.size() == 1) {
2786            ResolveInfo resolveInfo = matches.get(0);
2787            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2788                throw new RuntimeException("The installer must be a privileged app");
2789            }
2790            return matches.get(0).getComponentInfo().packageName;
2791        } else {
2792            throw new RuntimeException("There must be exactly one installer; found " + matches);
2793        }
2794    }
2795
2796    private @NonNull String getRequiredUninstallerLPr() {
2797        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2798        intent.addCategory(Intent.CATEGORY_DEFAULT);
2799        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2800
2801        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2802                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2803                UserHandle.USER_SYSTEM);
2804        if (resolveInfo == null ||
2805                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2806            throw new RuntimeException("There must be exactly one uninstaller; found "
2807                    + resolveInfo);
2808        }
2809        return resolveInfo.getComponentInfo().packageName;
2810    }
2811
2812    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2813        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2814
2815        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2816                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2817                UserHandle.USER_SYSTEM);
2818        ResolveInfo best = null;
2819        final int N = matches.size();
2820        for (int i = 0; i < N; i++) {
2821            final ResolveInfo cur = matches.get(i);
2822            final String packageName = cur.getComponentInfo().packageName;
2823            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2824                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2825                continue;
2826            }
2827
2828            if (best == null || cur.priority > best.priority) {
2829                best = cur;
2830            }
2831        }
2832
2833        if (best != null) {
2834            return best.getComponentInfo().getComponentName();
2835        } else {
2836            throw new RuntimeException("There must be at least one intent filter verifier");
2837        }
2838    }
2839
2840    private @Nullable ComponentName getEphemeralResolverLPr() {
2841        final String[] packageArray =
2842                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2843        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2844            if (DEBUG_EPHEMERAL) {
2845                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2846            }
2847            return null;
2848        }
2849
2850        final int resolveFlags =
2851                MATCH_DIRECT_BOOT_AWARE
2852                | MATCH_DIRECT_BOOT_UNAWARE
2853                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2854        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2855        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2856                resolveFlags, UserHandle.USER_SYSTEM);
2857
2858        final int N = resolvers.size();
2859        if (N == 0) {
2860            if (DEBUG_EPHEMERAL) {
2861                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2862            }
2863            return null;
2864        }
2865
2866        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2867        for (int i = 0; i < N; i++) {
2868            final ResolveInfo info = resolvers.get(i);
2869
2870            if (info.serviceInfo == null) {
2871                continue;
2872            }
2873
2874            final String packageName = info.serviceInfo.packageName;
2875            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2876                if (DEBUG_EPHEMERAL) {
2877                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2878                            + " pkg: " + packageName + ", info:" + info);
2879                }
2880                continue;
2881            }
2882
2883            if (DEBUG_EPHEMERAL) {
2884                Slog.v(TAG, "Ephemeral resolver found;"
2885                        + " pkg: " + packageName + ", info:" + info);
2886            }
2887            return new ComponentName(packageName, info.serviceInfo.name);
2888        }
2889        if (DEBUG_EPHEMERAL) {
2890            Slog.v(TAG, "Ephemeral resolver NOT found");
2891        }
2892        return null;
2893    }
2894
2895    private @Nullable ComponentName getEphemeralInstallerLPr() {
2896        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2897        intent.addCategory(Intent.CATEGORY_DEFAULT);
2898        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2899
2900        final int resolveFlags =
2901                MATCH_DIRECT_BOOT_AWARE
2902                | MATCH_DIRECT_BOOT_UNAWARE
2903                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2904        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2905                resolveFlags, UserHandle.USER_SYSTEM);
2906        if (matches.size() == 0) {
2907            return null;
2908        } else if (matches.size() == 1) {
2909            return matches.get(0).getComponentInfo().getComponentName();
2910        } else {
2911            throw new RuntimeException(
2912                    "There must be at most one ephemeral installer; found " + matches);
2913        }
2914    }
2915
2916    private void primeDomainVerificationsLPw(int userId) {
2917        if (DEBUG_DOMAIN_VERIFICATION) {
2918            Slog.d(TAG, "Priming domain verifications in user " + userId);
2919        }
2920
2921        SystemConfig systemConfig = SystemConfig.getInstance();
2922        ArraySet<String> packages = systemConfig.getLinkedApps();
2923
2924        for (String packageName : packages) {
2925            PackageParser.Package pkg = mPackages.get(packageName);
2926            if (pkg != null) {
2927                if (!pkg.isSystemApp()) {
2928                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2929                    continue;
2930                }
2931
2932                ArraySet<String> domains = null;
2933                for (PackageParser.Activity a : pkg.activities) {
2934                    for (ActivityIntentInfo filter : a.intents) {
2935                        if (hasValidDomains(filter)) {
2936                            if (domains == null) {
2937                                domains = new ArraySet<String>();
2938                            }
2939                            domains.addAll(filter.getHostsList());
2940                        }
2941                    }
2942                }
2943
2944                if (domains != null && domains.size() > 0) {
2945                    if (DEBUG_DOMAIN_VERIFICATION) {
2946                        Slog.v(TAG, "      + " + packageName);
2947                    }
2948                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2949                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2950                    // and then 'always' in the per-user state actually used for intent resolution.
2951                    final IntentFilterVerificationInfo ivi;
2952                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
2953                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2954                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2955                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2956                } else {
2957                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2958                            + "' does not handle web links");
2959                }
2960            } else {
2961                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2962            }
2963        }
2964
2965        scheduleWritePackageRestrictionsLocked(userId);
2966        scheduleWriteSettingsLocked();
2967    }
2968
2969    private void applyFactoryDefaultBrowserLPw(int userId) {
2970        // The default browser app's package name is stored in a string resource,
2971        // with a product-specific overlay used for vendor customization.
2972        String browserPkg = mContext.getResources().getString(
2973                com.android.internal.R.string.default_browser);
2974        if (!TextUtils.isEmpty(browserPkg)) {
2975            // non-empty string => required to be a known package
2976            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2977            if (ps == null) {
2978                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2979                browserPkg = null;
2980            } else {
2981                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2982            }
2983        }
2984
2985        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2986        // default.  If there's more than one, just leave everything alone.
2987        if (browserPkg == null) {
2988            calculateDefaultBrowserLPw(userId);
2989        }
2990    }
2991
2992    private void calculateDefaultBrowserLPw(int userId) {
2993        List<String> allBrowsers = resolveAllBrowserApps(userId);
2994        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2995        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2996    }
2997
2998    private List<String> resolveAllBrowserApps(int userId) {
2999        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3000        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3001                PackageManager.MATCH_ALL, userId);
3002
3003        final int count = list.size();
3004        List<String> result = new ArrayList<String>(count);
3005        for (int i=0; i<count; i++) {
3006            ResolveInfo info = list.get(i);
3007            if (info.activityInfo == null
3008                    || !info.handleAllWebDataURI
3009                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3010                    || result.contains(info.activityInfo.packageName)) {
3011                continue;
3012            }
3013            result.add(info.activityInfo.packageName);
3014        }
3015
3016        return result;
3017    }
3018
3019    private boolean packageIsBrowser(String packageName, int userId) {
3020        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3021                PackageManager.MATCH_ALL, userId);
3022        final int N = list.size();
3023        for (int i = 0; i < N; i++) {
3024            ResolveInfo info = list.get(i);
3025            if (packageName.equals(info.activityInfo.packageName)) {
3026                return true;
3027            }
3028        }
3029        return false;
3030    }
3031
3032    private void checkDefaultBrowser() {
3033        final int myUserId = UserHandle.myUserId();
3034        final String packageName = getDefaultBrowserPackageName(myUserId);
3035        if (packageName != null) {
3036            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3037            if (info == null) {
3038                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3039                synchronized (mPackages) {
3040                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3041                }
3042            }
3043        }
3044    }
3045
3046    @Override
3047    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3048            throws RemoteException {
3049        try {
3050            return super.onTransact(code, data, reply, flags);
3051        } catch (RuntimeException e) {
3052            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3053                Slog.wtf(TAG, "Package Manager Crash", e);
3054            }
3055            throw e;
3056        }
3057    }
3058
3059    static int[] appendInts(int[] cur, int[] add) {
3060        if (add == null) return cur;
3061        if (cur == null) return add;
3062        final int N = add.length;
3063        for (int i=0; i<N; i++) {
3064            cur = appendInt(cur, add[i]);
3065        }
3066        return cur;
3067    }
3068
3069    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3070        if (!sUserManager.exists(userId)) return null;
3071        if (ps == null) {
3072            return null;
3073        }
3074        final PackageParser.Package p = ps.pkg;
3075        if (p == null) {
3076            return null;
3077        }
3078
3079        final PermissionsState permissionsState = ps.getPermissionsState();
3080
3081        // Compute GIDs only if requested
3082        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3083                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3084        // Compute granted permissions only if package has requested permissions
3085        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3086                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3087        final PackageUserState state = ps.readUserState(userId);
3088
3089        return PackageParser.generatePackageInfo(p, gids, flags,
3090                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3091    }
3092
3093    @Override
3094    public void checkPackageStartable(String packageName, int userId) {
3095        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3096
3097        synchronized (mPackages) {
3098            final PackageSetting ps = mSettings.mPackages.get(packageName);
3099            if (ps == null) {
3100                throw new SecurityException("Package " + packageName + " was not found!");
3101            }
3102
3103            if (!ps.getInstalled(userId)) {
3104                throw new SecurityException(
3105                        "Package " + packageName + " was not installed for user " + userId + "!");
3106            }
3107
3108            if (mSafeMode && !ps.isSystem()) {
3109                throw new SecurityException("Package " + packageName + " not a system app!");
3110            }
3111
3112            if (mFrozenPackages.contains(packageName)) {
3113                throw new SecurityException("Package " + packageName + " is currently frozen!");
3114            }
3115
3116            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3117                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3118                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3119            }
3120        }
3121    }
3122
3123    @Override
3124    public boolean isPackageAvailable(String packageName, int userId) {
3125        if (!sUserManager.exists(userId)) return false;
3126        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3127                false /* requireFullPermission */, false /* checkShell */, "is package available");
3128        synchronized (mPackages) {
3129            PackageParser.Package p = mPackages.get(packageName);
3130            if (p != null) {
3131                final PackageSetting ps = (PackageSetting) p.mExtras;
3132                if (ps != null) {
3133                    final PackageUserState state = ps.readUserState(userId);
3134                    if (state != null) {
3135                        return PackageParser.isAvailable(state);
3136                    }
3137                }
3138            }
3139        }
3140        return false;
3141    }
3142
3143    @Override
3144    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3145        if (!sUserManager.exists(userId)) return null;
3146        flags = updateFlagsForPackage(flags, userId, packageName);
3147        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3148                false /* requireFullPermission */, false /* checkShell */, "get package info");
3149        // reader
3150        synchronized (mPackages) {
3151            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3152            PackageParser.Package p = null;
3153            if (matchFactoryOnly) {
3154                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3155                if (ps != null) {
3156                    return generatePackageInfo(ps, flags, userId);
3157                }
3158            }
3159            if (p == null) {
3160                p = mPackages.get(packageName);
3161                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3162                    return null;
3163                }
3164            }
3165            if (DEBUG_PACKAGE_INFO)
3166                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3167            if (p != null) {
3168                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3169            }
3170            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3171                final PackageSetting ps = mSettings.mPackages.get(packageName);
3172                return generatePackageInfo(ps, flags, userId);
3173            }
3174        }
3175        return null;
3176    }
3177
3178    @Override
3179    public String[] currentToCanonicalPackageNames(String[] names) {
3180        String[] out = new String[names.length];
3181        // reader
3182        synchronized (mPackages) {
3183            for (int i=names.length-1; i>=0; i--) {
3184                PackageSetting ps = mSettings.mPackages.get(names[i]);
3185                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3186            }
3187        }
3188        return out;
3189    }
3190
3191    @Override
3192    public String[] canonicalToCurrentPackageNames(String[] names) {
3193        String[] out = new String[names.length];
3194        // reader
3195        synchronized (mPackages) {
3196            for (int i=names.length-1; i>=0; i--) {
3197                String cur = mSettings.getRenamedPackageLPr(names[i]);
3198                out[i] = cur != null ? cur : names[i];
3199            }
3200        }
3201        return out;
3202    }
3203
3204    @Override
3205    public int getPackageUid(String packageName, int flags, int userId) {
3206        if (!sUserManager.exists(userId)) return -1;
3207        flags = updateFlagsForPackage(flags, userId, packageName);
3208        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3209                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3210
3211        // reader
3212        synchronized (mPackages) {
3213            final PackageParser.Package p = mPackages.get(packageName);
3214            if (p != null && p.isMatch(flags)) {
3215                return UserHandle.getUid(userId, p.applicationInfo.uid);
3216            }
3217            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3218                final PackageSetting ps = mSettings.mPackages.get(packageName);
3219                if (ps != null && ps.isMatch(flags)) {
3220                    return UserHandle.getUid(userId, ps.appId);
3221                }
3222            }
3223        }
3224
3225        return -1;
3226    }
3227
3228    @Override
3229    public int[] getPackageGids(String packageName, int flags, int userId) {
3230        if (!sUserManager.exists(userId)) return null;
3231        flags = updateFlagsForPackage(flags, userId, packageName);
3232        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3233                false /* requireFullPermission */, false /* checkShell */,
3234                "getPackageGids");
3235
3236        // reader
3237        synchronized (mPackages) {
3238            final PackageParser.Package p = mPackages.get(packageName);
3239            if (p != null && p.isMatch(flags)) {
3240                PackageSetting ps = (PackageSetting) p.mExtras;
3241                return ps.getPermissionsState().computeGids(userId);
3242            }
3243            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3244                final PackageSetting ps = mSettings.mPackages.get(packageName);
3245                if (ps != null && ps.isMatch(flags)) {
3246                    return ps.getPermissionsState().computeGids(userId);
3247                }
3248            }
3249        }
3250
3251        return null;
3252    }
3253
3254    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3255        if (bp.perm != null) {
3256            return PackageParser.generatePermissionInfo(bp.perm, flags);
3257        }
3258        PermissionInfo pi = new PermissionInfo();
3259        pi.name = bp.name;
3260        pi.packageName = bp.sourcePackage;
3261        pi.nonLocalizedLabel = bp.name;
3262        pi.protectionLevel = bp.protectionLevel;
3263        return pi;
3264    }
3265
3266    @Override
3267    public PermissionInfo getPermissionInfo(String name, int flags) {
3268        // reader
3269        synchronized (mPackages) {
3270            final BasePermission p = mSettings.mPermissions.get(name);
3271            if (p != null) {
3272                return generatePermissionInfo(p, flags);
3273            }
3274            return null;
3275        }
3276    }
3277
3278    @Override
3279    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3280            int flags) {
3281        // reader
3282        synchronized (mPackages) {
3283            if (group != null && !mPermissionGroups.containsKey(group)) {
3284                // This is thrown as NameNotFoundException
3285                return null;
3286            }
3287
3288            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3289            for (BasePermission p : mSettings.mPermissions.values()) {
3290                if (group == null) {
3291                    if (p.perm == null || p.perm.info.group == null) {
3292                        out.add(generatePermissionInfo(p, flags));
3293                    }
3294                } else {
3295                    if (p.perm != null && group.equals(p.perm.info.group)) {
3296                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3297                    }
3298                }
3299            }
3300            return new ParceledListSlice<>(out);
3301        }
3302    }
3303
3304    @Override
3305    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3306        // reader
3307        synchronized (mPackages) {
3308            return PackageParser.generatePermissionGroupInfo(
3309                    mPermissionGroups.get(name), flags);
3310        }
3311    }
3312
3313    @Override
3314    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3315        // reader
3316        synchronized (mPackages) {
3317            final int N = mPermissionGroups.size();
3318            ArrayList<PermissionGroupInfo> out
3319                    = new ArrayList<PermissionGroupInfo>(N);
3320            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3321                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3322            }
3323            return new ParceledListSlice<>(out);
3324        }
3325    }
3326
3327    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3328            int userId) {
3329        if (!sUserManager.exists(userId)) return null;
3330        PackageSetting ps = mSettings.mPackages.get(packageName);
3331        if (ps != null) {
3332            if (ps.pkg == null) {
3333                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3334                if (pInfo != null) {
3335                    return pInfo.applicationInfo;
3336                }
3337                return null;
3338            }
3339            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3340                    ps.readUserState(userId), userId);
3341        }
3342        return null;
3343    }
3344
3345    @Override
3346    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3347        if (!sUserManager.exists(userId)) return null;
3348        flags = updateFlagsForApplication(flags, userId, packageName);
3349        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3350                false /* requireFullPermission */, false /* checkShell */, "get application info");
3351        // writer
3352        synchronized (mPackages) {
3353            PackageParser.Package p = mPackages.get(packageName);
3354            if (DEBUG_PACKAGE_INFO) Log.v(
3355                    TAG, "getApplicationInfo " + packageName
3356                    + ": " + p);
3357            if (p != null) {
3358                PackageSetting ps = mSettings.mPackages.get(packageName);
3359                if (ps == null) return null;
3360                // Note: isEnabledLP() does not apply here - always return info
3361                return PackageParser.generateApplicationInfo(
3362                        p, flags, ps.readUserState(userId), userId);
3363            }
3364            if ("android".equals(packageName)||"system".equals(packageName)) {
3365                return mAndroidApplication;
3366            }
3367            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3368                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3369            }
3370        }
3371        return null;
3372    }
3373
3374    @Override
3375    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3376            final IPackageDataObserver observer) {
3377        mContext.enforceCallingOrSelfPermission(
3378                android.Manifest.permission.CLEAR_APP_CACHE, null);
3379        // Queue up an async operation since clearing cache may take a little while.
3380        mHandler.post(new Runnable() {
3381            public void run() {
3382                mHandler.removeCallbacks(this);
3383                boolean success = true;
3384                synchronized (mInstallLock) {
3385                    try {
3386                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3387                    } catch (InstallerException e) {
3388                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3389                        success = false;
3390                    }
3391                }
3392                if (observer != null) {
3393                    try {
3394                        observer.onRemoveCompleted(null, success);
3395                    } catch (RemoteException e) {
3396                        Slog.w(TAG, "RemoveException when invoking call back");
3397                    }
3398                }
3399            }
3400        });
3401    }
3402
3403    @Override
3404    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3405            final IntentSender pi) {
3406        mContext.enforceCallingOrSelfPermission(
3407                android.Manifest.permission.CLEAR_APP_CACHE, null);
3408        // Queue up an async operation since clearing cache may take a little while.
3409        mHandler.post(new Runnable() {
3410            public void run() {
3411                mHandler.removeCallbacks(this);
3412                boolean success = true;
3413                synchronized (mInstallLock) {
3414                    try {
3415                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3416                    } catch (InstallerException e) {
3417                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3418                        success = false;
3419                    }
3420                }
3421                if(pi != null) {
3422                    try {
3423                        // Callback via pending intent
3424                        int code = success ? 1 : 0;
3425                        pi.sendIntent(null, code, null,
3426                                null, null);
3427                    } catch (SendIntentException e1) {
3428                        Slog.i(TAG, "Failed to send pending intent");
3429                    }
3430                }
3431            }
3432        });
3433    }
3434
3435    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3436        synchronized (mInstallLock) {
3437            try {
3438                mInstaller.freeCache(volumeUuid, freeStorageSize);
3439            } catch (InstallerException e) {
3440                throw new IOException("Failed to free enough space", e);
3441            }
3442        }
3443    }
3444
3445    /**
3446     * Update given flags based on encryption status of current user.
3447     */
3448    private int updateFlags(int flags, int userId) {
3449        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3450                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3451            // Caller expressed an explicit opinion about what encryption
3452            // aware/unaware components they want to see, so fall through and
3453            // give them what they want
3454        } else {
3455            // Caller expressed no opinion, so match based on user state
3456            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3457                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3458            } else {
3459                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3460            }
3461        }
3462        return flags;
3463    }
3464
3465    private UserManagerInternal getUserManagerInternal() {
3466        if (mUserManagerInternal == null) {
3467            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3468        }
3469        return mUserManagerInternal;
3470    }
3471
3472    /**
3473     * Update given flags when being used to request {@link PackageInfo}.
3474     */
3475    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3476        boolean triaged = true;
3477        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3478                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3479            // Caller is asking for component details, so they'd better be
3480            // asking for specific encryption matching behavior, or be triaged
3481            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3482                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3483                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3484                triaged = false;
3485            }
3486        }
3487        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3488                | PackageManager.MATCH_SYSTEM_ONLY
3489                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3490            triaged = false;
3491        }
3492        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3493            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3494                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3495        }
3496        return updateFlags(flags, userId);
3497    }
3498
3499    /**
3500     * Update given flags when being used to request {@link ApplicationInfo}.
3501     */
3502    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3503        return updateFlagsForPackage(flags, userId, cookie);
3504    }
3505
3506    /**
3507     * Update given flags when being used to request {@link ComponentInfo}.
3508     */
3509    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3510        if (cookie instanceof Intent) {
3511            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3512                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3513            }
3514        }
3515
3516        boolean triaged = true;
3517        // Caller is asking for component details, so they'd better be
3518        // asking for specific encryption matching behavior, or be triaged
3519        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3520                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3521                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3522            triaged = false;
3523        }
3524        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3525            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3526                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3527        }
3528
3529        return updateFlags(flags, userId);
3530    }
3531
3532    /**
3533     * Update given flags when being used to request {@link ResolveInfo}.
3534     */
3535    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3536        // Safe mode means we shouldn't match any third-party components
3537        if (mSafeMode) {
3538            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3539        }
3540
3541        return updateFlagsForComponent(flags, userId, cookie);
3542    }
3543
3544    @Override
3545    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3546        if (!sUserManager.exists(userId)) return null;
3547        flags = updateFlagsForComponent(flags, userId, component);
3548        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3549                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3550        synchronized (mPackages) {
3551            PackageParser.Activity a = mActivities.mActivities.get(component);
3552
3553            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3554            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3555                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3556                if (ps == null) return null;
3557                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3558                        userId);
3559            }
3560            if (mResolveComponentName.equals(component)) {
3561                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3562                        new PackageUserState(), userId);
3563            }
3564        }
3565        return null;
3566    }
3567
3568    @Override
3569    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3570            String resolvedType) {
3571        synchronized (mPackages) {
3572            if (component.equals(mResolveComponentName)) {
3573                // The resolver supports EVERYTHING!
3574                return true;
3575            }
3576            PackageParser.Activity a = mActivities.mActivities.get(component);
3577            if (a == null) {
3578                return false;
3579            }
3580            for (int i=0; i<a.intents.size(); i++) {
3581                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3582                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3583                    return true;
3584                }
3585            }
3586            return false;
3587        }
3588    }
3589
3590    @Override
3591    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3592        if (!sUserManager.exists(userId)) return null;
3593        flags = updateFlagsForComponent(flags, userId, component);
3594        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3595                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3596        synchronized (mPackages) {
3597            PackageParser.Activity a = mReceivers.mActivities.get(component);
3598            if (DEBUG_PACKAGE_INFO) Log.v(
3599                TAG, "getReceiverInfo " + component + ": " + a);
3600            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3601                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3602                if (ps == null) return null;
3603                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3604                        userId);
3605            }
3606        }
3607        return null;
3608    }
3609
3610    @Override
3611    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3612        if (!sUserManager.exists(userId)) return null;
3613        flags = updateFlagsForComponent(flags, userId, component);
3614        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3615                false /* requireFullPermission */, false /* checkShell */, "get service info");
3616        synchronized (mPackages) {
3617            PackageParser.Service s = mServices.mServices.get(component);
3618            if (DEBUG_PACKAGE_INFO) Log.v(
3619                TAG, "getServiceInfo " + component + ": " + s);
3620            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3621                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3622                if (ps == null) return null;
3623                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3624                        userId);
3625            }
3626        }
3627        return null;
3628    }
3629
3630    @Override
3631    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3632        if (!sUserManager.exists(userId)) return null;
3633        flags = updateFlagsForComponent(flags, userId, component);
3634        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3635                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3636        synchronized (mPackages) {
3637            PackageParser.Provider p = mProviders.mProviders.get(component);
3638            if (DEBUG_PACKAGE_INFO) Log.v(
3639                TAG, "getProviderInfo " + component + ": " + p);
3640            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3641                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3642                if (ps == null) return null;
3643                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3644                        userId);
3645            }
3646        }
3647        return null;
3648    }
3649
3650    @Override
3651    public String[] getSystemSharedLibraryNames() {
3652        Set<String> libSet;
3653        synchronized (mPackages) {
3654            libSet = mSharedLibraries.keySet();
3655            int size = libSet.size();
3656            if (size > 0) {
3657                String[] libs = new String[size];
3658                libSet.toArray(libs);
3659                return libs;
3660            }
3661        }
3662        return null;
3663    }
3664
3665    @Override
3666    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3667        synchronized (mPackages) {
3668            return mServicesSystemSharedLibraryPackageName;
3669        }
3670    }
3671
3672    @Override
3673    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3674        synchronized (mPackages) {
3675            return mSharedSystemSharedLibraryPackageName;
3676        }
3677    }
3678
3679    @Override
3680    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3681        synchronized (mPackages) {
3682            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3683
3684            final FeatureInfo fi = new FeatureInfo();
3685            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3686                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3687            res.add(fi);
3688
3689            return new ParceledListSlice<>(res);
3690        }
3691    }
3692
3693    @Override
3694    public boolean hasSystemFeature(String name, int version) {
3695        synchronized (mPackages) {
3696            final FeatureInfo feat = mAvailableFeatures.get(name);
3697            if (feat == null) {
3698                return false;
3699            } else {
3700                return feat.version >= version;
3701            }
3702        }
3703    }
3704
3705    @Override
3706    public int checkPermission(String permName, String pkgName, int userId) {
3707        if (!sUserManager.exists(userId)) {
3708            return PackageManager.PERMISSION_DENIED;
3709        }
3710
3711        synchronized (mPackages) {
3712            final PackageParser.Package p = mPackages.get(pkgName);
3713            if (p != null && p.mExtras != null) {
3714                final PackageSetting ps = (PackageSetting) p.mExtras;
3715                final PermissionsState permissionsState = ps.getPermissionsState();
3716                if (permissionsState.hasPermission(permName, userId)) {
3717                    return PackageManager.PERMISSION_GRANTED;
3718                }
3719                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3720                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3721                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3722                    return PackageManager.PERMISSION_GRANTED;
3723                }
3724            }
3725        }
3726
3727        return PackageManager.PERMISSION_DENIED;
3728    }
3729
3730    @Override
3731    public int checkUidPermission(String permName, int uid) {
3732        final int userId = UserHandle.getUserId(uid);
3733
3734        if (!sUserManager.exists(userId)) {
3735            return PackageManager.PERMISSION_DENIED;
3736        }
3737
3738        synchronized (mPackages) {
3739            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3740            if (obj != null) {
3741                final SettingBase ps = (SettingBase) obj;
3742                final PermissionsState permissionsState = ps.getPermissionsState();
3743                if (permissionsState.hasPermission(permName, userId)) {
3744                    return PackageManager.PERMISSION_GRANTED;
3745                }
3746                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3747                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3748                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3749                    return PackageManager.PERMISSION_GRANTED;
3750                }
3751            } else {
3752                ArraySet<String> perms = mSystemPermissions.get(uid);
3753                if (perms != null) {
3754                    if (perms.contains(permName)) {
3755                        return PackageManager.PERMISSION_GRANTED;
3756                    }
3757                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3758                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3759                        return PackageManager.PERMISSION_GRANTED;
3760                    }
3761                }
3762            }
3763        }
3764
3765        return PackageManager.PERMISSION_DENIED;
3766    }
3767
3768    @Override
3769    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3770        if (UserHandle.getCallingUserId() != userId) {
3771            mContext.enforceCallingPermission(
3772                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3773                    "isPermissionRevokedByPolicy for user " + userId);
3774        }
3775
3776        if (checkPermission(permission, packageName, userId)
3777                == PackageManager.PERMISSION_GRANTED) {
3778            return false;
3779        }
3780
3781        final long identity = Binder.clearCallingIdentity();
3782        try {
3783            final int flags = getPermissionFlags(permission, packageName, userId);
3784            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3785        } finally {
3786            Binder.restoreCallingIdentity(identity);
3787        }
3788    }
3789
3790    @Override
3791    public String getPermissionControllerPackageName() {
3792        synchronized (mPackages) {
3793            return mRequiredInstallerPackage;
3794        }
3795    }
3796
3797    /**
3798     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3799     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3800     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3801     * @param message the message to log on security exception
3802     */
3803    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3804            boolean checkShell, String message) {
3805        if (userId < 0) {
3806            throw new IllegalArgumentException("Invalid userId " + userId);
3807        }
3808        if (checkShell) {
3809            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3810        }
3811        if (userId == UserHandle.getUserId(callingUid)) return;
3812        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3813            if (requireFullPermission) {
3814                mContext.enforceCallingOrSelfPermission(
3815                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3816            } else {
3817                try {
3818                    mContext.enforceCallingOrSelfPermission(
3819                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3820                } catch (SecurityException se) {
3821                    mContext.enforceCallingOrSelfPermission(
3822                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3823                }
3824            }
3825        }
3826    }
3827
3828    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3829        if (callingUid == Process.SHELL_UID) {
3830            if (userHandle >= 0
3831                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3832                throw new SecurityException("Shell does not have permission to access user "
3833                        + userHandle);
3834            } else if (userHandle < 0) {
3835                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3836                        + Debug.getCallers(3));
3837            }
3838        }
3839    }
3840
3841    private BasePermission findPermissionTreeLP(String permName) {
3842        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3843            if (permName.startsWith(bp.name) &&
3844                    permName.length() > bp.name.length() &&
3845                    permName.charAt(bp.name.length()) == '.') {
3846                return bp;
3847            }
3848        }
3849        return null;
3850    }
3851
3852    private BasePermission checkPermissionTreeLP(String permName) {
3853        if (permName != null) {
3854            BasePermission bp = findPermissionTreeLP(permName);
3855            if (bp != null) {
3856                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3857                    return bp;
3858                }
3859                throw new SecurityException("Calling uid "
3860                        + Binder.getCallingUid()
3861                        + " is not allowed to add to permission tree "
3862                        + bp.name + " owned by uid " + bp.uid);
3863            }
3864        }
3865        throw new SecurityException("No permission tree found for " + permName);
3866    }
3867
3868    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3869        if (s1 == null) {
3870            return s2 == null;
3871        }
3872        if (s2 == null) {
3873            return false;
3874        }
3875        if (s1.getClass() != s2.getClass()) {
3876            return false;
3877        }
3878        return s1.equals(s2);
3879    }
3880
3881    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3882        if (pi1.icon != pi2.icon) return false;
3883        if (pi1.logo != pi2.logo) return false;
3884        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3885        if (!compareStrings(pi1.name, pi2.name)) return false;
3886        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3887        // We'll take care of setting this one.
3888        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3889        // These are not currently stored in settings.
3890        //if (!compareStrings(pi1.group, pi2.group)) return false;
3891        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3892        //if (pi1.labelRes != pi2.labelRes) return false;
3893        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3894        return true;
3895    }
3896
3897    int permissionInfoFootprint(PermissionInfo info) {
3898        int size = info.name.length();
3899        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3900        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3901        return size;
3902    }
3903
3904    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3905        int size = 0;
3906        for (BasePermission perm : mSettings.mPermissions.values()) {
3907            if (perm.uid == tree.uid) {
3908                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3909            }
3910        }
3911        return size;
3912    }
3913
3914    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3915        // We calculate the max size of permissions defined by this uid and throw
3916        // if that plus the size of 'info' would exceed our stated maximum.
3917        if (tree.uid != Process.SYSTEM_UID) {
3918            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3919            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3920                throw new SecurityException("Permission tree size cap exceeded");
3921            }
3922        }
3923    }
3924
3925    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3926        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3927            throw new SecurityException("Label must be specified in permission");
3928        }
3929        BasePermission tree = checkPermissionTreeLP(info.name);
3930        BasePermission bp = mSettings.mPermissions.get(info.name);
3931        boolean added = bp == null;
3932        boolean changed = true;
3933        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3934        if (added) {
3935            enforcePermissionCapLocked(info, tree);
3936            bp = new BasePermission(info.name, tree.sourcePackage,
3937                    BasePermission.TYPE_DYNAMIC);
3938        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3939            throw new SecurityException(
3940                    "Not allowed to modify non-dynamic permission "
3941                    + info.name);
3942        } else {
3943            if (bp.protectionLevel == fixedLevel
3944                    && bp.perm.owner.equals(tree.perm.owner)
3945                    && bp.uid == tree.uid
3946                    && comparePermissionInfos(bp.perm.info, info)) {
3947                changed = false;
3948            }
3949        }
3950        bp.protectionLevel = fixedLevel;
3951        info = new PermissionInfo(info);
3952        info.protectionLevel = fixedLevel;
3953        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3954        bp.perm.info.packageName = tree.perm.info.packageName;
3955        bp.uid = tree.uid;
3956        if (added) {
3957            mSettings.mPermissions.put(info.name, bp);
3958        }
3959        if (changed) {
3960            if (!async) {
3961                mSettings.writeLPr();
3962            } else {
3963                scheduleWriteSettingsLocked();
3964            }
3965        }
3966        return added;
3967    }
3968
3969    @Override
3970    public boolean addPermission(PermissionInfo info) {
3971        synchronized (mPackages) {
3972            return addPermissionLocked(info, false);
3973        }
3974    }
3975
3976    @Override
3977    public boolean addPermissionAsync(PermissionInfo info) {
3978        synchronized (mPackages) {
3979            return addPermissionLocked(info, true);
3980        }
3981    }
3982
3983    @Override
3984    public void removePermission(String name) {
3985        synchronized (mPackages) {
3986            checkPermissionTreeLP(name);
3987            BasePermission bp = mSettings.mPermissions.get(name);
3988            if (bp != null) {
3989                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3990                    throw new SecurityException(
3991                            "Not allowed to modify non-dynamic permission "
3992                            + name);
3993                }
3994                mSettings.mPermissions.remove(name);
3995                mSettings.writeLPr();
3996            }
3997        }
3998    }
3999
4000    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4001            BasePermission bp) {
4002        int index = pkg.requestedPermissions.indexOf(bp.name);
4003        if (index == -1) {
4004            throw new SecurityException("Package " + pkg.packageName
4005                    + " has not requested permission " + bp.name);
4006        }
4007        if (!bp.isRuntime() && !bp.isDevelopment()) {
4008            throw new SecurityException("Permission " + bp.name
4009                    + " is not a changeable permission type");
4010        }
4011    }
4012
4013    @Override
4014    public void grantRuntimePermission(String packageName, String name, final int userId) {
4015        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4016    }
4017
4018    private void grantRuntimePermission(String packageName, String name, final int userId,
4019            boolean overridePolicy) {
4020        if (!sUserManager.exists(userId)) {
4021            Log.e(TAG, "No such user:" + userId);
4022            return;
4023        }
4024
4025        mContext.enforceCallingOrSelfPermission(
4026                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4027                "grantRuntimePermission");
4028
4029        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4030                true /* requireFullPermission */, true /* checkShell */,
4031                "grantRuntimePermission");
4032
4033        final int uid;
4034        final SettingBase sb;
4035
4036        synchronized (mPackages) {
4037            final PackageParser.Package pkg = mPackages.get(packageName);
4038            if (pkg == null) {
4039                throw new IllegalArgumentException("Unknown package: " + packageName);
4040            }
4041
4042            final BasePermission bp = mSettings.mPermissions.get(name);
4043            if (bp == null) {
4044                throw new IllegalArgumentException("Unknown permission: " + name);
4045            }
4046
4047            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4048
4049            // If a permission review is required for legacy apps we represent
4050            // their permissions as always granted runtime ones since we need
4051            // to keep the review required permission flag per user while an
4052            // install permission's state is shared across all users.
4053            if (mPermissionReviewRequired
4054                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4055                    && bp.isRuntime()) {
4056                return;
4057            }
4058
4059            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4060            sb = (SettingBase) pkg.mExtras;
4061            if (sb == null) {
4062                throw new IllegalArgumentException("Unknown package: " + packageName);
4063            }
4064
4065            final PermissionsState permissionsState = sb.getPermissionsState();
4066
4067            final int flags = permissionsState.getPermissionFlags(name, userId);
4068            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4069                throw new SecurityException("Cannot grant system fixed permission "
4070                        + name + " for package " + packageName);
4071            }
4072            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4073                throw new SecurityException("Cannot grant policy fixed permission "
4074                        + name + " for package " + packageName);
4075            }
4076
4077            if (bp.isDevelopment()) {
4078                // Development permissions must be handled specially, since they are not
4079                // normal runtime permissions.  For now they apply to all users.
4080                if (permissionsState.grantInstallPermission(bp) !=
4081                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4082                    scheduleWriteSettingsLocked();
4083                }
4084                return;
4085            }
4086
4087            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4088                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4089                return;
4090            }
4091
4092            final int result = permissionsState.grantRuntimePermission(bp, userId);
4093            switch (result) {
4094                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4095                    return;
4096                }
4097
4098                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4099                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4100                    mHandler.post(new Runnable() {
4101                        @Override
4102                        public void run() {
4103                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4104                        }
4105                    });
4106                }
4107                break;
4108            }
4109
4110            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4111
4112            // Not critical if that is lost - app has to request again.
4113            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4114        }
4115
4116        // Only need to do this if user is initialized. Otherwise it's a new user
4117        // and there are no processes running as the user yet and there's no need
4118        // to make an expensive call to remount processes for the changed permissions.
4119        if (READ_EXTERNAL_STORAGE.equals(name)
4120                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4121            final long token = Binder.clearCallingIdentity();
4122            try {
4123                if (sUserManager.isInitialized(userId)) {
4124                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4125                            MountServiceInternal.class);
4126                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4127                }
4128            } finally {
4129                Binder.restoreCallingIdentity(token);
4130            }
4131        }
4132    }
4133
4134    @Override
4135    public void revokeRuntimePermission(String packageName, String name, int userId) {
4136        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4137    }
4138
4139    private void revokeRuntimePermission(String packageName, String name, int userId,
4140            boolean overridePolicy) {
4141        if (!sUserManager.exists(userId)) {
4142            Log.e(TAG, "No such user:" + userId);
4143            return;
4144        }
4145
4146        mContext.enforceCallingOrSelfPermission(
4147                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4148                "revokeRuntimePermission");
4149
4150        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4151                true /* requireFullPermission */, true /* checkShell */,
4152                "revokeRuntimePermission");
4153
4154        final int appId;
4155
4156        synchronized (mPackages) {
4157            final PackageParser.Package pkg = mPackages.get(packageName);
4158            if (pkg == null) {
4159                throw new IllegalArgumentException("Unknown package: " + packageName);
4160            }
4161
4162            final BasePermission bp = mSettings.mPermissions.get(name);
4163            if (bp == null) {
4164                throw new IllegalArgumentException("Unknown permission: " + name);
4165            }
4166
4167            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4168
4169            // If a permission review is required for legacy apps we represent
4170            // their permissions as always granted runtime ones since we need
4171            // to keep the review required permission flag per user while an
4172            // install permission's state is shared across all users.
4173            if (mPermissionReviewRequired
4174                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4175                    && bp.isRuntime()) {
4176                return;
4177            }
4178
4179            SettingBase sb = (SettingBase) pkg.mExtras;
4180            if (sb == null) {
4181                throw new IllegalArgumentException("Unknown package: " + packageName);
4182            }
4183
4184            final PermissionsState permissionsState = sb.getPermissionsState();
4185
4186            final int flags = permissionsState.getPermissionFlags(name, userId);
4187            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4188                throw new SecurityException("Cannot revoke system fixed permission "
4189                        + name + " for package " + packageName);
4190            }
4191            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4192                throw new SecurityException("Cannot revoke policy fixed permission "
4193                        + name + " for package " + packageName);
4194            }
4195
4196            if (bp.isDevelopment()) {
4197                // Development permissions must be handled specially, since they are not
4198                // normal runtime permissions.  For now they apply to all users.
4199                if (permissionsState.revokeInstallPermission(bp) !=
4200                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4201                    scheduleWriteSettingsLocked();
4202                }
4203                return;
4204            }
4205
4206            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4207                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4208                return;
4209            }
4210
4211            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4212
4213            // Critical, after this call app should never have the permission.
4214            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4215
4216            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4217        }
4218
4219        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4220    }
4221
4222    @Override
4223    public void resetRuntimePermissions() {
4224        mContext.enforceCallingOrSelfPermission(
4225                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4226                "revokeRuntimePermission");
4227
4228        int callingUid = Binder.getCallingUid();
4229        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4230            mContext.enforceCallingOrSelfPermission(
4231                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4232                    "resetRuntimePermissions");
4233        }
4234
4235        synchronized (mPackages) {
4236            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4237            for (int userId : UserManagerService.getInstance().getUserIds()) {
4238                final int packageCount = mPackages.size();
4239                for (int i = 0; i < packageCount; i++) {
4240                    PackageParser.Package pkg = mPackages.valueAt(i);
4241                    if (!(pkg.mExtras instanceof PackageSetting)) {
4242                        continue;
4243                    }
4244                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4245                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4246                }
4247            }
4248        }
4249    }
4250
4251    @Override
4252    public int getPermissionFlags(String name, String packageName, int userId) {
4253        if (!sUserManager.exists(userId)) {
4254            return 0;
4255        }
4256
4257        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4258
4259        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4260                true /* requireFullPermission */, false /* checkShell */,
4261                "getPermissionFlags");
4262
4263        synchronized (mPackages) {
4264            final PackageParser.Package pkg = mPackages.get(packageName);
4265            if (pkg == null) {
4266                return 0;
4267            }
4268
4269            final BasePermission bp = mSettings.mPermissions.get(name);
4270            if (bp == null) {
4271                return 0;
4272            }
4273
4274            SettingBase sb = (SettingBase) pkg.mExtras;
4275            if (sb == null) {
4276                return 0;
4277            }
4278
4279            PermissionsState permissionsState = sb.getPermissionsState();
4280            return permissionsState.getPermissionFlags(name, userId);
4281        }
4282    }
4283
4284    @Override
4285    public void updatePermissionFlags(String name, String packageName, int flagMask,
4286            int flagValues, int userId) {
4287        if (!sUserManager.exists(userId)) {
4288            return;
4289        }
4290
4291        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4292
4293        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4294                true /* requireFullPermission */, true /* checkShell */,
4295                "updatePermissionFlags");
4296
4297        // Only the system can change these flags and nothing else.
4298        if (getCallingUid() != Process.SYSTEM_UID) {
4299            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4300            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4301            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4302            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4303            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4304        }
4305
4306        synchronized (mPackages) {
4307            final PackageParser.Package pkg = mPackages.get(packageName);
4308            if (pkg == null) {
4309                throw new IllegalArgumentException("Unknown package: " + packageName);
4310            }
4311
4312            final BasePermission bp = mSettings.mPermissions.get(name);
4313            if (bp == null) {
4314                throw new IllegalArgumentException("Unknown permission: " + name);
4315            }
4316
4317            SettingBase sb = (SettingBase) pkg.mExtras;
4318            if (sb == null) {
4319                throw new IllegalArgumentException("Unknown package: " + packageName);
4320            }
4321
4322            PermissionsState permissionsState = sb.getPermissionsState();
4323
4324            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4325
4326            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4327                // Install and runtime permissions are stored in different places,
4328                // so figure out what permission changed and persist the change.
4329                if (permissionsState.getInstallPermissionState(name) != null) {
4330                    scheduleWriteSettingsLocked();
4331                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4332                        || hadState) {
4333                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4334                }
4335            }
4336        }
4337    }
4338
4339    /**
4340     * Update the permission flags for all packages and runtime permissions of a user in order
4341     * to allow device or profile owner to remove POLICY_FIXED.
4342     */
4343    @Override
4344    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4345        if (!sUserManager.exists(userId)) {
4346            return;
4347        }
4348
4349        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4350
4351        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4352                true /* requireFullPermission */, true /* checkShell */,
4353                "updatePermissionFlagsForAllApps");
4354
4355        // Only the system can change system fixed flags.
4356        if (getCallingUid() != Process.SYSTEM_UID) {
4357            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4358            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4359        }
4360
4361        synchronized (mPackages) {
4362            boolean changed = false;
4363            final int packageCount = mPackages.size();
4364            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4365                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4366                SettingBase sb = (SettingBase) pkg.mExtras;
4367                if (sb == null) {
4368                    continue;
4369                }
4370                PermissionsState permissionsState = sb.getPermissionsState();
4371                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4372                        userId, flagMask, flagValues);
4373            }
4374            if (changed) {
4375                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4376            }
4377        }
4378    }
4379
4380    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4381        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4382                != PackageManager.PERMISSION_GRANTED
4383            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4384                != PackageManager.PERMISSION_GRANTED) {
4385            throw new SecurityException(message + " requires "
4386                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4387                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4388        }
4389    }
4390
4391    @Override
4392    public boolean shouldShowRequestPermissionRationale(String permissionName,
4393            String packageName, int userId) {
4394        if (UserHandle.getCallingUserId() != userId) {
4395            mContext.enforceCallingPermission(
4396                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4397                    "canShowRequestPermissionRationale for user " + userId);
4398        }
4399
4400        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4401        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4402            return false;
4403        }
4404
4405        if (checkPermission(permissionName, packageName, userId)
4406                == PackageManager.PERMISSION_GRANTED) {
4407            return false;
4408        }
4409
4410        final int flags;
4411
4412        final long identity = Binder.clearCallingIdentity();
4413        try {
4414            flags = getPermissionFlags(permissionName,
4415                    packageName, userId);
4416        } finally {
4417            Binder.restoreCallingIdentity(identity);
4418        }
4419
4420        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4421                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4422                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4423
4424        if ((flags & fixedFlags) != 0) {
4425            return false;
4426        }
4427
4428        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4429    }
4430
4431    @Override
4432    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4433        mContext.enforceCallingOrSelfPermission(
4434                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4435                "addOnPermissionsChangeListener");
4436
4437        synchronized (mPackages) {
4438            mOnPermissionChangeListeners.addListenerLocked(listener);
4439        }
4440    }
4441
4442    @Override
4443    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4444        synchronized (mPackages) {
4445            mOnPermissionChangeListeners.removeListenerLocked(listener);
4446        }
4447    }
4448
4449    @Override
4450    public boolean isProtectedBroadcast(String actionName) {
4451        synchronized (mPackages) {
4452            if (mProtectedBroadcasts.contains(actionName)) {
4453                return true;
4454            } else if (actionName != null) {
4455                // TODO: remove these terrible hacks
4456                if (actionName.startsWith("android.net.netmon.lingerExpired")
4457                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4458                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4459                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4460                    return true;
4461                }
4462            }
4463        }
4464        return false;
4465    }
4466
4467    @Override
4468    public int checkSignatures(String pkg1, String pkg2) {
4469        synchronized (mPackages) {
4470            final PackageParser.Package p1 = mPackages.get(pkg1);
4471            final PackageParser.Package p2 = mPackages.get(pkg2);
4472            if (p1 == null || p1.mExtras == null
4473                    || p2 == null || p2.mExtras == null) {
4474                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4475            }
4476            return compareSignatures(p1.mSignatures, p2.mSignatures);
4477        }
4478    }
4479
4480    @Override
4481    public int checkUidSignatures(int uid1, int uid2) {
4482        // Map to base uids.
4483        uid1 = UserHandle.getAppId(uid1);
4484        uid2 = UserHandle.getAppId(uid2);
4485        // reader
4486        synchronized (mPackages) {
4487            Signature[] s1;
4488            Signature[] s2;
4489            Object obj = mSettings.getUserIdLPr(uid1);
4490            if (obj != null) {
4491                if (obj instanceof SharedUserSetting) {
4492                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4493                } else if (obj instanceof PackageSetting) {
4494                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4495                } else {
4496                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4497                }
4498            } else {
4499                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4500            }
4501            obj = mSettings.getUserIdLPr(uid2);
4502            if (obj != null) {
4503                if (obj instanceof SharedUserSetting) {
4504                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4505                } else if (obj instanceof PackageSetting) {
4506                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4507                } else {
4508                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4509                }
4510            } else {
4511                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4512            }
4513            return compareSignatures(s1, s2);
4514        }
4515    }
4516
4517    /**
4518     * This method should typically only be used when granting or revoking
4519     * permissions, since the app may immediately restart after this call.
4520     * <p>
4521     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4522     * guard your work against the app being relaunched.
4523     */
4524    private void killUid(int appId, int userId, String reason) {
4525        final long identity = Binder.clearCallingIdentity();
4526        try {
4527            IActivityManager am = ActivityManagerNative.getDefault();
4528            if (am != null) {
4529                try {
4530                    am.killUid(appId, userId, reason);
4531                } catch (RemoteException e) {
4532                    /* ignore - same process */
4533                }
4534            }
4535        } finally {
4536            Binder.restoreCallingIdentity(identity);
4537        }
4538    }
4539
4540    /**
4541     * Compares two sets of signatures. Returns:
4542     * <br />
4543     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4544     * <br />
4545     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4546     * <br />
4547     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4548     * <br />
4549     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4550     * <br />
4551     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4552     */
4553    static int compareSignatures(Signature[] s1, Signature[] s2) {
4554        if (s1 == null) {
4555            return s2 == null
4556                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4557                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4558        }
4559
4560        if (s2 == null) {
4561            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4562        }
4563
4564        if (s1.length != s2.length) {
4565            return PackageManager.SIGNATURE_NO_MATCH;
4566        }
4567
4568        // Since both signature sets are of size 1, we can compare without HashSets.
4569        if (s1.length == 1) {
4570            return s1[0].equals(s2[0]) ?
4571                    PackageManager.SIGNATURE_MATCH :
4572                    PackageManager.SIGNATURE_NO_MATCH;
4573        }
4574
4575        ArraySet<Signature> set1 = new ArraySet<Signature>();
4576        for (Signature sig : s1) {
4577            set1.add(sig);
4578        }
4579        ArraySet<Signature> set2 = new ArraySet<Signature>();
4580        for (Signature sig : s2) {
4581            set2.add(sig);
4582        }
4583        // Make sure s2 contains all signatures in s1.
4584        if (set1.equals(set2)) {
4585            return PackageManager.SIGNATURE_MATCH;
4586        }
4587        return PackageManager.SIGNATURE_NO_MATCH;
4588    }
4589
4590    /**
4591     * If the database version for this type of package (internal storage or
4592     * external storage) is less than the version where package signatures
4593     * were updated, return true.
4594     */
4595    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4596        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4597        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4598    }
4599
4600    /**
4601     * Used for backward compatibility to make sure any packages with
4602     * certificate chains get upgraded to the new style. {@code existingSigs}
4603     * will be in the old format (since they were stored on disk from before the
4604     * system upgrade) and {@code scannedSigs} will be in the newer format.
4605     */
4606    private int compareSignaturesCompat(PackageSignatures existingSigs,
4607            PackageParser.Package scannedPkg) {
4608        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4609            return PackageManager.SIGNATURE_NO_MATCH;
4610        }
4611
4612        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4613        for (Signature sig : existingSigs.mSignatures) {
4614            existingSet.add(sig);
4615        }
4616        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4617        for (Signature sig : scannedPkg.mSignatures) {
4618            try {
4619                Signature[] chainSignatures = sig.getChainSignatures();
4620                for (Signature chainSig : chainSignatures) {
4621                    scannedCompatSet.add(chainSig);
4622                }
4623            } catch (CertificateEncodingException e) {
4624                scannedCompatSet.add(sig);
4625            }
4626        }
4627        /*
4628         * Make sure the expanded scanned set contains all signatures in the
4629         * existing one.
4630         */
4631        if (scannedCompatSet.equals(existingSet)) {
4632            // Migrate the old signatures to the new scheme.
4633            existingSigs.assignSignatures(scannedPkg.mSignatures);
4634            // The new KeySets will be re-added later in the scanning process.
4635            synchronized (mPackages) {
4636                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4637            }
4638            return PackageManager.SIGNATURE_MATCH;
4639        }
4640        return PackageManager.SIGNATURE_NO_MATCH;
4641    }
4642
4643    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4644        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4645        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4646    }
4647
4648    private int compareSignaturesRecover(PackageSignatures existingSigs,
4649            PackageParser.Package scannedPkg) {
4650        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4651            return PackageManager.SIGNATURE_NO_MATCH;
4652        }
4653
4654        String msg = null;
4655        try {
4656            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4657                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4658                        + scannedPkg.packageName);
4659                return PackageManager.SIGNATURE_MATCH;
4660            }
4661        } catch (CertificateException e) {
4662            msg = e.getMessage();
4663        }
4664
4665        logCriticalInfo(Log.INFO,
4666                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4667        return PackageManager.SIGNATURE_NO_MATCH;
4668    }
4669
4670    @Override
4671    public List<String> getAllPackages() {
4672        synchronized (mPackages) {
4673            return new ArrayList<String>(mPackages.keySet());
4674        }
4675    }
4676
4677    @Override
4678    public String[] getPackagesForUid(int uid) {
4679        final int userId = UserHandle.getUserId(uid);
4680        uid = UserHandle.getAppId(uid);
4681        // reader
4682        synchronized (mPackages) {
4683            Object obj = mSettings.getUserIdLPr(uid);
4684            if (obj instanceof SharedUserSetting) {
4685                final SharedUserSetting sus = (SharedUserSetting) obj;
4686                final int N = sus.packages.size();
4687                String[] res = new String[N];
4688                final Iterator<PackageSetting> it = sus.packages.iterator();
4689                int i = 0;
4690                while (it.hasNext()) {
4691                    PackageSetting ps = it.next();
4692                    if (ps.getInstalled(userId)) {
4693                        res[i++] = ps.name;
4694                    } else {
4695                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4696                    }
4697                }
4698                return res;
4699            } else if (obj instanceof PackageSetting) {
4700                final PackageSetting ps = (PackageSetting) obj;
4701                return new String[] { ps.name };
4702            }
4703        }
4704        return null;
4705    }
4706
4707    @Override
4708    public String getNameForUid(int uid) {
4709        // reader
4710        synchronized (mPackages) {
4711            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4712            if (obj instanceof SharedUserSetting) {
4713                final SharedUserSetting sus = (SharedUserSetting) obj;
4714                return sus.name + ":" + sus.userId;
4715            } else if (obj instanceof PackageSetting) {
4716                final PackageSetting ps = (PackageSetting) obj;
4717                return ps.name;
4718            }
4719        }
4720        return null;
4721    }
4722
4723    @Override
4724    public int getUidForSharedUser(String sharedUserName) {
4725        if(sharedUserName == null) {
4726            return -1;
4727        }
4728        // reader
4729        synchronized (mPackages) {
4730            SharedUserSetting suid;
4731            try {
4732                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4733                if (suid != null) {
4734                    return suid.userId;
4735                }
4736            } catch (PackageManagerException ignore) {
4737                // can't happen, but, still need to catch it
4738            }
4739            return -1;
4740        }
4741    }
4742
4743    @Override
4744    public int getFlagsForUid(int uid) {
4745        synchronized (mPackages) {
4746            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4747            if (obj instanceof SharedUserSetting) {
4748                final SharedUserSetting sus = (SharedUserSetting) obj;
4749                return sus.pkgFlags;
4750            } else if (obj instanceof PackageSetting) {
4751                final PackageSetting ps = (PackageSetting) obj;
4752                return ps.pkgFlags;
4753            }
4754        }
4755        return 0;
4756    }
4757
4758    @Override
4759    public int getPrivateFlagsForUid(int uid) {
4760        synchronized (mPackages) {
4761            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4762            if (obj instanceof SharedUserSetting) {
4763                final SharedUserSetting sus = (SharedUserSetting) obj;
4764                return sus.pkgPrivateFlags;
4765            } else if (obj instanceof PackageSetting) {
4766                final PackageSetting ps = (PackageSetting) obj;
4767                return ps.pkgPrivateFlags;
4768            }
4769        }
4770        return 0;
4771    }
4772
4773    @Override
4774    public boolean isUidPrivileged(int uid) {
4775        uid = UserHandle.getAppId(uid);
4776        // reader
4777        synchronized (mPackages) {
4778            Object obj = mSettings.getUserIdLPr(uid);
4779            if (obj instanceof SharedUserSetting) {
4780                final SharedUserSetting sus = (SharedUserSetting) obj;
4781                final Iterator<PackageSetting> it = sus.packages.iterator();
4782                while (it.hasNext()) {
4783                    if (it.next().isPrivileged()) {
4784                        return true;
4785                    }
4786                }
4787            } else if (obj instanceof PackageSetting) {
4788                final PackageSetting ps = (PackageSetting) obj;
4789                return ps.isPrivileged();
4790            }
4791        }
4792        return false;
4793    }
4794
4795    @Override
4796    public String[] getAppOpPermissionPackages(String permissionName) {
4797        synchronized (mPackages) {
4798            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4799            if (pkgs == null) {
4800                return null;
4801            }
4802            return pkgs.toArray(new String[pkgs.size()]);
4803        }
4804    }
4805
4806    @Override
4807    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4808            int flags, int userId) {
4809        try {
4810            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4811
4812            if (!sUserManager.exists(userId)) return null;
4813            flags = updateFlagsForResolve(flags, userId, intent);
4814            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4815                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4816
4817            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4818            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4819                    flags, userId);
4820            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4821
4822            final ResolveInfo bestChoice =
4823                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4824            return bestChoice;
4825        } finally {
4826            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4827        }
4828    }
4829
4830    @Override
4831    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4832            IntentFilter filter, int match, ComponentName activity) {
4833        final int userId = UserHandle.getCallingUserId();
4834        if (DEBUG_PREFERRED) {
4835            Log.v(TAG, "setLastChosenActivity intent=" + intent
4836                + " resolvedType=" + resolvedType
4837                + " flags=" + flags
4838                + " filter=" + filter
4839                + " match=" + match
4840                + " activity=" + activity);
4841            filter.dump(new PrintStreamPrinter(System.out), "    ");
4842        }
4843        intent.setComponent(null);
4844        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4845                userId);
4846        // Find any earlier preferred or last chosen entries and nuke them
4847        findPreferredActivity(intent, resolvedType,
4848                flags, query, 0, false, true, false, userId);
4849        // Add the new activity as the last chosen for this filter
4850        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4851                "Setting last chosen");
4852    }
4853
4854    @Override
4855    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4856        final int userId = UserHandle.getCallingUserId();
4857        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4858        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4859                userId);
4860        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4861                false, false, false, userId);
4862    }
4863
4864    private boolean isEphemeralDisabled() {
4865        // ephemeral apps have been disabled across the board
4866        if (DISABLE_EPHEMERAL_APPS) {
4867            return true;
4868        }
4869        // system isn't up yet; can't read settings, so, assume no ephemeral apps
4870        if (!mSystemReady) {
4871            return true;
4872        }
4873        // we can't get a content resolver until the system is ready; these checks must happen last
4874        final ContentResolver resolver = mContext.getContentResolver();
4875        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4876            return true;
4877        }
4878        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4879    }
4880
4881    private boolean isEphemeralAllowed(
4882            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4883            boolean skipPackageCheck) {
4884        // Short circuit and return early if possible.
4885        if (isEphemeralDisabled()) {
4886            return false;
4887        }
4888        final int callingUser = UserHandle.getCallingUserId();
4889        if (callingUser != UserHandle.USER_SYSTEM) {
4890            return false;
4891        }
4892        if (mEphemeralResolverConnection == null) {
4893            return false;
4894        }
4895        if (intent.getComponent() != null) {
4896            return false;
4897        }
4898        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4899            return false;
4900        }
4901        if (!skipPackageCheck && intent.getPackage() != null) {
4902            return false;
4903        }
4904        final boolean isWebUri = hasWebURI(intent);
4905        if (!isWebUri || intent.getData().getHost() == null) {
4906            return false;
4907        }
4908        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4909        synchronized (mPackages) {
4910            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4911            for (int n = 0; n < count; n++) {
4912                ResolveInfo info = resolvedActivities.get(n);
4913                String packageName = info.activityInfo.packageName;
4914                PackageSetting ps = mSettings.mPackages.get(packageName);
4915                if (ps != null) {
4916                    // Try to get the status from User settings first
4917                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4918                    int status = (int) (packedStatus >> 32);
4919                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4920                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4921                        if (DEBUG_EPHEMERAL) {
4922                            Slog.v(TAG, "DENY ephemeral apps;"
4923                                + " pkg: " + packageName + ", status: " + status);
4924                        }
4925                        return false;
4926                    }
4927                }
4928            }
4929        }
4930        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4931        return true;
4932    }
4933
4934    private static EphemeralResolveInfo getEphemeralResolveInfo(
4935            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4936            String resolvedType, int userId, String packageName) {
4937        final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4938                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4939        final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4940                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4941        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4942                ephemeralPrefixCount);
4943        final int[] shaPrefix = digest.getDigestPrefix();
4944        final byte[][] digestBytes = digest.getDigestBytes();
4945        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4946                resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4947        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4948            // No hash prefix match; there are no ephemeral apps for this domain.
4949            return null;
4950        }
4951
4952        // Go in reverse order so we match the narrowest scope first.
4953        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4954            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4955                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4956                    continue;
4957                }
4958                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4959                // No filters; this should never happen.
4960                if (filters.isEmpty()) {
4961                    continue;
4962                }
4963                if (packageName != null
4964                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4965                    continue;
4966                }
4967                // We have a domain match; resolve the filters to see if anything matches.
4968                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4969                for (int j = filters.size() - 1; j >= 0; --j) {
4970                    final EphemeralResolveIntentInfo intentInfo =
4971                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4972                    ephemeralResolver.addFilter(intentInfo);
4973                }
4974                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4975                        intent, resolvedType, false /*defaultOnly*/, userId);
4976                if (!matchedResolveInfoList.isEmpty()) {
4977                    return matchedResolveInfoList.get(0);
4978                }
4979            }
4980        }
4981        // Hash or filter mis-match; no ephemeral apps for this domain.
4982        return null;
4983    }
4984
4985    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4986            int flags, List<ResolveInfo> query, int userId) {
4987        if (query != null) {
4988            final int N = query.size();
4989            if (N == 1) {
4990                return query.get(0);
4991            } else if (N > 1) {
4992                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4993                // If there is more than one activity with the same priority,
4994                // then let the user decide between them.
4995                ResolveInfo r0 = query.get(0);
4996                ResolveInfo r1 = query.get(1);
4997                if (DEBUG_INTENT_MATCHING || debug) {
4998                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4999                            + r1.activityInfo.name + "=" + r1.priority);
5000                }
5001                // If the first activity has a higher priority, or a different
5002                // default, then it is always desirable to pick it.
5003                if (r0.priority != r1.priority
5004                        || r0.preferredOrder != r1.preferredOrder
5005                        || r0.isDefault != r1.isDefault) {
5006                    return query.get(0);
5007                }
5008                // If we have saved a preference for a preferred activity for
5009                // this Intent, use that.
5010                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5011                        flags, query, r0.priority, true, false, debug, userId);
5012                if (ri != null) {
5013                    return ri;
5014                }
5015                ri = new ResolveInfo(mResolveInfo);
5016                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5017                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5018                // If all of the options come from the same package, show the application's
5019                // label and icon instead of the generic resolver's.
5020                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5021                // and then throw away the ResolveInfo itself, meaning that the caller loses
5022                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5023                // a fallback for this case; we only set the target package's resources on
5024                // the ResolveInfo, not the ActivityInfo.
5025                final String intentPackage = intent.getPackage();
5026                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5027                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5028                    ri.resolvePackageName = intentPackage;
5029                    if (userNeedsBadging(userId)) {
5030                        ri.noResourceId = true;
5031                    } else {
5032                        ri.icon = appi.icon;
5033                    }
5034                    ri.iconResourceId = appi.icon;
5035                    ri.labelRes = appi.labelRes;
5036                }
5037                ri.activityInfo.applicationInfo = new ApplicationInfo(
5038                        ri.activityInfo.applicationInfo);
5039                if (userId != 0) {
5040                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5041                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5042                }
5043                // Make sure that the resolver is displayable in car mode
5044                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5045                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5046                return ri;
5047            }
5048        }
5049        return null;
5050    }
5051
5052    /**
5053     * Return true if the given list is not empty and all of its contents have
5054     * an activityInfo with the given package name.
5055     */
5056    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5057        if (ArrayUtils.isEmpty(list)) {
5058            return false;
5059        }
5060        for (int i = 0, N = list.size(); i < N; i++) {
5061            final ResolveInfo ri = list.get(i);
5062            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5063            if (ai == null || !packageName.equals(ai.packageName)) {
5064                return false;
5065            }
5066        }
5067        return true;
5068    }
5069
5070    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5071            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5072        final int N = query.size();
5073        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5074                .get(userId);
5075        // Get the list of persistent preferred activities that handle the intent
5076        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5077        List<PersistentPreferredActivity> pprefs = ppir != null
5078                ? ppir.queryIntent(intent, resolvedType,
5079                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5080                : null;
5081        if (pprefs != null && pprefs.size() > 0) {
5082            final int M = pprefs.size();
5083            for (int i=0; i<M; i++) {
5084                final PersistentPreferredActivity ppa = pprefs.get(i);
5085                if (DEBUG_PREFERRED || debug) {
5086                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5087                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5088                            + "\n  component=" + ppa.mComponent);
5089                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5090                }
5091                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5092                        flags | MATCH_DISABLED_COMPONENTS, userId);
5093                if (DEBUG_PREFERRED || debug) {
5094                    Slog.v(TAG, "Found persistent preferred activity:");
5095                    if (ai != null) {
5096                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5097                    } else {
5098                        Slog.v(TAG, "  null");
5099                    }
5100                }
5101                if (ai == null) {
5102                    // This previously registered persistent preferred activity
5103                    // component is no longer known. Ignore it and do NOT remove it.
5104                    continue;
5105                }
5106                for (int j=0; j<N; j++) {
5107                    final ResolveInfo ri = query.get(j);
5108                    if (!ri.activityInfo.applicationInfo.packageName
5109                            .equals(ai.applicationInfo.packageName)) {
5110                        continue;
5111                    }
5112                    if (!ri.activityInfo.name.equals(ai.name)) {
5113                        continue;
5114                    }
5115                    //  Found a persistent preference that can handle the intent.
5116                    if (DEBUG_PREFERRED || debug) {
5117                        Slog.v(TAG, "Returning persistent preferred activity: " +
5118                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5119                    }
5120                    return ri;
5121                }
5122            }
5123        }
5124        return null;
5125    }
5126
5127    // TODO: handle preferred activities missing while user has amnesia
5128    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5129            List<ResolveInfo> query, int priority, boolean always,
5130            boolean removeMatches, boolean debug, int userId) {
5131        if (!sUserManager.exists(userId)) return null;
5132        flags = updateFlagsForResolve(flags, userId, intent);
5133        // writer
5134        synchronized (mPackages) {
5135            if (intent.getSelector() != null) {
5136                intent = intent.getSelector();
5137            }
5138            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5139
5140            // Try to find a matching persistent preferred activity.
5141            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5142                    debug, userId);
5143
5144            // If a persistent preferred activity matched, use it.
5145            if (pri != null) {
5146                return pri;
5147            }
5148
5149            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5150            // Get the list of preferred activities that handle the intent
5151            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5152            List<PreferredActivity> prefs = pir != null
5153                    ? pir.queryIntent(intent, resolvedType,
5154                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5155                    : null;
5156            if (prefs != null && prefs.size() > 0) {
5157                boolean changed = false;
5158                try {
5159                    // First figure out how good the original match set is.
5160                    // We will only allow preferred activities that came
5161                    // from the same match quality.
5162                    int match = 0;
5163
5164                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5165
5166                    final int N = query.size();
5167                    for (int j=0; j<N; j++) {
5168                        final ResolveInfo ri = query.get(j);
5169                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5170                                + ": 0x" + Integer.toHexString(match));
5171                        if (ri.match > match) {
5172                            match = ri.match;
5173                        }
5174                    }
5175
5176                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5177                            + Integer.toHexString(match));
5178
5179                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5180                    final int M = prefs.size();
5181                    for (int i=0; i<M; i++) {
5182                        final PreferredActivity pa = prefs.get(i);
5183                        if (DEBUG_PREFERRED || debug) {
5184                            Slog.v(TAG, "Checking PreferredActivity ds="
5185                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5186                                    + "\n  component=" + pa.mPref.mComponent);
5187                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5188                        }
5189                        if (pa.mPref.mMatch != match) {
5190                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5191                                    + Integer.toHexString(pa.mPref.mMatch));
5192                            continue;
5193                        }
5194                        // If it's not an "always" type preferred activity and that's what we're
5195                        // looking for, skip it.
5196                        if (always && !pa.mPref.mAlways) {
5197                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5198                            continue;
5199                        }
5200                        final ActivityInfo ai = getActivityInfo(
5201                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5202                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5203                                userId);
5204                        if (DEBUG_PREFERRED || debug) {
5205                            Slog.v(TAG, "Found preferred activity:");
5206                            if (ai != null) {
5207                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5208                            } else {
5209                                Slog.v(TAG, "  null");
5210                            }
5211                        }
5212                        if (ai == null) {
5213                            // This previously registered preferred activity
5214                            // component is no longer known.  Most likely an update
5215                            // to the app was installed and in the new version this
5216                            // component no longer exists.  Clean it up by removing
5217                            // it from the preferred activities list, and skip it.
5218                            Slog.w(TAG, "Removing dangling preferred activity: "
5219                                    + pa.mPref.mComponent);
5220                            pir.removeFilter(pa);
5221                            changed = true;
5222                            continue;
5223                        }
5224                        for (int j=0; j<N; j++) {
5225                            final ResolveInfo ri = query.get(j);
5226                            if (!ri.activityInfo.applicationInfo.packageName
5227                                    .equals(ai.applicationInfo.packageName)) {
5228                                continue;
5229                            }
5230                            if (!ri.activityInfo.name.equals(ai.name)) {
5231                                continue;
5232                            }
5233
5234                            if (removeMatches) {
5235                                pir.removeFilter(pa);
5236                                changed = true;
5237                                if (DEBUG_PREFERRED) {
5238                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5239                                }
5240                                break;
5241                            }
5242
5243                            // Okay we found a previously set preferred or last chosen app.
5244                            // If the result set is different from when this
5245                            // was created, we need to clear it and re-ask the
5246                            // user their preference, if we're looking for an "always" type entry.
5247                            if (always && !pa.mPref.sameSet(query)) {
5248                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5249                                        + intent + " type " + resolvedType);
5250                                if (DEBUG_PREFERRED) {
5251                                    Slog.v(TAG, "Removing preferred activity since set changed "
5252                                            + pa.mPref.mComponent);
5253                                }
5254                                pir.removeFilter(pa);
5255                                // Re-add the filter as a "last chosen" entry (!always)
5256                                PreferredActivity lastChosen = new PreferredActivity(
5257                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5258                                pir.addFilter(lastChosen);
5259                                changed = true;
5260                                return null;
5261                            }
5262
5263                            // Yay! Either the set matched or we're looking for the last chosen
5264                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5265                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5266                            return ri;
5267                        }
5268                    }
5269                } finally {
5270                    if (changed) {
5271                        if (DEBUG_PREFERRED) {
5272                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5273                        }
5274                        scheduleWritePackageRestrictionsLocked(userId);
5275                    }
5276                }
5277            }
5278        }
5279        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5280        return null;
5281    }
5282
5283    /*
5284     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5285     */
5286    @Override
5287    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5288            int targetUserId) {
5289        mContext.enforceCallingOrSelfPermission(
5290                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5291        List<CrossProfileIntentFilter> matches =
5292                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5293        if (matches != null) {
5294            int size = matches.size();
5295            for (int i = 0; i < size; i++) {
5296                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5297            }
5298        }
5299        if (hasWebURI(intent)) {
5300            // cross-profile app linking works only towards the parent.
5301            final UserInfo parent = getProfileParent(sourceUserId);
5302            synchronized(mPackages) {
5303                int flags = updateFlagsForResolve(0, parent.id, intent);
5304                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5305                        intent, resolvedType, flags, sourceUserId, parent.id);
5306                return xpDomainInfo != null;
5307            }
5308        }
5309        return false;
5310    }
5311
5312    private UserInfo getProfileParent(int userId) {
5313        final long identity = Binder.clearCallingIdentity();
5314        try {
5315            return sUserManager.getProfileParent(userId);
5316        } finally {
5317            Binder.restoreCallingIdentity(identity);
5318        }
5319    }
5320
5321    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5322            String resolvedType, int userId) {
5323        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5324        if (resolver != null) {
5325            return resolver.queryIntent(intent, resolvedType, false, userId);
5326        }
5327        return null;
5328    }
5329
5330    @Override
5331    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5332            String resolvedType, int flags, int userId) {
5333        try {
5334            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5335
5336            return new ParceledListSlice<>(
5337                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5338        } finally {
5339            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5340        }
5341    }
5342
5343    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5344            String resolvedType, int flags, int userId) {
5345        if (!sUserManager.exists(userId)) return Collections.emptyList();
5346        flags = updateFlagsForResolve(flags, userId, intent);
5347        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5348                false /* requireFullPermission */, false /* checkShell */,
5349                "query intent activities");
5350        ComponentName comp = intent.getComponent();
5351        if (comp == null) {
5352            if (intent.getSelector() != null) {
5353                intent = intent.getSelector();
5354                comp = intent.getComponent();
5355            }
5356        }
5357
5358        if (comp != null) {
5359            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5360            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5361            if (ai != null) {
5362                final ResolveInfo ri = new ResolveInfo();
5363                ri.activityInfo = ai;
5364                list.add(ri);
5365            }
5366            return list;
5367        }
5368
5369        // reader
5370        boolean sortResult = false;
5371        boolean addEphemeral = false;
5372        boolean matchEphemeralPackage = false;
5373        List<ResolveInfo> result;
5374        final String pkgName = intent.getPackage();
5375        synchronized (mPackages) {
5376            if (pkgName == null) {
5377                List<CrossProfileIntentFilter> matchingFilters =
5378                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5379                // Check for results that need to skip the current profile.
5380                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5381                        resolvedType, flags, userId);
5382                if (xpResolveInfo != null) {
5383                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5384                    xpResult.add(xpResolveInfo);
5385                    return filterIfNotSystemUser(xpResult, userId);
5386                }
5387
5388                // Check for results in the current profile.
5389                result = filterIfNotSystemUser(mActivities.queryIntent(
5390                        intent, resolvedType, flags, userId), userId);
5391                addEphemeral =
5392                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5393
5394                // Check for cross profile results.
5395                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5396                xpResolveInfo = queryCrossProfileIntents(
5397                        matchingFilters, intent, resolvedType, flags, userId,
5398                        hasNonNegativePriorityResult);
5399                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5400                    boolean isVisibleToUser = filterIfNotSystemUser(
5401                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5402                    if (isVisibleToUser) {
5403                        result.add(xpResolveInfo);
5404                        sortResult = true;
5405                    }
5406                }
5407                if (hasWebURI(intent)) {
5408                    CrossProfileDomainInfo xpDomainInfo = null;
5409                    final UserInfo parent = getProfileParent(userId);
5410                    if (parent != null) {
5411                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5412                                flags, userId, parent.id);
5413                    }
5414                    if (xpDomainInfo != null) {
5415                        if (xpResolveInfo != null) {
5416                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5417                            // in the result.
5418                            result.remove(xpResolveInfo);
5419                        }
5420                        if (result.size() == 0 && !addEphemeral) {
5421                            result.add(xpDomainInfo.resolveInfo);
5422                            return result;
5423                        }
5424                    }
5425                    if (result.size() > 1 || addEphemeral) {
5426                        result = filterCandidatesWithDomainPreferredActivitiesLPr(
5427                                intent, flags, result, xpDomainInfo, userId);
5428                        sortResult = true;
5429                    }
5430                }
5431            } else {
5432                final PackageParser.Package pkg = mPackages.get(pkgName);
5433                if (pkg != null) {
5434                    result = filterIfNotSystemUser(
5435                            mActivities.queryIntentForPackage(
5436                                    intent, resolvedType, flags, pkg.activities, userId),
5437                            userId);
5438                } else {
5439                    // the caller wants to resolve for a particular package; however, there
5440                    // were no installed results, so, try to find an ephemeral result
5441                    addEphemeral = isEphemeralAllowed(
5442                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5443                    matchEphemeralPackage = true;
5444                    result = new ArrayList<ResolveInfo>();
5445                }
5446            }
5447        }
5448        if (addEphemeral) {
5449            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5450            final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5451                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5452                    matchEphemeralPackage ? pkgName : null);
5453            if (ai != null) {
5454                if (DEBUG_EPHEMERAL) {
5455                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5456                }
5457                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5458                ephemeralInstaller.ephemeralResolveInfo = ai;
5459                // make sure this resolver is the default
5460                ephemeralInstaller.isDefault = true;
5461                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5462                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5463                // add a non-generic filter
5464                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5465                ephemeralInstaller.filter.addDataPath(
5466                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5467                result.add(ephemeralInstaller);
5468            }
5469            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5470        }
5471        if (sortResult) {
5472            Collections.sort(result, mResolvePrioritySorter);
5473        }
5474        return result;
5475    }
5476
5477    private static class CrossProfileDomainInfo {
5478        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5479        ResolveInfo resolveInfo;
5480        /* Best domain verification status of the activities found in the other profile */
5481        int bestDomainVerificationStatus;
5482    }
5483
5484    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5485            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5486        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5487                sourceUserId)) {
5488            return null;
5489        }
5490        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5491                resolvedType, flags, parentUserId);
5492
5493        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5494            return null;
5495        }
5496        CrossProfileDomainInfo result = null;
5497        int size = resultTargetUser.size();
5498        for (int i = 0; i < size; i++) {
5499            ResolveInfo riTargetUser = resultTargetUser.get(i);
5500            // Intent filter verification is only for filters that specify a host. So don't return
5501            // those that handle all web uris.
5502            if (riTargetUser.handleAllWebDataURI) {
5503                continue;
5504            }
5505            String packageName = riTargetUser.activityInfo.packageName;
5506            PackageSetting ps = mSettings.mPackages.get(packageName);
5507            if (ps == null) {
5508                continue;
5509            }
5510            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5511            int status = (int)(verificationState >> 32);
5512            if (result == null) {
5513                result = new CrossProfileDomainInfo();
5514                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5515                        sourceUserId, parentUserId);
5516                result.bestDomainVerificationStatus = status;
5517            } else {
5518                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5519                        result.bestDomainVerificationStatus);
5520            }
5521        }
5522        // Don't consider matches with status NEVER across profiles.
5523        if (result != null && result.bestDomainVerificationStatus
5524                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5525            return null;
5526        }
5527        return result;
5528    }
5529
5530    /**
5531     * Verification statuses are ordered from the worse to the best, except for
5532     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5533     */
5534    private int bestDomainVerificationStatus(int status1, int status2) {
5535        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5536            return status2;
5537        }
5538        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5539            return status1;
5540        }
5541        return (int) MathUtils.max(status1, status2);
5542    }
5543
5544    private boolean isUserEnabled(int userId) {
5545        long callingId = Binder.clearCallingIdentity();
5546        try {
5547            UserInfo userInfo = sUserManager.getUserInfo(userId);
5548            return userInfo != null && userInfo.isEnabled();
5549        } finally {
5550            Binder.restoreCallingIdentity(callingId);
5551        }
5552    }
5553
5554    /**
5555     * Filter out activities with systemUserOnly flag set, when current user is not System.
5556     *
5557     * @return filtered list
5558     */
5559    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5560        if (userId == UserHandle.USER_SYSTEM) {
5561            return resolveInfos;
5562        }
5563        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5564            ResolveInfo info = resolveInfos.get(i);
5565            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5566                resolveInfos.remove(i);
5567            }
5568        }
5569        return resolveInfos;
5570    }
5571
5572    /**
5573     * @param resolveInfos list of resolve infos in descending priority order
5574     * @return if the list contains a resolve info with non-negative priority
5575     */
5576    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5577        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5578    }
5579
5580    private static boolean hasWebURI(Intent intent) {
5581        if (intent.getData() == null) {
5582            return false;
5583        }
5584        final String scheme = intent.getScheme();
5585        if (TextUtils.isEmpty(scheme)) {
5586            return false;
5587        }
5588        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5589    }
5590
5591    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5592            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5593            int userId) {
5594        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5595
5596        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5597            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5598                    candidates.size());
5599        }
5600
5601        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5602        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5603        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5604        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5605        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5606        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5607
5608        synchronized (mPackages) {
5609            final int count = candidates.size();
5610            // First, try to use linked apps. Partition the candidates into four lists:
5611            // one for the final results, one for the "do not use ever", one for "undefined status"
5612            // and finally one for "browser app type".
5613            for (int n=0; n<count; n++) {
5614                ResolveInfo info = candidates.get(n);
5615                String packageName = info.activityInfo.packageName;
5616                PackageSetting ps = mSettings.mPackages.get(packageName);
5617                if (ps != null) {
5618                    // Add to the special match all list (Browser use case)
5619                    if (info.handleAllWebDataURI) {
5620                        matchAllList.add(info);
5621                        continue;
5622                    }
5623                    // Try to get the status from User settings first
5624                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5625                    int status = (int)(packedStatus >> 32);
5626                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5627                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5628                        if (DEBUG_DOMAIN_VERIFICATION) {
5629                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5630                                    + " : linkgen=" + linkGeneration);
5631                        }
5632                        // Use link-enabled generation as preferredOrder, i.e.
5633                        // prefer newly-enabled over earlier-enabled.
5634                        info.preferredOrder = linkGeneration;
5635                        alwaysList.add(info);
5636                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5637                        if (DEBUG_DOMAIN_VERIFICATION) {
5638                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5639                        }
5640                        neverList.add(info);
5641                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5642                        if (DEBUG_DOMAIN_VERIFICATION) {
5643                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5644                        }
5645                        alwaysAskList.add(info);
5646                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5647                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5648                        if (DEBUG_DOMAIN_VERIFICATION) {
5649                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5650                        }
5651                        undefinedList.add(info);
5652                    }
5653                }
5654            }
5655
5656            // We'll want to include browser possibilities in a few cases
5657            boolean includeBrowser = false;
5658
5659            // First try to add the "always" resolution(s) for the current user, if any
5660            if (alwaysList.size() > 0) {
5661                result.addAll(alwaysList);
5662            } else {
5663                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5664                result.addAll(undefinedList);
5665                // Maybe add one for the other profile.
5666                if (xpDomainInfo != null && (
5667                        xpDomainInfo.bestDomainVerificationStatus
5668                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5669                    result.add(xpDomainInfo.resolveInfo);
5670                }
5671                includeBrowser = true;
5672            }
5673
5674            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5675            // If there were 'always' entries their preferred order has been set, so we also
5676            // back that off to make the alternatives equivalent
5677            if (alwaysAskList.size() > 0) {
5678                for (ResolveInfo i : result) {
5679                    i.preferredOrder = 0;
5680                }
5681                result.addAll(alwaysAskList);
5682                includeBrowser = true;
5683            }
5684
5685            if (includeBrowser) {
5686                // Also add browsers (all of them or only the default one)
5687                if (DEBUG_DOMAIN_VERIFICATION) {
5688                    Slog.v(TAG, "   ...including browsers in candidate set");
5689                }
5690                if ((matchFlags & MATCH_ALL) != 0) {
5691                    result.addAll(matchAllList);
5692                } else {
5693                    // Browser/generic handling case.  If there's a default browser, go straight
5694                    // to that (but only if there is no other higher-priority match).
5695                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5696                    int maxMatchPrio = 0;
5697                    ResolveInfo defaultBrowserMatch = null;
5698                    final int numCandidates = matchAllList.size();
5699                    for (int n = 0; n < numCandidates; n++) {
5700                        ResolveInfo info = matchAllList.get(n);
5701                        // track the highest overall match priority...
5702                        if (info.priority > maxMatchPrio) {
5703                            maxMatchPrio = info.priority;
5704                        }
5705                        // ...and the highest-priority default browser match
5706                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5707                            if (defaultBrowserMatch == null
5708                                    || (defaultBrowserMatch.priority < info.priority)) {
5709                                if (debug) {
5710                                    Slog.v(TAG, "Considering default browser match " + info);
5711                                }
5712                                defaultBrowserMatch = info;
5713                            }
5714                        }
5715                    }
5716                    if (defaultBrowserMatch != null
5717                            && defaultBrowserMatch.priority >= maxMatchPrio
5718                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5719                    {
5720                        if (debug) {
5721                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5722                        }
5723                        result.add(defaultBrowserMatch);
5724                    } else {
5725                        result.addAll(matchAllList);
5726                    }
5727                }
5728
5729                // If there is nothing selected, add all candidates and remove the ones that the user
5730                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5731                if (result.size() == 0) {
5732                    result.addAll(candidates);
5733                    result.removeAll(neverList);
5734                }
5735            }
5736        }
5737        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5738            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5739                    result.size());
5740            for (ResolveInfo info : result) {
5741                Slog.v(TAG, "  + " + info.activityInfo);
5742            }
5743        }
5744        return result;
5745    }
5746
5747    // Returns a packed value as a long:
5748    //
5749    // high 'int'-sized word: link status: undefined/ask/never/always.
5750    // low 'int'-sized word: relative priority among 'always' results.
5751    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5752        long result = ps.getDomainVerificationStatusForUser(userId);
5753        // if none available, get the master status
5754        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5755            if (ps.getIntentFilterVerificationInfo() != null) {
5756                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5757            }
5758        }
5759        return result;
5760    }
5761
5762    private ResolveInfo querySkipCurrentProfileIntents(
5763            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5764            int flags, int sourceUserId) {
5765        if (matchingFilters != null) {
5766            int size = matchingFilters.size();
5767            for (int i = 0; i < size; i ++) {
5768                CrossProfileIntentFilter filter = matchingFilters.get(i);
5769                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5770                    // Checking if there are activities in the target user that can handle the
5771                    // intent.
5772                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5773                            resolvedType, flags, sourceUserId);
5774                    if (resolveInfo != null) {
5775                        return resolveInfo;
5776                    }
5777                }
5778            }
5779        }
5780        return null;
5781    }
5782
5783    // Return matching ResolveInfo in target user if any.
5784    private ResolveInfo queryCrossProfileIntents(
5785            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5786            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5787        if (matchingFilters != null) {
5788            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5789            // match the same intent. For performance reasons, it is better not to
5790            // run queryIntent twice for the same userId
5791            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5792            int size = matchingFilters.size();
5793            for (int i = 0; i < size; i++) {
5794                CrossProfileIntentFilter filter = matchingFilters.get(i);
5795                int targetUserId = filter.getTargetUserId();
5796                boolean skipCurrentProfile =
5797                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5798                boolean skipCurrentProfileIfNoMatchFound =
5799                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5800                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5801                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5802                    // Checking if there are activities in the target user that can handle the
5803                    // intent.
5804                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5805                            resolvedType, flags, sourceUserId);
5806                    if (resolveInfo != null) return resolveInfo;
5807                    alreadyTriedUserIds.put(targetUserId, true);
5808                }
5809            }
5810        }
5811        return null;
5812    }
5813
5814    /**
5815     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5816     * will forward the intent to the filter's target user.
5817     * Otherwise, returns null.
5818     */
5819    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5820            String resolvedType, int flags, int sourceUserId) {
5821        int targetUserId = filter.getTargetUserId();
5822        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5823                resolvedType, flags, targetUserId);
5824        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5825            // If all the matches in the target profile are suspended, return null.
5826            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5827                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5828                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5829                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5830                            targetUserId);
5831                }
5832            }
5833        }
5834        return null;
5835    }
5836
5837    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5838            int sourceUserId, int targetUserId) {
5839        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5840        long ident = Binder.clearCallingIdentity();
5841        boolean targetIsProfile;
5842        try {
5843            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5844        } finally {
5845            Binder.restoreCallingIdentity(ident);
5846        }
5847        String className;
5848        if (targetIsProfile) {
5849            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5850        } else {
5851            className = FORWARD_INTENT_TO_PARENT;
5852        }
5853        ComponentName forwardingActivityComponentName = new ComponentName(
5854                mAndroidApplication.packageName, className);
5855        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5856                sourceUserId);
5857        if (!targetIsProfile) {
5858            forwardingActivityInfo.showUserIcon = targetUserId;
5859            forwardingResolveInfo.noResourceId = true;
5860        }
5861        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5862        forwardingResolveInfo.priority = 0;
5863        forwardingResolveInfo.preferredOrder = 0;
5864        forwardingResolveInfo.match = 0;
5865        forwardingResolveInfo.isDefault = true;
5866        forwardingResolveInfo.filter = filter;
5867        forwardingResolveInfo.targetUserId = targetUserId;
5868        return forwardingResolveInfo;
5869    }
5870
5871    @Override
5872    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5873            Intent[] specifics, String[] specificTypes, Intent intent,
5874            String resolvedType, int flags, int userId) {
5875        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5876                specificTypes, intent, resolvedType, flags, userId));
5877    }
5878
5879    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5880            Intent[] specifics, String[] specificTypes, Intent intent,
5881            String resolvedType, int flags, int userId) {
5882        if (!sUserManager.exists(userId)) return Collections.emptyList();
5883        flags = updateFlagsForResolve(flags, userId, intent);
5884        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5885                false /* requireFullPermission */, false /* checkShell */,
5886                "query intent activity options");
5887        final String resultsAction = intent.getAction();
5888
5889        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5890                | PackageManager.GET_RESOLVED_FILTER, userId);
5891
5892        if (DEBUG_INTENT_MATCHING) {
5893            Log.v(TAG, "Query " + intent + ": " + results);
5894        }
5895
5896        int specificsPos = 0;
5897        int N;
5898
5899        // todo: note that the algorithm used here is O(N^2).  This
5900        // isn't a problem in our current environment, but if we start running
5901        // into situations where we have more than 5 or 10 matches then this
5902        // should probably be changed to something smarter...
5903
5904        // First we go through and resolve each of the specific items
5905        // that were supplied, taking care of removing any corresponding
5906        // duplicate items in the generic resolve list.
5907        if (specifics != null) {
5908            for (int i=0; i<specifics.length; i++) {
5909                final Intent sintent = specifics[i];
5910                if (sintent == null) {
5911                    continue;
5912                }
5913
5914                if (DEBUG_INTENT_MATCHING) {
5915                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5916                }
5917
5918                String action = sintent.getAction();
5919                if (resultsAction != null && resultsAction.equals(action)) {
5920                    // If this action was explicitly requested, then don't
5921                    // remove things that have it.
5922                    action = null;
5923                }
5924
5925                ResolveInfo ri = null;
5926                ActivityInfo ai = null;
5927
5928                ComponentName comp = sintent.getComponent();
5929                if (comp == null) {
5930                    ri = resolveIntent(
5931                        sintent,
5932                        specificTypes != null ? specificTypes[i] : null,
5933                            flags, userId);
5934                    if (ri == null) {
5935                        continue;
5936                    }
5937                    if (ri == mResolveInfo) {
5938                        // ACK!  Must do something better with this.
5939                    }
5940                    ai = ri.activityInfo;
5941                    comp = new ComponentName(ai.applicationInfo.packageName,
5942                            ai.name);
5943                } else {
5944                    ai = getActivityInfo(comp, flags, userId);
5945                    if (ai == null) {
5946                        continue;
5947                    }
5948                }
5949
5950                // Look for any generic query activities that are duplicates
5951                // of this specific one, and remove them from the results.
5952                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5953                N = results.size();
5954                int j;
5955                for (j=specificsPos; j<N; j++) {
5956                    ResolveInfo sri = results.get(j);
5957                    if ((sri.activityInfo.name.equals(comp.getClassName())
5958                            && sri.activityInfo.applicationInfo.packageName.equals(
5959                                    comp.getPackageName()))
5960                        || (action != null && sri.filter.matchAction(action))) {
5961                        results.remove(j);
5962                        if (DEBUG_INTENT_MATCHING) Log.v(
5963                            TAG, "Removing duplicate item from " + j
5964                            + " due to specific " + specificsPos);
5965                        if (ri == null) {
5966                            ri = sri;
5967                        }
5968                        j--;
5969                        N--;
5970                    }
5971                }
5972
5973                // Add this specific item to its proper place.
5974                if (ri == null) {
5975                    ri = new ResolveInfo();
5976                    ri.activityInfo = ai;
5977                }
5978                results.add(specificsPos, ri);
5979                ri.specificIndex = i;
5980                specificsPos++;
5981            }
5982        }
5983
5984        // Now we go through the remaining generic results and remove any
5985        // duplicate actions that are found here.
5986        N = results.size();
5987        for (int i=specificsPos; i<N-1; i++) {
5988            final ResolveInfo rii = results.get(i);
5989            if (rii.filter == null) {
5990                continue;
5991            }
5992
5993            // Iterate over all of the actions of this result's intent
5994            // filter...  typically this should be just one.
5995            final Iterator<String> it = rii.filter.actionsIterator();
5996            if (it == null) {
5997                continue;
5998            }
5999            while (it.hasNext()) {
6000                final String action = it.next();
6001                if (resultsAction != null && resultsAction.equals(action)) {
6002                    // If this action was explicitly requested, then don't
6003                    // remove things that have it.
6004                    continue;
6005                }
6006                for (int j=i+1; j<N; j++) {
6007                    final ResolveInfo rij = results.get(j);
6008                    if (rij.filter != null && rij.filter.hasAction(action)) {
6009                        results.remove(j);
6010                        if (DEBUG_INTENT_MATCHING) Log.v(
6011                            TAG, "Removing duplicate item from " + j
6012                            + " due to action " + action + " at " + i);
6013                        j--;
6014                        N--;
6015                    }
6016                }
6017            }
6018
6019            // If the caller didn't request filter information, drop it now
6020            // so we don't have to marshall/unmarshall it.
6021            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6022                rii.filter = null;
6023            }
6024        }
6025
6026        // Filter out the caller activity if so requested.
6027        if (caller != null) {
6028            N = results.size();
6029            for (int i=0; i<N; i++) {
6030                ActivityInfo ainfo = results.get(i).activityInfo;
6031                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6032                        && caller.getClassName().equals(ainfo.name)) {
6033                    results.remove(i);
6034                    break;
6035                }
6036            }
6037        }
6038
6039        // If the caller didn't request filter information,
6040        // drop them now so we don't have to
6041        // marshall/unmarshall it.
6042        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6043            N = results.size();
6044            for (int i=0; i<N; i++) {
6045                results.get(i).filter = null;
6046            }
6047        }
6048
6049        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6050        return results;
6051    }
6052
6053    @Override
6054    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6055            String resolvedType, int flags, int userId) {
6056        return new ParceledListSlice<>(
6057                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6058    }
6059
6060    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6061            String resolvedType, int flags, int userId) {
6062        if (!sUserManager.exists(userId)) return Collections.emptyList();
6063        flags = updateFlagsForResolve(flags, userId, intent);
6064        ComponentName comp = intent.getComponent();
6065        if (comp == null) {
6066            if (intent.getSelector() != null) {
6067                intent = intent.getSelector();
6068                comp = intent.getComponent();
6069            }
6070        }
6071        if (comp != null) {
6072            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6073            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6074            if (ai != null) {
6075                ResolveInfo ri = new ResolveInfo();
6076                ri.activityInfo = ai;
6077                list.add(ri);
6078            }
6079            return list;
6080        }
6081
6082        // reader
6083        synchronized (mPackages) {
6084            String pkgName = intent.getPackage();
6085            if (pkgName == null) {
6086                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6087            }
6088            final PackageParser.Package pkg = mPackages.get(pkgName);
6089            if (pkg != null) {
6090                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6091                        userId);
6092            }
6093            return Collections.emptyList();
6094        }
6095    }
6096
6097    @Override
6098    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6099        if (!sUserManager.exists(userId)) return null;
6100        flags = updateFlagsForResolve(flags, userId, intent);
6101        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6102        if (query != null) {
6103            if (query.size() >= 1) {
6104                // If there is more than one service with the same priority,
6105                // just arbitrarily pick the first one.
6106                return query.get(0);
6107            }
6108        }
6109        return null;
6110    }
6111
6112    @Override
6113    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6114            String resolvedType, int flags, int userId) {
6115        return new ParceledListSlice<>(
6116                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6117    }
6118
6119    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6120            String resolvedType, int flags, int userId) {
6121        if (!sUserManager.exists(userId)) return Collections.emptyList();
6122        flags = updateFlagsForResolve(flags, userId, intent);
6123        ComponentName comp = intent.getComponent();
6124        if (comp == null) {
6125            if (intent.getSelector() != null) {
6126                intent = intent.getSelector();
6127                comp = intent.getComponent();
6128            }
6129        }
6130        if (comp != null) {
6131            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6132            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6133            if (si != null) {
6134                final ResolveInfo ri = new ResolveInfo();
6135                ri.serviceInfo = si;
6136                list.add(ri);
6137            }
6138            return list;
6139        }
6140
6141        // reader
6142        synchronized (mPackages) {
6143            String pkgName = intent.getPackage();
6144            if (pkgName == null) {
6145                return mServices.queryIntent(intent, resolvedType, flags, userId);
6146            }
6147            final PackageParser.Package pkg = mPackages.get(pkgName);
6148            if (pkg != null) {
6149                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6150                        userId);
6151            }
6152            return Collections.emptyList();
6153        }
6154    }
6155
6156    @Override
6157    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6158            String resolvedType, int flags, int userId) {
6159        return new ParceledListSlice<>(
6160                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6161    }
6162
6163    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6164            Intent intent, String resolvedType, int flags, int userId) {
6165        if (!sUserManager.exists(userId)) return Collections.emptyList();
6166        flags = updateFlagsForResolve(flags, userId, intent);
6167        ComponentName comp = intent.getComponent();
6168        if (comp == null) {
6169            if (intent.getSelector() != null) {
6170                intent = intent.getSelector();
6171                comp = intent.getComponent();
6172            }
6173        }
6174        if (comp != null) {
6175            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6176            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6177            if (pi != null) {
6178                final ResolveInfo ri = new ResolveInfo();
6179                ri.providerInfo = pi;
6180                list.add(ri);
6181            }
6182            return list;
6183        }
6184
6185        // reader
6186        synchronized (mPackages) {
6187            String pkgName = intent.getPackage();
6188            if (pkgName == null) {
6189                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6190            }
6191            final PackageParser.Package pkg = mPackages.get(pkgName);
6192            if (pkg != null) {
6193                return mProviders.queryIntentForPackage(
6194                        intent, resolvedType, flags, pkg.providers, userId);
6195            }
6196            return Collections.emptyList();
6197        }
6198    }
6199
6200    @Override
6201    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6202        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6203        flags = updateFlagsForPackage(flags, userId, null);
6204        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6205        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6206                true /* requireFullPermission */, false /* checkShell */,
6207                "get installed packages");
6208
6209        // writer
6210        synchronized (mPackages) {
6211            ArrayList<PackageInfo> list;
6212            if (listUninstalled) {
6213                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6214                for (PackageSetting ps : mSettings.mPackages.values()) {
6215                    final PackageInfo pi;
6216                    if (ps.pkg != null) {
6217                        pi = generatePackageInfo(ps, flags, userId);
6218                    } else {
6219                        pi = generatePackageInfo(ps, flags, userId);
6220                    }
6221                    if (pi != null) {
6222                        list.add(pi);
6223                    }
6224                }
6225            } else {
6226                list = new ArrayList<PackageInfo>(mPackages.size());
6227                for (PackageParser.Package p : mPackages.values()) {
6228                    final PackageInfo pi =
6229                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6230                    if (pi != null) {
6231                        list.add(pi);
6232                    }
6233                }
6234            }
6235
6236            return new ParceledListSlice<PackageInfo>(list);
6237        }
6238    }
6239
6240    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6241            String[] permissions, boolean[] tmp, int flags, int userId) {
6242        int numMatch = 0;
6243        final PermissionsState permissionsState = ps.getPermissionsState();
6244        for (int i=0; i<permissions.length; i++) {
6245            final String permission = permissions[i];
6246            if (permissionsState.hasPermission(permission, userId)) {
6247                tmp[i] = true;
6248                numMatch++;
6249            } else {
6250                tmp[i] = false;
6251            }
6252        }
6253        if (numMatch == 0) {
6254            return;
6255        }
6256        final PackageInfo pi;
6257        if (ps.pkg != null) {
6258            pi = generatePackageInfo(ps, flags, userId);
6259        } else {
6260            pi = generatePackageInfo(ps, flags, userId);
6261        }
6262        // The above might return null in cases of uninstalled apps or install-state
6263        // skew across users/profiles.
6264        if (pi != null) {
6265            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6266                if (numMatch == permissions.length) {
6267                    pi.requestedPermissions = permissions;
6268                } else {
6269                    pi.requestedPermissions = new String[numMatch];
6270                    numMatch = 0;
6271                    for (int i=0; i<permissions.length; i++) {
6272                        if (tmp[i]) {
6273                            pi.requestedPermissions[numMatch] = permissions[i];
6274                            numMatch++;
6275                        }
6276                    }
6277                }
6278            }
6279            list.add(pi);
6280        }
6281    }
6282
6283    @Override
6284    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6285            String[] permissions, int flags, int userId) {
6286        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6287        flags = updateFlagsForPackage(flags, userId, permissions);
6288        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6289
6290        // writer
6291        synchronized (mPackages) {
6292            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6293            boolean[] tmpBools = new boolean[permissions.length];
6294            if (listUninstalled) {
6295                for (PackageSetting ps : mSettings.mPackages.values()) {
6296                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6297                }
6298            } else {
6299                for (PackageParser.Package pkg : mPackages.values()) {
6300                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6301                    if (ps != null) {
6302                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6303                                userId);
6304                    }
6305                }
6306            }
6307
6308            return new ParceledListSlice<PackageInfo>(list);
6309        }
6310    }
6311
6312    @Override
6313    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6314        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6315        flags = updateFlagsForApplication(flags, userId, null);
6316        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6317
6318        // writer
6319        synchronized (mPackages) {
6320            ArrayList<ApplicationInfo> list;
6321            if (listUninstalled) {
6322                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6323                for (PackageSetting ps : mSettings.mPackages.values()) {
6324                    ApplicationInfo ai;
6325                    if (ps.pkg != null) {
6326                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6327                                ps.readUserState(userId), userId);
6328                    } else {
6329                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6330                    }
6331                    if (ai != null) {
6332                        list.add(ai);
6333                    }
6334                }
6335            } else {
6336                list = new ArrayList<ApplicationInfo>(mPackages.size());
6337                for (PackageParser.Package p : mPackages.values()) {
6338                    if (p.mExtras != null) {
6339                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6340                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6341                        if (ai != null) {
6342                            list.add(ai);
6343                        }
6344                    }
6345                }
6346            }
6347
6348            return new ParceledListSlice<ApplicationInfo>(list);
6349        }
6350    }
6351
6352    @Override
6353    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6354        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6355            return null;
6356        }
6357
6358        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6359                "getEphemeralApplications");
6360        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6361                true /* requireFullPermission */, false /* checkShell */,
6362                "getEphemeralApplications");
6363        synchronized (mPackages) {
6364            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6365                    .getEphemeralApplicationsLPw(userId);
6366            if (ephemeralApps != null) {
6367                return new ParceledListSlice<>(ephemeralApps);
6368            }
6369        }
6370        return null;
6371    }
6372
6373    @Override
6374    public boolean isEphemeralApplication(String packageName, int userId) {
6375        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6376                true /* requireFullPermission */, false /* checkShell */,
6377                "isEphemeral");
6378        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6379            return false;
6380        }
6381
6382        if (!isCallerSameApp(packageName)) {
6383            return false;
6384        }
6385        synchronized (mPackages) {
6386            PackageParser.Package pkg = mPackages.get(packageName);
6387            if (pkg != null) {
6388                return pkg.applicationInfo.isEphemeralApp();
6389            }
6390        }
6391        return false;
6392    }
6393
6394    @Override
6395    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6396        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6397            return null;
6398        }
6399
6400        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6401                true /* requireFullPermission */, false /* checkShell */,
6402                "getCookie");
6403        if (!isCallerSameApp(packageName)) {
6404            return null;
6405        }
6406        synchronized (mPackages) {
6407            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6408                    packageName, userId);
6409        }
6410    }
6411
6412    @Override
6413    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6414        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6415            return true;
6416        }
6417
6418        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6419                true /* requireFullPermission */, true /* checkShell */,
6420                "setCookie");
6421        if (!isCallerSameApp(packageName)) {
6422            return false;
6423        }
6424        synchronized (mPackages) {
6425            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6426                    packageName, cookie, userId);
6427        }
6428    }
6429
6430    @Override
6431    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6432        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6433            return null;
6434        }
6435
6436        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6437                "getEphemeralApplicationIcon");
6438        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6439                true /* requireFullPermission */, false /* checkShell */,
6440                "getEphemeralApplicationIcon");
6441        synchronized (mPackages) {
6442            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6443                    packageName, userId);
6444        }
6445    }
6446
6447    private boolean isCallerSameApp(String packageName) {
6448        PackageParser.Package pkg = mPackages.get(packageName);
6449        return pkg != null
6450                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6451    }
6452
6453    @Override
6454    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6455        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6456    }
6457
6458    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6459        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6460
6461        // reader
6462        synchronized (mPackages) {
6463            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6464            final int userId = UserHandle.getCallingUserId();
6465            while (i.hasNext()) {
6466                final PackageParser.Package p = i.next();
6467                if (p.applicationInfo == null) continue;
6468
6469                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6470                        && !p.applicationInfo.isDirectBootAware();
6471                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6472                        && p.applicationInfo.isDirectBootAware();
6473
6474                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6475                        && (!mSafeMode || isSystemApp(p))
6476                        && (matchesUnaware || matchesAware)) {
6477                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6478                    if (ps != null) {
6479                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6480                                ps.readUserState(userId), userId);
6481                        if (ai != null) {
6482                            finalList.add(ai);
6483                        }
6484                    }
6485                }
6486            }
6487        }
6488
6489        return finalList;
6490    }
6491
6492    @Override
6493    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6494        if (!sUserManager.exists(userId)) return null;
6495        flags = updateFlagsForComponent(flags, userId, name);
6496        // reader
6497        synchronized (mPackages) {
6498            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6499            PackageSetting ps = provider != null
6500                    ? mSettings.mPackages.get(provider.owner.packageName)
6501                    : null;
6502            return ps != null
6503                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6504                    ? PackageParser.generateProviderInfo(provider, flags,
6505                            ps.readUserState(userId), userId)
6506                    : null;
6507        }
6508    }
6509
6510    /**
6511     * @deprecated
6512     */
6513    @Deprecated
6514    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6515        // reader
6516        synchronized (mPackages) {
6517            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6518                    .entrySet().iterator();
6519            final int userId = UserHandle.getCallingUserId();
6520            while (i.hasNext()) {
6521                Map.Entry<String, PackageParser.Provider> entry = i.next();
6522                PackageParser.Provider p = entry.getValue();
6523                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6524
6525                if (ps != null && p.syncable
6526                        && (!mSafeMode || (p.info.applicationInfo.flags
6527                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6528                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6529                            ps.readUserState(userId), userId);
6530                    if (info != null) {
6531                        outNames.add(entry.getKey());
6532                        outInfo.add(info);
6533                    }
6534                }
6535            }
6536        }
6537    }
6538
6539    @Override
6540    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6541            int uid, int flags) {
6542        final int userId = processName != null ? UserHandle.getUserId(uid)
6543                : UserHandle.getCallingUserId();
6544        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6545        flags = updateFlagsForComponent(flags, userId, processName);
6546
6547        ArrayList<ProviderInfo> finalList = null;
6548        // reader
6549        synchronized (mPackages) {
6550            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6551            while (i.hasNext()) {
6552                final PackageParser.Provider p = i.next();
6553                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6554                if (ps != null && p.info.authority != null
6555                        && (processName == null
6556                                || (p.info.processName.equals(processName)
6557                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6558                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6559                    if (finalList == null) {
6560                        finalList = new ArrayList<ProviderInfo>(3);
6561                    }
6562                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6563                            ps.readUserState(userId), userId);
6564                    if (info != null) {
6565                        finalList.add(info);
6566                    }
6567                }
6568            }
6569        }
6570
6571        if (finalList != null) {
6572            Collections.sort(finalList, mProviderInitOrderSorter);
6573            return new ParceledListSlice<ProviderInfo>(finalList);
6574        }
6575
6576        return ParceledListSlice.emptyList();
6577    }
6578
6579    @Override
6580    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6581        // reader
6582        synchronized (mPackages) {
6583            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6584            return PackageParser.generateInstrumentationInfo(i, flags);
6585        }
6586    }
6587
6588    @Override
6589    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6590            String targetPackage, int flags) {
6591        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6592    }
6593
6594    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6595            int flags) {
6596        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6597
6598        // reader
6599        synchronized (mPackages) {
6600            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6601            while (i.hasNext()) {
6602                final PackageParser.Instrumentation p = i.next();
6603                if (targetPackage == null
6604                        || targetPackage.equals(p.info.targetPackage)) {
6605                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6606                            flags);
6607                    if (ii != null) {
6608                        finalList.add(ii);
6609                    }
6610                }
6611            }
6612        }
6613
6614        return finalList;
6615    }
6616
6617    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6618        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6619        if (overlays == null) {
6620            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6621            return;
6622        }
6623        for (PackageParser.Package opkg : overlays.values()) {
6624            // Not much to do if idmap fails: we already logged the error
6625            // and we certainly don't want to abort installation of pkg simply
6626            // because an overlay didn't fit properly. For these reasons,
6627            // ignore the return value of createIdmapForPackagePairLI.
6628            createIdmapForPackagePairLI(pkg, opkg);
6629        }
6630    }
6631
6632    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6633            PackageParser.Package opkg) {
6634        if (!opkg.mTrustedOverlay) {
6635            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6636                    opkg.baseCodePath + ": overlay not trusted");
6637            return false;
6638        }
6639        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6640        if (overlaySet == null) {
6641            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6642                    opkg.baseCodePath + " but target package has no known overlays");
6643            return false;
6644        }
6645        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6646        // TODO: generate idmap for split APKs
6647        try {
6648            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6649        } catch (InstallerException e) {
6650            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6651                    + opkg.baseCodePath);
6652            return false;
6653        }
6654        PackageParser.Package[] overlayArray =
6655            overlaySet.values().toArray(new PackageParser.Package[0]);
6656        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6657            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6658                return p1.mOverlayPriority - p2.mOverlayPriority;
6659            }
6660        };
6661        Arrays.sort(overlayArray, cmp);
6662
6663        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6664        int i = 0;
6665        for (PackageParser.Package p : overlayArray) {
6666            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6667        }
6668        return true;
6669    }
6670
6671    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6672        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
6673        try {
6674            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6675        } finally {
6676            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6677        }
6678    }
6679
6680    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6681        final File[] files = dir.listFiles();
6682        if (ArrayUtils.isEmpty(files)) {
6683            Log.d(TAG, "No files in app dir " + dir);
6684            return;
6685        }
6686
6687        if (DEBUG_PACKAGE_SCANNING) {
6688            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6689                    + " flags=0x" + Integer.toHexString(parseFlags));
6690        }
6691
6692        for (File file : files) {
6693            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6694                    && !PackageInstallerService.isStageName(file.getName());
6695            if (!isPackage) {
6696                // Ignore entries which are not packages
6697                continue;
6698            }
6699            try {
6700                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6701                        scanFlags, currentTime, null);
6702            } catch (PackageManagerException e) {
6703                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6704
6705                // Delete invalid userdata apps
6706                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6707                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6708                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6709                    removeCodePathLI(file);
6710                }
6711            }
6712        }
6713    }
6714
6715    private static File getSettingsProblemFile() {
6716        File dataDir = Environment.getDataDirectory();
6717        File systemDir = new File(dataDir, "system");
6718        File fname = new File(systemDir, "uiderrors.txt");
6719        return fname;
6720    }
6721
6722    static void reportSettingsProblem(int priority, String msg) {
6723        logCriticalInfo(priority, msg);
6724    }
6725
6726    static void logCriticalInfo(int priority, String msg) {
6727        Slog.println(priority, TAG, msg);
6728        EventLogTags.writePmCriticalInfo(msg);
6729        try {
6730            File fname = getSettingsProblemFile();
6731            FileOutputStream out = new FileOutputStream(fname, true);
6732            PrintWriter pw = new FastPrintWriter(out);
6733            SimpleDateFormat formatter = new SimpleDateFormat();
6734            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6735            pw.println(dateString + ": " + msg);
6736            pw.close();
6737            FileUtils.setPermissions(
6738                    fname.toString(),
6739                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6740                    -1, -1);
6741        } catch (java.io.IOException e) {
6742        }
6743    }
6744
6745    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6746        if (srcFile.isDirectory()) {
6747            final File baseFile = new File(pkg.baseCodePath);
6748            long maxModifiedTime = baseFile.lastModified();
6749            if (pkg.splitCodePaths != null) {
6750                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6751                    final File splitFile = new File(pkg.splitCodePaths[i]);
6752                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6753                }
6754            }
6755            return maxModifiedTime;
6756        }
6757        return srcFile.lastModified();
6758    }
6759
6760    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6761            final int policyFlags) throws PackageManagerException {
6762        // When upgrading from pre-N MR1, verify the package time stamp using the package
6763        // directory and not the APK file.
6764        final long lastModifiedTime = mIsPreNMR1Upgrade
6765                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6766        if (ps != null
6767                && ps.codePath.equals(srcFile)
6768                && ps.timeStamp == lastModifiedTime
6769                && !isCompatSignatureUpdateNeeded(pkg)
6770                && !isRecoverSignatureUpdateNeeded(pkg)) {
6771            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6772            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6773            ArraySet<PublicKey> signingKs;
6774            synchronized (mPackages) {
6775                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6776            }
6777            if (ps.signatures.mSignatures != null
6778                    && ps.signatures.mSignatures.length != 0
6779                    && signingKs != null) {
6780                // Optimization: reuse the existing cached certificates
6781                // if the package appears to be unchanged.
6782                pkg.mSignatures = ps.signatures.mSignatures;
6783                pkg.mSigningKeys = signingKs;
6784                return;
6785            }
6786
6787            Slog.w(TAG, "PackageSetting for " + ps.name
6788                    + " is missing signatures.  Collecting certs again to recover them.");
6789        } else {
6790            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6791        }
6792
6793        try {
6794            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
6795            PackageParser.collectCertificates(pkg, policyFlags);
6796        } catch (PackageParserException e) {
6797            throw PackageManagerException.from(e);
6798        } finally {
6799            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6800        }
6801    }
6802
6803    /**
6804     *  Traces a package scan.
6805     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6806     */
6807    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6808            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6809        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
6810        try {
6811            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6812        } finally {
6813            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6814        }
6815    }
6816
6817    /**
6818     *  Scans a package and returns the newly parsed package.
6819     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6820     */
6821    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6822            long currentTime, UserHandle user) throws PackageManagerException {
6823        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6824        PackageParser pp = new PackageParser();
6825        pp.setSeparateProcesses(mSeparateProcesses);
6826        pp.setOnlyCoreApps(mOnlyCore);
6827        pp.setDisplayMetrics(mMetrics);
6828
6829        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6830            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6831        }
6832
6833        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6834        final PackageParser.Package pkg;
6835        try {
6836            pkg = pp.parsePackage(scanFile, parseFlags);
6837        } catch (PackageParserException e) {
6838            throw PackageManagerException.from(e);
6839        } finally {
6840            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6841        }
6842
6843        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6844    }
6845
6846    /**
6847     *  Scans a package and returns the newly parsed package.
6848     *  @throws PackageManagerException on a parse error.
6849     */
6850    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6851            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6852            throws PackageManagerException {
6853        // If the package has children and this is the first dive in the function
6854        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6855        // packages (parent and children) would be successfully scanned before the
6856        // actual scan since scanning mutates internal state and we want to atomically
6857        // install the package and its children.
6858        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6859            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6860                scanFlags |= SCAN_CHECK_ONLY;
6861            }
6862        } else {
6863            scanFlags &= ~SCAN_CHECK_ONLY;
6864        }
6865
6866        // Scan the parent
6867        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6868                scanFlags, currentTime, user);
6869
6870        // Scan the children
6871        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6872        for (int i = 0; i < childCount; i++) {
6873            PackageParser.Package childPackage = pkg.childPackages.get(i);
6874            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6875                    currentTime, user);
6876        }
6877
6878
6879        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6880            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6881        }
6882
6883        return scannedPkg;
6884    }
6885
6886    /**
6887     *  Scans a package and returns the newly parsed package.
6888     *  @throws PackageManagerException on a parse error.
6889     */
6890    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6891            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6892            throws PackageManagerException {
6893        PackageSetting ps = null;
6894        PackageSetting updatedPkg;
6895        // reader
6896        synchronized (mPackages) {
6897            // Look to see if we already know about this package.
6898            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
6899            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6900                // This package has been renamed to its original name.  Let's
6901                // use that.
6902                ps = mSettings.peekPackageLPr(oldName);
6903            }
6904            // If there was no original package, see one for the real package name.
6905            if (ps == null) {
6906                ps = mSettings.peekPackageLPr(pkg.packageName);
6907            }
6908            // Check to see if this package could be hiding/updating a system
6909            // package.  Must look for it either under the original or real
6910            // package name depending on our state.
6911            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6912            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6913
6914            // If this is a package we don't know about on the system partition, we
6915            // may need to remove disabled child packages on the system partition
6916            // or may need to not add child packages if the parent apk is updated
6917            // on the data partition and no longer defines this child package.
6918            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6919                // If this is a parent package for an updated system app and this system
6920                // app got an OTA update which no longer defines some of the child packages
6921                // we have to prune them from the disabled system packages.
6922                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6923                if (disabledPs != null) {
6924                    final int scannedChildCount = (pkg.childPackages != null)
6925                            ? pkg.childPackages.size() : 0;
6926                    final int disabledChildCount = disabledPs.childPackageNames != null
6927                            ? disabledPs.childPackageNames.size() : 0;
6928                    for (int i = 0; i < disabledChildCount; i++) {
6929                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6930                        boolean disabledPackageAvailable = false;
6931                        for (int j = 0; j < scannedChildCount; j++) {
6932                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6933                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6934                                disabledPackageAvailable = true;
6935                                break;
6936                            }
6937                         }
6938                         if (!disabledPackageAvailable) {
6939                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6940                         }
6941                    }
6942                }
6943            }
6944        }
6945
6946        boolean updatedPkgBetter = false;
6947        // First check if this is a system package that may involve an update
6948        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6949            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6950            // it needs to drop FLAG_PRIVILEGED.
6951            if (locationIsPrivileged(scanFile)) {
6952                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6953            } else {
6954                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6955            }
6956
6957            if (ps != null && !ps.codePath.equals(scanFile)) {
6958                // The path has changed from what was last scanned...  check the
6959                // version of the new path against what we have stored to determine
6960                // what to do.
6961                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6962                if (pkg.mVersionCode <= ps.versionCode) {
6963                    // The system package has been updated and the code path does not match
6964                    // Ignore entry. Skip it.
6965                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6966                            + " ignored: updated version " + ps.versionCode
6967                            + " better than this " + pkg.mVersionCode);
6968                    if (!updatedPkg.codePath.equals(scanFile)) {
6969                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6970                                + ps.name + " changing from " + updatedPkg.codePathString
6971                                + " to " + scanFile);
6972                        updatedPkg.codePath = scanFile;
6973                        updatedPkg.codePathString = scanFile.toString();
6974                        updatedPkg.resourcePath = scanFile;
6975                        updatedPkg.resourcePathString = scanFile.toString();
6976                    }
6977                    updatedPkg.pkg = pkg;
6978                    updatedPkg.versionCode = pkg.mVersionCode;
6979
6980                    // Update the disabled system child packages to point to the package too.
6981                    final int childCount = updatedPkg.childPackageNames != null
6982                            ? updatedPkg.childPackageNames.size() : 0;
6983                    for (int i = 0; i < childCount; i++) {
6984                        String childPackageName = updatedPkg.childPackageNames.get(i);
6985                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6986                                childPackageName);
6987                        if (updatedChildPkg != null) {
6988                            updatedChildPkg.pkg = pkg;
6989                            updatedChildPkg.versionCode = pkg.mVersionCode;
6990                        }
6991                    }
6992
6993                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6994                            + scanFile + " ignored: updated version " + ps.versionCode
6995                            + " better than this " + pkg.mVersionCode);
6996                } else {
6997                    // The current app on the system partition is better than
6998                    // what we have updated to on the data partition; switch
6999                    // back to the system partition version.
7000                    // At this point, its safely assumed that package installation for
7001                    // apps in system partition will go through. If not there won't be a working
7002                    // version of the app
7003                    // writer
7004                    synchronized (mPackages) {
7005                        // Just remove the loaded entries from package lists.
7006                        mPackages.remove(ps.name);
7007                    }
7008
7009                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7010                            + " reverting from " + ps.codePathString
7011                            + ": new version " + pkg.mVersionCode
7012                            + " better than installed " + ps.versionCode);
7013
7014                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7015                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7016                    synchronized (mInstallLock) {
7017                        args.cleanUpResourcesLI();
7018                    }
7019                    synchronized (mPackages) {
7020                        mSettings.enableSystemPackageLPw(ps.name);
7021                    }
7022                    updatedPkgBetter = true;
7023                }
7024            }
7025        }
7026
7027        if (updatedPkg != null) {
7028            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7029            // initially
7030            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7031
7032            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7033            // flag set initially
7034            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7035                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7036            }
7037        }
7038
7039        // Verify certificates against what was last scanned
7040        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7041
7042        /*
7043         * A new system app appeared, but we already had a non-system one of the
7044         * same name installed earlier.
7045         */
7046        boolean shouldHideSystemApp = false;
7047        if (updatedPkg == null && ps != null
7048                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7049            /*
7050             * Check to make sure the signatures match first. If they don't,
7051             * wipe the installed application and its data.
7052             */
7053            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7054                    != PackageManager.SIGNATURE_MATCH) {
7055                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7056                        + " signatures don't match existing userdata copy; removing");
7057                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7058                        "scanPackageInternalLI")) {
7059                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7060                }
7061                ps = null;
7062            } else {
7063                /*
7064                 * If the newly-added system app is an older version than the
7065                 * already installed version, hide it. It will be scanned later
7066                 * and re-added like an update.
7067                 */
7068                if (pkg.mVersionCode <= ps.versionCode) {
7069                    shouldHideSystemApp = true;
7070                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7071                            + " but new version " + pkg.mVersionCode + " better than installed "
7072                            + ps.versionCode + "; hiding system");
7073                } else {
7074                    /*
7075                     * The newly found system app is a newer version that the
7076                     * one previously installed. Simply remove the
7077                     * already-installed application and replace it with our own
7078                     * while keeping the application data.
7079                     */
7080                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7081                            + " reverting from " + ps.codePathString + ": new version "
7082                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7083                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7084                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7085                    synchronized (mInstallLock) {
7086                        args.cleanUpResourcesLI();
7087                    }
7088                }
7089            }
7090        }
7091
7092        // The apk is forward locked (not public) if its code and resources
7093        // are kept in different files. (except for app in either system or
7094        // vendor path).
7095        // TODO grab this value from PackageSettings
7096        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7097            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7098                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7099            }
7100        }
7101
7102        // TODO: extend to support forward-locked splits
7103        String resourcePath = null;
7104        String baseResourcePath = null;
7105        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7106            if (ps != null && ps.resourcePathString != null) {
7107                resourcePath = ps.resourcePathString;
7108                baseResourcePath = ps.resourcePathString;
7109            } else {
7110                // Should not happen at all. Just log an error.
7111                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7112            }
7113        } else {
7114            resourcePath = pkg.codePath;
7115            baseResourcePath = pkg.baseCodePath;
7116        }
7117
7118        // Set application objects path explicitly.
7119        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7120        pkg.setApplicationInfoCodePath(pkg.codePath);
7121        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7122        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7123        pkg.setApplicationInfoResourcePath(resourcePath);
7124        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7125        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7126
7127        // Note that we invoke the following method only if we are about to unpack an application
7128        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7129                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7130
7131        /*
7132         * If the system app should be overridden by a previously installed
7133         * data, hide the system app now and let the /data/app scan pick it up
7134         * again.
7135         */
7136        if (shouldHideSystemApp) {
7137            synchronized (mPackages) {
7138                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7139            }
7140        }
7141
7142        return scannedPkg;
7143    }
7144
7145    private static String fixProcessName(String defProcessName,
7146            String processName) {
7147        if (processName == null) {
7148            return defProcessName;
7149        }
7150        return processName;
7151    }
7152
7153    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7154            throws PackageManagerException {
7155        if (pkgSetting.signatures.mSignatures != null) {
7156            // Already existing package. Make sure signatures match
7157            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7158                    == PackageManager.SIGNATURE_MATCH;
7159            if (!match) {
7160                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7161                        == PackageManager.SIGNATURE_MATCH;
7162            }
7163            if (!match) {
7164                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7165                        == PackageManager.SIGNATURE_MATCH;
7166            }
7167            if (!match) {
7168                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7169                        + pkg.packageName + " signatures do not match the "
7170                        + "previously installed version; ignoring!");
7171            }
7172        }
7173
7174        // Check for shared user signatures
7175        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7176            // Already existing package. Make sure signatures match
7177            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7178                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7179            if (!match) {
7180                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7181                        == PackageManager.SIGNATURE_MATCH;
7182            }
7183            if (!match) {
7184                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7185                        == PackageManager.SIGNATURE_MATCH;
7186            }
7187            if (!match) {
7188                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7189                        "Package " + pkg.packageName
7190                        + " has no signatures that match those in shared user "
7191                        + pkgSetting.sharedUser.name + "; ignoring!");
7192            }
7193        }
7194    }
7195
7196    /**
7197     * Enforces that only the system UID or root's UID can call a method exposed
7198     * via Binder.
7199     *
7200     * @param message used as message if SecurityException is thrown
7201     * @throws SecurityException if the caller is not system or root
7202     */
7203    private static final void enforceSystemOrRoot(String message) {
7204        final int uid = Binder.getCallingUid();
7205        if (uid != Process.SYSTEM_UID && uid != 0) {
7206            throw new SecurityException(message);
7207        }
7208    }
7209
7210    @Override
7211    public void performFstrimIfNeeded() {
7212        enforceSystemOrRoot("Only the system can request fstrim");
7213
7214        // Before everything else, see whether we need to fstrim.
7215        try {
7216            IMountService ms = PackageHelper.getMountService();
7217            if (ms != null) {
7218                boolean doTrim = false;
7219                final long interval = android.provider.Settings.Global.getLong(
7220                        mContext.getContentResolver(),
7221                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7222                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7223                if (interval > 0) {
7224                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7225                    if (timeSinceLast > interval) {
7226                        doTrim = true;
7227                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7228                                + "; running immediately");
7229                    }
7230                }
7231                if (doTrim) {
7232                    final boolean dexOptDialogShown;
7233                    synchronized (mPackages) {
7234                        dexOptDialogShown = mDexOptDialogShown;
7235                    }
7236                    if (!isFirstBoot() && dexOptDialogShown) {
7237                        try {
7238                            ActivityManagerNative.getDefault().showBootMessage(
7239                                    mContext.getResources().getString(
7240                                            R.string.android_upgrading_fstrim), true);
7241                        } catch (RemoteException e) {
7242                        }
7243                    }
7244                    ms.runMaintenance();
7245                }
7246            } else {
7247                Slog.e(TAG, "Mount service unavailable!");
7248            }
7249        } catch (RemoteException e) {
7250            // Can't happen; MountService is local
7251        }
7252    }
7253
7254    @Override
7255    public void updatePackagesIfNeeded() {
7256        enforceSystemOrRoot("Only the system can request package update");
7257
7258        // We need to re-extract after an OTA.
7259        boolean causeUpgrade = isUpgrade();
7260
7261        // First boot or factory reset.
7262        // Note: we also handle devices that are upgrading to N right now as if it is their
7263        //       first boot, as they do not have profile data.
7264        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7265
7266        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7267        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7268
7269        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7270            return;
7271        }
7272
7273        List<PackageParser.Package> pkgs;
7274        synchronized (mPackages) {
7275            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7276        }
7277
7278        final long startTime = System.nanoTime();
7279        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7280                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7281
7282        final int elapsedTimeSeconds =
7283                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7284
7285        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7286        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7287        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7288        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7289        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7290    }
7291
7292    /**
7293     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7294     * containing statistics about the invocation. The array consists of three elements,
7295     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7296     * and {@code numberOfPackagesFailed}.
7297     */
7298    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7299            String compilerFilter) {
7300
7301        int numberOfPackagesVisited = 0;
7302        int numberOfPackagesOptimized = 0;
7303        int numberOfPackagesSkipped = 0;
7304        int numberOfPackagesFailed = 0;
7305        final int numberOfPackagesToDexopt = pkgs.size();
7306
7307        for (PackageParser.Package pkg : pkgs) {
7308            numberOfPackagesVisited++;
7309
7310            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7311                if (DEBUG_DEXOPT) {
7312                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7313                }
7314                numberOfPackagesSkipped++;
7315                continue;
7316            }
7317
7318            if (DEBUG_DEXOPT) {
7319                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7320                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7321            }
7322
7323            if (showDialog) {
7324                try {
7325                    ActivityManagerNative.getDefault().showBootMessage(
7326                            mContext.getResources().getString(R.string.android_upgrading_apk,
7327                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7328                } catch (RemoteException e) {
7329                }
7330                synchronized (mPackages) {
7331                    mDexOptDialogShown = true;
7332                }
7333            }
7334
7335            // If the OTA updates a system app which was previously preopted to a non-preopted state
7336            // the app might end up being verified at runtime. That's because by default the apps
7337            // are verify-profile but for preopted apps there's no profile.
7338            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7339            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7340            // filter (by default interpret-only).
7341            // Note that at this stage unused apps are already filtered.
7342            if (isSystemApp(pkg) &&
7343                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7344                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7345                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7346            }
7347
7348            // If the OTA updates a system app which was previously preopted to a non-preopted state
7349            // the app might end up being verified at runtime. That's because by default the apps
7350            // are verify-profile but for preopted apps there's no profile.
7351            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7352            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7353            // filter (by default interpret-only).
7354            // Note that at this stage unused apps are already filtered.
7355            if (isSystemApp(pkg) &&
7356                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7357                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7358                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7359            }
7360
7361            // checkProfiles is false to avoid merging profiles during boot which
7362            // might interfere with background compilation (b/28612421).
7363            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7364            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7365            // trade-off worth doing to save boot time work.
7366            int dexOptStatus = performDexOptTraced(pkg.packageName,
7367                    false /* checkProfiles */,
7368                    compilerFilter,
7369                    false /* force */);
7370            switch (dexOptStatus) {
7371                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7372                    numberOfPackagesOptimized++;
7373                    break;
7374                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7375                    numberOfPackagesSkipped++;
7376                    break;
7377                case PackageDexOptimizer.DEX_OPT_FAILED:
7378                    numberOfPackagesFailed++;
7379                    break;
7380                default:
7381                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7382                    break;
7383            }
7384        }
7385
7386        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7387                numberOfPackagesFailed };
7388    }
7389
7390    @Override
7391    public void notifyPackageUse(String packageName, int reason) {
7392        synchronized (mPackages) {
7393            PackageParser.Package p = mPackages.get(packageName);
7394            if (p == null) {
7395                return;
7396            }
7397            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7398        }
7399    }
7400
7401    // TODO: this is not used nor needed. Delete it.
7402    @Override
7403    public boolean performDexOptIfNeeded(String packageName) {
7404        int dexOptStatus = performDexOptTraced(packageName,
7405                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7406        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7407    }
7408
7409    @Override
7410    public boolean performDexOpt(String packageName,
7411            boolean checkProfiles, int compileReason, boolean force) {
7412        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7413                getCompilerFilterForReason(compileReason), force);
7414        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7415    }
7416
7417    @Override
7418    public boolean performDexOptMode(String packageName,
7419            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7420        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7421                targetCompilerFilter, force);
7422        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7423    }
7424
7425    private int performDexOptTraced(String packageName,
7426                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7427        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7428        try {
7429            return performDexOptInternal(packageName, checkProfiles,
7430                    targetCompilerFilter, force);
7431        } finally {
7432            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7433        }
7434    }
7435
7436    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7437    // if the package can now be considered up to date for the given filter.
7438    private int performDexOptInternal(String packageName,
7439                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7440        PackageParser.Package p;
7441        synchronized (mPackages) {
7442            p = mPackages.get(packageName);
7443            if (p == null) {
7444                // Package could not be found. Report failure.
7445                return PackageDexOptimizer.DEX_OPT_FAILED;
7446            }
7447            mPackageUsage.maybeWriteAsync(mPackages);
7448            mCompilerStats.maybeWriteAsync();
7449        }
7450        long callingId = Binder.clearCallingIdentity();
7451        try {
7452            synchronized (mInstallLock) {
7453                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7454                        targetCompilerFilter, force);
7455            }
7456        } finally {
7457            Binder.restoreCallingIdentity(callingId);
7458        }
7459    }
7460
7461    public ArraySet<String> getOptimizablePackages() {
7462        ArraySet<String> pkgs = new ArraySet<String>();
7463        synchronized (mPackages) {
7464            for (PackageParser.Package p : mPackages.values()) {
7465                if (PackageDexOptimizer.canOptimizePackage(p)) {
7466                    pkgs.add(p.packageName);
7467                }
7468            }
7469        }
7470        return pkgs;
7471    }
7472
7473    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7474            boolean checkProfiles, String targetCompilerFilter,
7475            boolean force) {
7476        // Select the dex optimizer based on the force parameter.
7477        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7478        //       allocate an object here.
7479        PackageDexOptimizer pdo = force
7480                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7481                : mPackageDexOptimizer;
7482
7483        // Optimize all dependencies first. Note: we ignore the return value and march on
7484        // on errors.
7485        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7486        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7487        if (!deps.isEmpty()) {
7488            for (PackageParser.Package depPackage : deps) {
7489                // TODO: Analyze and investigate if we (should) profile libraries.
7490                // Currently this will do a full compilation of the library by default.
7491                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7492                        false /* checkProfiles */,
7493                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7494                        getOrCreateCompilerPackageStats(depPackage));
7495            }
7496        }
7497        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7498                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7499    }
7500
7501    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7502        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7503            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7504            Set<String> collectedNames = new HashSet<>();
7505            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7506
7507            retValue.remove(p);
7508
7509            return retValue;
7510        } else {
7511            return Collections.emptyList();
7512        }
7513    }
7514
7515    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7516            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7517        if (!collectedNames.contains(p.packageName)) {
7518            collectedNames.add(p.packageName);
7519            collected.add(p);
7520
7521            if (p.usesLibraries != null) {
7522                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7523            }
7524            if (p.usesOptionalLibraries != null) {
7525                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7526                        collectedNames);
7527            }
7528        }
7529    }
7530
7531    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7532            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7533        for (String libName : libs) {
7534            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7535            if (libPkg != null) {
7536                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7537            }
7538        }
7539    }
7540
7541    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7542        synchronized (mPackages) {
7543            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7544            if (lib != null && lib.apk != null) {
7545                return mPackages.get(lib.apk);
7546            }
7547        }
7548        return null;
7549    }
7550
7551    public void shutdown() {
7552        mPackageUsage.writeNow(mPackages);
7553        mCompilerStats.writeNow();
7554    }
7555
7556    @Override
7557    public void dumpProfiles(String packageName) {
7558        PackageParser.Package pkg;
7559        synchronized (mPackages) {
7560            pkg = mPackages.get(packageName);
7561            if (pkg == null) {
7562                throw new IllegalArgumentException("Unknown package: " + packageName);
7563            }
7564        }
7565        /* Only the shell, root, or the app user should be able to dump profiles. */
7566        int callingUid = Binder.getCallingUid();
7567        if (callingUid != Process.SHELL_UID &&
7568            callingUid != Process.ROOT_UID &&
7569            callingUid != pkg.applicationInfo.uid) {
7570            throw new SecurityException("dumpProfiles");
7571        }
7572
7573        synchronized (mInstallLock) {
7574            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7575            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7576            try {
7577                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7578                String gid = Integer.toString(sharedGid);
7579                String codePaths = TextUtils.join(";", allCodePaths);
7580                mInstaller.dumpProfiles(gid, packageName, codePaths);
7581            } catch (InstallerException e) {
7582                Slog.w(TAG, "Failed to dump profiles", e);
7583            }
7584            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7585        }
7586    }
7587
7588    @Override
7589    public void forceDexOpt(String packageName) {
7590        enforceSystemOrRoot("forceDexOpt");
7591
7592        PackageParser.Package pkg;
7593        synchronized (mPackages) {
7594            pkg = mPackages.get(packageName);
7595            if (pkg == null) {
7596                throw new IllegalArgumentException("Unknown package: " + packageName);
7597            }
7598        }
7599
7600        synchronized (mInstallLock) {
7601            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7602
7603            // Whoever is calling forceDexOpt wants a fully compiled package.
7604            // Don't use profiles since that may cause compilation to be skipped.
7605            final int res = performDexOptInternalWithDependenciesLI(pkg,
7606                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7607                    true /* force */);
7608
7609            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7610            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7611                throw new IllegalStateException("Failed to dexopt: " + res);
7612            }
7613        }
7614    }
7615
7616    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7617        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7618            Slog.w(TAG, "Unable to update from " + oldPkg.name
7619                    + " to " + newPkg.packageName
7620                    + ": old package not in system partition");
7621            return false;
7622        } else if (mPackages.get(oldPkg.name) != null) {
7623            Slog.w(TAG, "Unable to update from " + oldPkg.name
7624                    + " to " + newPkg.packageName
7625                    + ": old package still exists");
7626            return false;
7627        }
7628        return true;
7629    }
7630
7631    void removeCodePathLI(File codePath) {
7632        if (codePath.isDirectory()) {
7633            try {
7634                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7635            } catch (InstallerException e) {
7636                Slog.w(TAG, "Failed to remove code path", e);
7637            }
7638        } else {
7639            codePath.delete();
7640        }
7641    }
7642
7643    private int[] resolveUserIds(int userId) {
7644        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7645    }
7646
7647    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7648        if (pkg == null) {
7649            Slog.wtf(TAG, "Package was null!", new Throwable());
7650            return;
7651        }
7652        clearAppDataLeafLIF(pkg, userId, flags);
7653        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7654        for (int i = 0; i < childCount; i++) {
7655            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7656        }
7657    }
7658
7659    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7660        final PackageSetting ps;
7661        synchronized (mPackages) {
7662            ps = mSettings.mPackages.get(pkg.packageName);
7663        }
7664        for (int realUserId : resolveUserIds(userId)) {
7665            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7666            try {
7667                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7668                        ceDataInode);
7669            } catch (InstallerException e) {
7670                Slog.w(TAG, String.valueOf(e));
7671            }
7672        }
7673    }
7674
7675    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7676        if (pkg == null) {
7677            Slog.wtf(TAG, "Package was null!", new Throwable());
7678            return;
7679        }
7680        destroyAppDataLeafLIF(pkg, userId, flags);
7681        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7682        for (int i = 0; i < childCount; i++) {
7683            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7684        }
7685    }
7686
7687    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7688        final PackageSetting ps;
7689        synchronized (mPackages) {
7690            ps = mSettings.mPackages.get(pkg.packageName);
7691        }
7692        for (int realUserId : resolveUserIds(userId)) {
7693            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7694            try {
7695                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7696                        ceDataInode);
7697            } catch (InstallerException e) {
7698                Slog.w(TAG, String.valueOf(e));
7699            }
7700        }
7701    }
7702
7703    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7704        if (pkg == null) {
7705            Slog.wtf(TAG, "Package was null!", new Throwable());
7706            return;
7707        }
7708        destroyAppProfilesLeafLIF(pkg);
7709        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7710        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7711        for (int i = 0; i < childCount; i++) {
7712            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7713            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7714                    true /* removeBaseMarker */);
7715        }
7716    }
7717
7718    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7719            boolean removeBaseMarker) {
7720        if (pkg.isForwardLocked()) {
7721            return;
7722        }
7723
7724        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7725            try {
7726                path = PackageManagerServiceUtils.realpath(new File(path));
7727            } catch (IOException e) {
7728                // TODO: Should we return early here ?
7729                Slog.w(TAG, "Failed to get canonical path", e);
7730                continue;
7731            }
7732
7733            final String useMarker = path.replace('/', '@');
7734            for (int realUserId : resolveUserIds(userId)) {
7735                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7736                if (removeBaseMarker) {
7737                    File foreignUseMark = new File(profileDir, useMarker);
7738                    if (foreignUseMark.exists()) {
7739                        if (!foreignUseMark.delete()) {
7740                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7741                                    + pkg.packageName);
7742                        }
7743                    }
7744                }
7745
7746                File[] markers = profileDir.listFiles();
7747                if (markers != null) {
7748                    final String searchString = "@" + pkg.packageName + "@";
7749                    // We also delete all markers that contain the package name we're
7750                    // uninstalling. These are associated with secondary dex-files belonging
7751                    // to the package. Reconstructing the path of these dex files is messy
7752                    // in general.
7753                    for (File marker : markers) {
7754                        if (marker.getName().indexOf(searchString) > 0) {
7755                            if (!marker.delete()) {
7756                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7757                                    + pkg.packageName);
7758                            }
7759                        }
7760                    }
7761                }
7762            }
7763        }
7764    }
7765
7766    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7767        try {
7768            mInstaller.destroyAppProfiles(pkg.packageName);
7769        } catch (InstallerException e) {
7770            Slog.w(TAG, String.valueOf(e));
7771        }
7772    }
7773
7774    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7775        if (pkg == null) {
7776            Slog.wtf(TAG, "Package was null!", new Throwable());
7777            return;
7778        }
7779        clearAppProfilesLeafLIF(pkg);
7780        // We don't remove the base foreign use marker when clearing profiles because
7781        // we will rename it when the app is updated. Unlike the actual profile contents,
7782        // the foreign use marker is good across installs.
7783        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7784        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7785        for (int i = 0; i < childCount; i++) {
7786            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7787        }
7788    }
7789
7790    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7791        try {
7792            mInstaller.clearAppProfiles(pkg.packageName);
7793        } catch (InstallerException e) {
7794            Slog.w(TAG, String.valueOf(e));
7795        }
7796    }
7797
7798    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7799            long lastUpdateTime) {
7800        // Set parent install/update time
7801        PackageSetting ps = (PackageSetting) pkg.mExtras;
7802        if (ps != null) {
7803            ps.firstInstallTime = firstInstallTime;
7804            ps.lastUpdateTime = lastUpdateTime;
7805        }
7806        // Set children install/update time
7807        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7808        for (int i = 0; i < childCount; i++) {
7809            PackageParser.Package childPkg = pkg.childPackages.get(i);
7810            ps = (PackageSetting) childPkg.mExtras;
7811            if (ps != null) {
7812                ps.firstInstallTime = firstInstallTime;
7813                ps.lastUpdateTime = lastUpdateTime;
7814            }
7815        }
7816    }
7817
7818    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7819            PackageParser.Package changingLib) {
7820        if (file.path != null) {
7821            usesLibraryFiles.add(file.path);
7822            return;
7823        }
7824        PackageParser.Package p = mPackages.get(file.apk);
7825        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7826            // If we are doing this while in the middle of updating a library apk,
7827            // then we need to make sure to use that new apk for determining the
7828            // dependencies here.  (We haven't yet finished committing the new apk
7829            // to the package manager state.)
7830            if (p == null || p.packageName.equals(changingLib.packageName)) {
7831                p = changingLib;
7832            }
7833        }
7834        if (p != null) {
7835            usesLibraryFiles.addAll(p.getAllCodePaths());
7836        }
7837    }
7838
7839    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
7840            PackageParser.Package changingLib) throws PackageManagerException {
7841        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7842            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7843            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7844            for (int i=0; i<N; i++) {
7845                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7846                if (file == null) {
7847                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7848                            "Package " + pkg.packageName + " requires unavailable shared library "
7849                            + pkg.usesLibraries.get(i) + "; failing!");
7850                }
7851                addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
7852            }
7853            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7854            for (int i=0; i<N; i++) {
7855                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7856                if (file == null) {
7857                    Slog.w(TAG, "Package " + pkg.packageName
7858                            + " desires unavailable shared library "
7859                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7860                } else {
7861                    addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
7862                }
7863            }
7864            N = usesLibraryFiles.size();
7865            if (N > 0) {
7866                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7867            } else {
7868                pkg.usesLibraryFiles = null;
7869            }
7870        }
7871    }
7872
7873    private static boolean hasString(List<String> list, List<String> which) {
7874        if (list == null) {
7875            return false;
7876        }
7877        for (int i=list.size()-1; i>=0; i--) {
7878            for (int j=which.size()-1; j>=0; j--) {
7879                if (which.get(j).equals(list.get(i))) {
7880                    return true;
7881                }
7882            }
7883        }
7884        return false;
7885    }
7886
7887    private void updateAllSharedLibrariesLPw() {
7888        for (PackageParser.Package pkg : mPackages.values()) {
7889            try {
7890                updateSharedLibrariesLPr(pkg, null);
7891            } catch (PackageManagerException e) {
7892                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7893            }
7894        }
7895    }
7896
7897    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7898            PackageParser.Package changingPkg) {
7899        ArrayList<PackageParser.Package> res = null;
7900        for (PackageParser.Package pkg : mPackages.values()) {
7901            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7902                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7903                if (res == null) {
7904                    res = new ArrayList<PackageParser.Package>();
7905                }
7906                res.add(pkg);
7907                try {
7908                    updateSharedLibrariesLPr(pkg, changingPkg);
7909                } catch (PackageManagerException e) {
7910                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7911                }
7912            }
7913        }
7914        return res;
7915    }
7916
7917    /**
7918     * Derive the value of the {@code cpuAbiOverride} based on the provided
7919     * value and an optional stored value from the package settings.
7920     */
7921    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7922        String cpuAbiOverride = null;
7923
7924        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7925            cpuAbiOverride = null;
7926        } else if (abiOverride != null) {
7927            cpuAbiOverride = abiOverride;
7928        } else if (settings != null) {
7929            cpuAbiOverride = settings.cpuAbiOverrideString;
7930        }
7931
7932        return cpuAbiOverride;
7933    }
7934
7935    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7936            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7937                    throws PackageManagerException {
7938        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7939        // If the package has children and this is the first dive in the function
7940        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7941        // whether all packages (parent and children) would be successfully scanned
7942        // before the actual scan since scanning mutates internal state and we want
7943        // to atomically install the package and its children.
7944        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7945            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7946                scanFlags |= SCAN_CHECK_ONLY;
7947            }
7948        } else {
7949            scanFlags &= ~SCAN_CHECK_ONLY;
7950        }
7951
7952        final PackageParser.Package scannedPkg;
7953        try {
7954            // Scan the parent
7955            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7956            // Scan the children
7957            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7958            for (int i = 0; i < childCount; i++) {
7959                PackageParser.Package childPkg = pkg.childPackages.get(i);
7960                scanPackageLI(childPkg, policyFlags,
7961                        scanFlags, currentTime, user);
7962            }
7963        } finally {
7964            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7965        }
7966
7967        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7968            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7969        }
7970
7971        return scannedPkg;
7972    }
7973
7974    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7975            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7976        boolean success = false;
7977        try {
7978            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7979                    currentTime, user);
7980            success = true;
7981            return res;
7982        } finally {
7983            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7984                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7985                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7986                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7987                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7988            }
7989        }
7990    }
7991
7992    /**
7993     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7994     */
7995    private static boolean apkHasCode(String fileName) {
7996        StrictJarFile jarFile = null;
7997        try {
7998            jarFile = new StrictJarFile(fileName,
7999                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8000            return jarFile.findEntry("classes.dex") != null;
8001        } catch (IOException ignore) {
8002        } finally {
8003            try {
8004                if (jarFile != null) {
8005                    jarFile.close();
8006                }
8007            } catch (IOException ignore) {}
8008        }
8009        return false;
8010    }
8011
8012    /**
8013     * Enforces code policy for the package. This ensures that if an APK has
8014     * declared hasCode="true" in its manifest that the APK actually contains
8015     * code.
8016     *
8017     * @throws PackageManagerException If bytecode could not be found when it should exist
8018     */
8019    private static void assertCodePolicy(PackageParser.Package pkg)
8020            throws PackageManagerException {
8021        final boolean shouldHaveCode =
8022                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8023        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8024            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8025                    "Package " + pkg.baseCodePath + " code is missing");
8026        }
8027
8028        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8029            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8030                final boolean splitShouldHaveCode =
8031                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8032                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8033                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8034                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8035                }
8036            }
8037        }
8038    }
8039
8040    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8041            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8042                    throws PackageManagerException {
8043        if (DEBUG_PACKAGE_SCANNING) {
8044            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8045                Log.d(TAG, "Scanning package " + pkg.packageName);
8046        }
8047
8048        applyPolicy(pkg, policyFlags);
8049
8050        assertPackageIsValid(pkg, policyFlags);
8051
8052        // Initialize package source and resource directories
8053        final File scanFile = new File(pkg.codePath);
8054        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8055        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8056
8057        SharedUserSetting suid = null;
8058        PackageSetting pkgSetting = null;
8059
8060        // Getting the package setting may have a side-effect, so if we
8061        // are only checking if scan would succeed, stash a copy of the
8062        // old setting to restore at the end.
8063        PackageSetting nonMutatedPs = null;
8064
8065        // writer
8066        synchronized (mPackages) {
8067            if (pkg.mSharedUserId != null) {
8068                // SIDE EFFECTS; may potentially allocate a new shared user
8069                suid = mSettings.getSharedUserLPw(
8070                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8071                if (DEBUG_PACKAGE_SCANNING) {
8072                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8073                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8074                                + "): packages=" + suid.packages);
8075                }
8076            }
8077
8078            // Check if we are renaming from an original package name.
8079            PackageSetting origPackage = null;
8080            String realName = null;
8081            if (pkg.mOriginalPackages != null) {
8082                // This package may need to be renamed to a previously
8083                // installed name.  Let's check on that...
8084                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8085                if (pkg.mOriginalPackages.contains(renamed)) {
8086                    // This package had originally been installed as the
8087                    // original name, and we have already taken care of
8088                    // transitioning to the new one.  Just update the new
8089                    // one to continue using the old name.
8090                    realName = pkg.mRealPackage;
8091                    if (!pkg.packageName.equals(renamed)) {
8092                        // Callers into this function may have already taken
8093                        // care of renaming the package; only do it here if
8094                        // it is not already done.
8095                        pkg.setPackageName(renamed);
8096                    }
8097                } else {
8098                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8099                        if ((origPackage = mSettings.peekPackageLPr(
8100                                pkg.mOriginalPackages.get(i))) != null) {
8101                            // We do have the package already installed under its
8102                            // original name...  should we use it?
8103                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8104                                // New package is not compatible with original.
8105                                origPackage = null;
8106                                continue;
8107                            } else if (origPackage.sharedUser != null) {
8108                                // Make sure uid is compatible between packages.
8109                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8110                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8111                                            + " to " + pkg.packageName + ": old uid "
8112                                            + origPackage.sharedUser.name
8113                                            + " differs from " + pkg.mSharedUserId);
8114                                    origPackage = null;
8115                                    continue;
8116                                }
8117                                // TODO: Add case when shared user id is added [b/28144775]
8118                            } else {
8119                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8120                                        + pkg.packageName + " to old name " + origPackage.name);
8121                            }
8122                            break;
8123                        }
8124                    }
8125                }
8126            }
8127
8128            if (mTransferedPackages.contains(pkg.packageName)) {
8129                Slog.w(TAG, "Package " + pkg.packageName
8130                        + " was transferred to another, but its .apk remains");
8131            }
8132
8133            // See comments in nonMutatedPs declaration
8134            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8135                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8136                if (foundPs != null) {
8137                    nonMutatedPs = new PackageSetting(foundPs);
8138                }
8139            }
8140
8141            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8142            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8143                PackageManagerService.reportSettingsProblem(Log.WARN,
8144                        "Package " + pkg.packageName + " shared user changed from "
8145                                + (pkgSetting.sharedUser != null
8146                                        ? pkgSetting.sharedUser.name : "<nothing>")
8147                                + " to "
8148                                + (suid != null ? suid.name : "<nothing>")
8149                                + "; replacing with new");
8150                pkgSetting = null;
8151            }
8152            final PackageSetting oldPkgSetting =
8153                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8154            final PackageSetting disabledPkgSetting =
8155                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8156            if (pkgSetting == null) {
8157                final String parentPackageName = (pkg.parentPackage != null)
8158                        ? pkg.parentPackage.packageName : null;
8159                // REMOVE SharedUserSetting from method; update in a separate call
8160                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8161                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8162                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8163                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8164                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8165                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8166                        UserManagerService.getInstance());
8167                // SIDE EFFECTS; updates system state; move elsewhere
8168                if (origPackage != null) {
8169                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8170                }
8171                mSettings.addUserToSettingLPw(pkgSetting);
8172            } else {
8173                // REMOVE SharedUserSetting from method; update in a separate call
8174                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
8175                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
8176                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
8177                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
8178                        UserManagerService.getInstance());
8179            }
8180            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
8181            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
8182
8183            // SIDE EFFECTS; modifies system state; move elsewhere
8184            if (pkgSetting.origPackage != null) {
8185                // If we are first transitioning from an original package,
8186                // fix up the new package's name now.  We need to do this after
8187                // looking up the package under its new name, so getPackageLP
8188                // can take care of fiddling things correctly.
8189                pkg.setPackageName(origPackage.name);
8190
8191                // File a report about this.
8192                String msg = "New package " + pkgSetting.realName
8193                        + " renamed to replace old package " + pkgSetting.name;
8194                reportSettingsProblem(Log.WARN, msg);
8195
8196                // Make a note of it.
8197                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8198                    mTransferedPackages.add(origPackage.name);
8199                }
8200
8201                // No longer need to retain this.
8202                pkgSetting.origPackage = null;
8203            }
8204
8205            // SIDE EFFECTS; modifies system state; move elsewhere
8206            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8207                // Make a note of it.
8208                mTransferedPackages.add(pkg.packageName);
8209            }
8210
8211            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8212                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8213            }
8214
8215            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8216                // Check all shared libraries and map to their actual file path.
8217                // We only do this here for apps not on a system dir, because those
8218                // are the only ones that can fail an install due to this.  We
8219                // will take care of the system apps by updating all of their
8220                // library paths after the scan is done.
8221                updateSharedLibrariesLPr(pkg, null);
8222            }
8223
8224            if (mFoundPolicyFile) {
8225                SELinuxMMAC.assignSeinfoValue(pkg);
8226            }
8227
8228            pkg.applicationInfo.uid = pkgSetting.appId;
8229            pkg.mExtras = pkgSetting;
8230            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8231                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8232                    // We just determined the app is signed correctly, so bring
8233                    // over the latest parsed certs.
8234                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8235                } else {
8236                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8237                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8238                                "Package " + pkg.packageName + " upgrade keys do not match the "
8239                                + "previously installed version");
8240                    } else {
8241                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8242                        String msg = "System package " + pkg.packageName
8243                                + " signature changed; retaining data.";
8244                        reportSettingsProblem(Log.WARN, msg);
8245                    }
8246                }
8247            } else {
8248                try {
8249                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
8250                    verifySignaturesLP(pkgSetting, pkg);
8251                    // We just determined the app is signed correctly, so bring
8252                    // over the latest parsed certs.
8253                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8254                } catch (PackageManagerException e) {
8255                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8256                        throw e;
8257                    }
8258                    // The signature has changed, but this package is in the system
8259                    // image...  let's recover!
8260                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8261                    // However...  if this package is part of a shared user, but it
8262                    // doesn't match the signature of the shared user, let's fail.
8263                    // What this means is that you can't change the signatures
8264                    // associated with an overall shared user, which doesn't seem all
8265                    // that unreasonable.
8266                    if (pkgSetting.sharedUser != null) {
8267                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8268                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8269                            throw new PackageManagerException(
8270                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8271                                    "Signature mismatch for shared user: "
8272                                            + pkgSetting.sharedUser);
8273                        }
8274                    }
8275                    // File a report about this.
8276                    String msg = "System package " + pkg.packageName
8277                            + " signature changed; retaining data.";
8278                    reportSettingsProblem(Log.WARN, msg);
8279                }
8280            }
8281
8282            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8283                // This package wants to adopt ownership of permissions from
8284                // another package.
8285                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8286                    final String origName = pkg.mAdoptPermissions.get(i);
8287                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8288                    if (orig != null) {
8289                        if (verifyPackageUpdateLPr(orig, pkg)) {
8290                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8291                                    + pkg.packageName);
8292                            // SIDE EFFECTS; updates permissions system state; move elsewhere
8293                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8294                        }
8295                    }
8296                }
8297            }
8298        }
8299
8300        pkg.applicationInfo.processName = fixProcessName(
8301                pkg.applicationInfo.packageName,
8302                pkg.applicationInfo.processName);
8303
8304        if (pkg != mPlatformPackage) {
8305            // Get all of our default paths setup
8306            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8307        }
8308
8309        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8310
8311        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8312            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8313            derivePackageAbi(
8314                    pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
8315            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8316
8317            // Some system apps still use directory structure for native libraries
8318            // in which case we might end up not detecting abi solely based on apk
8319            // structure. Try to detect abi based on directory structure.
8320            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8321                    pkg.applicationInfo.primaryCpuAbi == null) {
8322                setBundledAppAbisAndRoots(pkg, pkgSetting);
8323                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8324            }
8325        } else {
8326            if ((scanFlags & SCAN_MOVE) != 0) {
8327                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8328                // but we already have this packages package info in the PackageSetting. We just
8329                // use that and derive the native library path based on the new codepath.
8330                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8331                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8332            }
8333
8334            // Set native library paths again. For moves, the path will be updated based on the
8335            // ABIs we've determined above. For non-moves, the path will be updated based on the
8336            // ABIs we determined during compilation, but the path will depend on the final
8337            // package path (after the rename away from the stage path).
8338            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8339        }
8340
8341        // This is a special case for the "system" package, where the ABI is
8342        // dictated by the zygote configuration (and init.rc). We should keep track
8343        // of this ABI so that we can deal with "normal" applications that run under
8344        // the same UID correctly.
8345        if (mPlatformPackage == pkg) {
8346            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8347                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8348        }
8349
8350        // If there's a mismatch between the abi-override in the package setting
8351        // and the abiOverride specified for the install. Warn about this because we
8352        // would've already compiled the app without taking the package setting into
8353        // account.
8354        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8355            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8356                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8357                        " for package " + pkg.packageName);
8358            }
8359        }
8360
8361        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8362        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8363        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8364
8365        // Copy the derived override back to the parsed package, so that we can
8366        // update the package settings accordingly.
8367        pkg.cpuAbiOverride = cpuAbiOverride;
8368
8369        if (DEBUG_ABI_SELECTION) {
8370            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8371                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8372                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8373        }
8374
8375        // Push the derived path down into PackageSettings so we know what to
8376        // clean up at uninstall time.
8377        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8378
8379        if (DEBUG_ABI_SELECTION) {
8380            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8381                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8382                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8383        }
8384
8385        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
8386        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8387            // We don't do this here during boot because we can do it all
8388            // at once after scanning all existing packages.
8389            //
8390            // We also do this *before* we perform dexopt on this package, so that
8391            // we can avoid redundant dexopts, and also to make sure we've got the
8392            // code and package path correct.
8393            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
8394        }
8395
8396        if (mFactoryTest && pkg.requestedPermissions.contains(
8397                android.Manifest.permission.FACTORY_TEST)) {
8398            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8399        }
8400
8401        if (isSystemApp(pkg)) {
8402            pkgSetting.isOrphaned = true;
8403        }
8404
8405        // Take care of first install / last update times.
8406        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8407        if (currentTime != 0) {
8408            if (pkgSetting.firstInstallTime == 0) {
8409                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8410            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
8411                pkgSetting.lastUpdateTime = currentTime;
8412            }
8413        } else if (pkgSetting.firstInstallTime == 0) {
8414            // We need *something*.  Take time time stamp of the file.
8415            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8416        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8417            if (scanFileTime != pkgSetting.timeStamp) {
8418                // A package on the system image has changed; consider this
8419                // to be an update.
8420                pkgSetting.lastUpdateTime = scanFileTime;
8421            }
8422        }
8423        pkgSetting.setTimeStamp(scanFileTime);
8424
8425        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8426            if (nonMutatedPs != null) {
8427                synchronized (mPackages) {
8428                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8429                }
8430            }
8431        } else {
8432            // Modify state for the given package setting
8433            commitPackageSettings(pkg, pkgSetting, user, policyFlags,
8434                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
8435        }
8436        return pkg;
8437    }
8438
8439    /**
8440     * Applies policy to the parsed package based upon the given policy flags.
8441     * Ensures the package is in a good state.
8442     * <p>
8443     * Implementation detail: This method must NOT have any side effect. It would
8444     * ideally be static, but, it requires locks to read system state.
8445     */
8446    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
8447        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8448            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8449            if (pkg.applicationInfo.isDirectBootAware()) {
8450                // we're direct boot aware; set for all components
8451                for (PackageParser.Service s : pkg.services) {
8452                    s.info.encryptionAware = s.info.directBootAware = true;
8453                }
8454                for (PackageParser.Provider p : pkg.providers) {
8455                    p.info.encryptionAware = p.info.directBootAware = true;
8456                }
8457                for (PackageParser.Activity a : pkg.activities) {
8458                    a.info.encryptionAware = a.info.directBootAware = true;
8459                }
8460                for (PackageParser.Activity r : pkg.receivers) {
8461                    r.info.encryptionAware = r.info.directBootAware = true;
8462                }
8463            }
8464        } else {
8465            // Only allow system apps to be flagged as core apps.
8466            pkg.coreApp = false;
8467            // clear flags not applicable to regular apps
8468            pkg.applicationInfo.privateFlags &=
8469                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8470            pkg.applicationInfo.privateFlags &=
8471                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8472        }
8473        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8474
8475        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8476            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8477        }
8478
8479        if (!isSystemApp(pkg)) {
8480            // Only system apps can use these features.
8481            pkg.mOriginalPackages = null;
8482            pkg.mRealPackage = null;
8483            pkg.mAdoptPermissions = null;
8484        }
8485    }
8486
8487    /**
8488     * Asserts the parsed package is valid according to teh given policy. If the
8489     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
8490     * <p>
8491     * Implementation detail: This method must NOT have any side effects. It would
8492     * ideally be static, but, it requires locks to read system state.
8493     *
8494     * @throws PackageManagerException If the package fails any of the validation checks
8495     */
8496    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags)
8497            throws PackageManagerException {
8498        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8499            assertCodePolicy(pkg);
8500        }
8501
8502        if (pkg.applicationInfo.getCodePath() == null ||
8503                pkg.applicationInfo.getResourcePath() == null) {
8504            // Bail out. The resource and code paths haven't been set.
8505            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8506                    "Code and resource paths haven't been set correctly");
8507        }
8508
8509        // Make sure we're not adding any bogus keyset info
8510        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8511        ksms.assertScannedPackageValid(pkg);
8512
8513        synchronized (mPackages) {
8514            // The special "android" package can only be defined once
8515            if (pkg.packageName.equals("android")) {
8516                if (mAndroidApplication != null) {
8517                    Slog.w(TAG, "*************************************************");
8518                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8519                    Slog.w(TAG, " codePath=" + pkg.codePath);
8520                    Slog.w(TAG, "*************************************************");
8521                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8522                            "Core android package being redefined.  Skipping.");
8523                }
8524            }
8525
8526            // A package name must be unique; don't allow duplicates
8527            if (mPackages.containsKey(pkg.packageName)
8528                    || mSharedLibraries.containsKey(pkg.packageName)) {
8529                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8530                        "Application package " + pkg.packageName
8531                        + " already installed.  Skipping duplicate.");
8532            }
8533
8534            // Only privileged apps and updated privileged apps can add child packages.
8535            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8536                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8537                    throw new PackageManagerException("Only privileged apps can add child "
8538                            + "packages. Ignoring package " + pkg.packageName);
8539                }
8540                final int childCount = pkg.childPackages.size();
8541                for (int i = 0; i < childCount; i++) {
8542                    PackageParser.Package childPkg = pkg.childPackages.get(i);
8543                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8544                            childPkg.packageName)) {
8545                        throw new PackageManagerException("Can't override child of "
8546                                + "another disabled app. Ignoring package " + pkg.packageName);
8547                    }
8548                }
8549            }
8550
8551            // If we're only installing presumed-existing packages, require that the
8552            // scanned APK is both already known and at the path previously established
8553            // for it.  Previously unknown packages we pick up normally, but if we have an
8554            // a priori expectation about this package's install presence, enforce it.
8555            // With a singular exception for new system packages. When an OTA contains
8556            // a new system package, we allow the codepath to change from a system location
8557            // to the user-installed location. If we don't allow this change, any newer,
8558            // user-installed version of the application will be ignored.
8559            if ((policyFlags & SCAN_REQUIRE_KNOWN) != 0) {
8560                if (mExpectingBetter.containsKey(pkg.packageName)) {
8561                    logCriticalInfo(Log.WARN,
8562                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8563                } else {
8564                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8565                    if (known != null) {
8566                        if (DEBUG_PACKAGE_SCANNING) {
8567                            Log.d(TAG, "Examining " + pkg.codePath
8568                                    + " and requiring known paths " + known.codePathString
8569                                    + " & " + known.resourcePathString);
8570                        }
8571                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8572                                || !pkg.applicationInfo.getResourcePath().equals(
8573                                        known.resourcePathString)) {
8574                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8575                                    "Application package " + pkg.packageName
8576                                    + " found at " + pkg.applicationInfo.getCodePath()
8577                                    + " but expected at " + known.codePathString
8578                                    + "; ignoring.");
8579                        }
8580                    }
8581                }
8582            }
8583
8584            // Verify that this new package doesn't have any content providers
8585            // that conflict with existing packages.  Only do this if the
8586            // package isn't already installed, since we don't want to break
8587            // things that are installed.
8588            if ((policyFlags & SCAN_NEW_INSTALL) != 0) {
8589                final int N = pkg.providers.size();
8590                int i;
8591                for (i=0; i<N; i++) {
8592                    PackageParser.Provider p = pkg.providers.get(i);
8593                    if (p.info.authority != null) {
8594                        String names[] = p.info.authority.split(";");
8595                        for (int j = 0; j < names.length; j++) {
8596                            if (mProvidersByAuthority.containsKey(names[j])) {
8597                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8598                                final String otherPackageName =
8599                                        ((other != null && other.getComponentName() != null) ?
8600                                                other.getComponentName().getPackageName() : "?");
8601                                throw new PackageManagerException(
8602                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8603                                        "Can't install because provider name " + names[j]
8604                                                + " (in package " + pkg.applicationInfo.packageName
8605                                                + ") is already used by " + otherPackageName);
8606                            }
8607                        }
8608                    }
8609                }
8610            }
8611        }
8612    }
8613
8614    /**
8615     * Adds a scanned package to the system. When this method is finished, the package will
8616     * be available for query, resolution, etc...
8617     */
8618    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
8619            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
8620        final String pkgName = pkg.packageName;
8621        if (mCustomResolverComponentName != null &&
8622                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8623            setUpCustomResolverActivity(pkg);
8624        }
8625
8626        if (pkg.packageName.equals("android")) {
8627            synchronized (mPackages) {
8628                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8629                    // Set up information for our fall-back user intent resolution activity.
8630                    mPlatformPackage = pkg;
8631                    pkg.mVersionCode = mSdkVersion;
8632                    mAndroidApplication = pkg.applicationInfo;
8633
8634                    if (!mResolverReplaced) {
8635                        mResolveActivity.applicationInfo = mAndroidApplication;
8636                        mResolveActivity.name = ResolverActivity.class.getName();
8637                        mResolveActivity.packageName = mAndroidApplication.packageName;
8638                        mResolveActivity.processName = "system:ui";
8639                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8640                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8641                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8642                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8643                        mResolveActivity.exported = true;
8644                        mResolveActivity.enabled = true;
8645                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8646                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8647                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8648                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8649                                | ActivityInfo.CONFIG_ORIENTATION
8650                                | ActivityInfo.CONFIG_KEYBOARD
8651                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8652                        mResolveInfo.activityInfo = mResolveActivity;
8653                        mResolveInfo.priority = 0;
8654                        mResolveInfo.preferredOrder = 0;
8655                        mResolveInfo.match = 0;
8656                        mResolveComponentName = new ComponentName(
8657                                mAndroidApplication.packageName, mResolveActivity.name);
8658                    }
8659                }
8660            }
8661        }
8662
8663        ArrayList<PackageParser.Package> clientLibPkgs = null;
8664        // writer
8665        synchronized (mPackages) {
8666            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8667                // Only system apps can add new shared libraries.
8668                if (pkg.libraryNames != null) {
8669                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8670                        String name = pkg.libraryNames.get(i);
8671                        boolean allowed = false;
8672                        if (pkg.isUpdatedSystemApp()) {
8673                            // New library entries can only be added through the
8674                            // system image.  This is important to get rid of a lot
8675                            // of nasty edge cases: for example if we allowed a non-
8676                            // system update of the app to add a library, then uninstalling
8677                            // the update would make the library go away, and assumptions
8678                            // we made such as through app install filtering would now
8679                            // have allowed apps on the device which aren't compatible
8680                            // with it.  Better to just have the restriction here, be
8681                            // conservative, and create many fewer cases that can negatively
8682                            // impact the user experience.
8683                            final PackageSetting sysPs = mSettings
8684                                    .getDisabledSystemPkgLPr(pkg.packageName);
8685                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8686                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8687                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8688                                        allowed = true;
8689                                        break;
8690                                    }
8691                                }
8692                            }
8693                        } else {
8694                            allowed = true;
8695                        }
8696                        if (allowed) {
8697                            if (!mSharedLibraries.containsKey(name)) {
8698                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8699                            } else if (!name.equals(pkg.packageName)) {
8700                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8701                                        + name + " already exists; skipping");
8702                            }
8703                        } else {
8704                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8705                                    + name + " that is not declared on system image; skipping");
8706                        }
8707                    }
8708                    if ((scanFlags & SCAN_BOOTING) == 0) {
8709                        // If we are not booting, we need to update any applications
8710                        // that are clients of our shared library.  If we are booting,
8711                        // this will all be done once the scan is complete.
8712                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8713                    }
8714                }
8715            }
8716        }
8717
8718        if ((scanFlags & SCAN_BOOTING) != 0) {
8719            // No apps can run during boot scan, so they don't need to be frozen
8720        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8721            // Caller asked to not kill app, so it's probably not frozen
8722        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8723            // Caller asked us to ignore frozen check for some reason; they
8724            // probably didn't know the package name
8725        } else {
8726            // We're doing major surgery on this package, so it better be frozen
8727            // right now to keep it from launching
8728            checkPackageFrozen(pkgName);
8729        }
8730
8731        // Also need to kill any apps that are dependent on the library.
8732        if (clientLibPkgs != null) {
8733            for (int i=0; i<clientLibPkgs.size(); i++) {
8734                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8735                killApplication(clientPkg.applicationInfo.packageName,
8736                        clientPkg.applicationInfo.uid, "update lib");
8737            }
8738        }
8739
8740        // writer
8741        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8742
8743        boolean createIdmapFailed = false;
8744        synchronized (mPackages) {
8745            // We don't expect installation to fail beyond this point
8746
8747            if (pkgSetting.pkg != null) {
8748                // Note that |user| might be null during the initial boot scan. If a codePath
8749                // for an app has changed during a boot scan, it's due to an app update that's
8750                // part of the system partition and marker changes must be applied to all users.
8751                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
8752                final int[] userIds = resolveUserIds(userId);
8753                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
8754            }
8755
8756            // Add the new setting to mSettings
8757            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8758            // Add the new setting to mPackages
8759            mPackages.put(pkg.applicationInfo.packageName, pkg);
8760            // Make sure we don't accidentally delete its data.
8761            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8762            while (iter.hasNext()) {
8763                PackageCleanItem item = iter.next();
8764                if (pkgName.equals(item.packageName)) {
8765                    iter.remove();
8766                }
8767            }
8768
8769            // Add the package's KeySets to the global KeySetManagerService
8770            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8771            ksms.addScannedPackageLPw(pkg);
8772
8773            int N = pkg.providers.size();
8774            StringBuilder r = null;
8775            int i;
8776            for (i=0; i<N; i++) {
8777                PackageParser.Provider p = pkg.providers.get(i);
8778                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8779                        p.info.processName);
8780                mProviders.addProvider(p);
8781                p.syncable = p.info.isSyncable;
8782                if (p.info.authority != null) {
8783                    String names[] = p.info.authority.split(";");
8784                    p.info.authority = null;
8785                    for (int j = 0; j < names.length; j++) {
8786                        if (j == 1 && p.syncable) {
8787                            // We only want the first authority for a provider to possibly be
8788                            // syncable, so if we already added this provider using a different
8789                            // authority clear the syncable flag. We copy the provider before
8790                            // changing it because the mProviders object contains a reference
8791                            // to a provider that we don't want to change.
8792                            // Only do this for the second authority since the resulting provider
8793                            // object can be the same for all future authorities for this provider.
8794                            p = new PackageParser.Provider(p);
8795                            p.syncable = false;
8796                        }
8797                        if (!mProvidersByAuthority.containsKey(names[j])) {
8798                            mProvidersByAuthority.put(names[j], p);
8799                            if (p.info.authority == null) {
8800                                p.info.authority = names[j];
8801                            } else {
8802                                p.info.authority = p.info.authority + ";" + names[j];
8803                            }
8804                            if (DEBUG_PACKAGE_SCANNING) {
8805                                if (chatty)
8806                                    Log.d(TAG, "Registered content provider: " + names[j]
8807                                            + ", className = " + p.info.name + ", isSyncable = "
8808                                            + p.info.isSyncable);
8809                            }
8810                        } else {
8811                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8812                            Slog.w(TAG, "Skipping provider name " + names[j] +
8813                                    " (in package " + pkg.applicationInfo.packageName +
8814                                    "): name already used by "
8815                                    + ((other != null && other.getComponentName() != null)
8816                                            ? other.getComponentName().getPackageName() : "?"));
8817                        }
8818                    }
8819                }
8820                if (chatty) {
8821                    if (r == null) {
8822                        r = new StringBuilder(256);
8823                    } else {
8824                        r.append(' ');
8825                    }
8826                    r.append(p.info.name);
8827                }
8828            }
8829            if (r != null) {
8830                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8831            }
8832
8833            N = pkg.services.size();
8834            r = null;
8835            for (i=0; i<N; i++) {
8836                PackageParser.Service s = pkg.services.get(i);
8837                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8838                        s.info.processName);
8839                mServices.addService(s);
8840                if (chatty) {
8841                    if (r == null) {
8842                        r = new StringBuilder(256);
8843                    } else {
8844                        r.append(' ');
8845                    }
8846                    r.append(s.info.name);
8847                }
8848            }
8849            if (r != null) {
8850                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8851            }
8852
8853            N = pkg.receivers.size();
8854            r = null;
8855            for (i=0; i<N; i++) {
8856                PackageParser.Activity a = pkg.receivers.get(i);
8857                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8858                        a.info.processName);
8859                mReceivers.addActivity(a, "receiver");
8860                if (chatty) {
8861                    if (r == null) {
8862                        r = new StringBuilder(256);
8863                    } else {
8864                        r.append(' ');
8865                    }
8866                    r.append(a.info.name);
8867                }
8868            }
8869            if (r != null) {
8870                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8871            }
8872
8873            N = pkg.activities.size();
8874            r = null;
8875            for (i=0; i<N; i++) {
8876                PackageParser.Activity a = pkg.activities.get(i);
8877                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8878                        a.info.processName);
8879                mActivities.addActivity(a, "activity");
8880                if (chatty) {
8881                    if (r == null) {
8882                        r = new StringBuilder(256);
8883                    } else {
8884                        r.append(' ');
8885                    }
8886                    r.append(a.info.name);
8887                }
8888            }
8889            if (r != null) {
8890                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8891            }
8892
8893            N = pkg.permissionGroups.size();
8894            r = null;
8895            for (i=0; i<N; i++) {
8896                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8897                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8898                final String curPackageName = cur == null ? null : cur.info.packageName;
8899                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8900                if (cur == null || isPackageUpdate) {
8901                    mPermissionGroups.put(pg.info.name, pg);
8902                    if (chatty) {
8903                        if (r == null) {
8904                            r = new StringBuilder(256);
8905                        } else {
8906                            r.append(' ');
8907                        }
8908                        if (isPackageUpdate) {
8909                            r.append("UPD:");
8910                        }
8911                        r.append(pg.info.name);
8912                    }
8913                } else {
8914                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8915                            + pg.info.packageName + " ignored: original from "
8916                            + cur.info.packageName);
8917                    if (chatty) {
8918                        if (r == null) {
8919                            r = new StringBuilder(256);
8920                        } else {
8921                            r.append(' ');
8922                        }
8923                        r.append("DUP:");
8924                        r.append(pg.info.name);
8925                    }
8926                }
8927            }
8928            if (r != null) {
8929                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8930            }
8931
8932            N = pkg.permissions.size();
8933            r = null;
8934            for (i=0; i<N; i++) {
8935                PackageParser.Permission p = pkg.permissions.get(i);
8936
8937                // Assume by default that we did not install this permission into the system.
8938                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8939
8940                // Now that permission groups have a special meaning, we ignore permission
8941                // groups for legacy apps to prevent unexpected behavior. In particular,
8942                // permissions for one app being granted to someone just becase they happen
8943                // to be in a group defined by another app (before this had no implications).
8944                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8945                    p.group = mPermissionGroups.get(p.info.group);
8946                    // Warn for a permission in an unknown group.
8947                    if (p.info.group != null && p.group == null) {
8948                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8949                                + p.info.packageName + " in an unknown group " + p.info.group);
8950                    }
8951                }
8952
8953                ArrayMap<String, BasePermission> permissionMap =
8954                        p.tree ? mSettings.mPermissionTrees
8955                                : mSettings.mPermissions;
8956                BasePermission bp = permissionMap.get(p.info.name);
8957
8958                // Allow system apps to redefine non-system permissions
8959                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8960                    final boolean currentOwnerIsSystem = (bp.perm != null
8961                            && isSystemApp(bp.perm.owner));
8962                    if (isSystemApp(p.owner)) {
8963                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8964                            // It's a built-in permission and no owner, take ownership now
8965                            bp.packageSetting = pkgSetting;
8966                            bp.perm = p;
8967                            bp.uid = pkg.applicationInfo.uid;
8968                            bp.sourcePackage = p.info.packageName;
8969                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8970                        } else if (!currentOwnerIsSystem) {
8971                            String msg = "New decl " + p.owner + " of permission  "
8972                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8973                            reportSettingsProblem(Log.WARN, msg);
8974                            bp = null;
8975                        }
8976                    }
8977                }
8978
8979                if (bp == null) {
8980                    bp = new BasePermission(p.info.name, p.info.packageName,
8981                            BasePermission.TYPE_NORMAL);
8982                    permissionMap.put(p.info.name, bp);
8983                }
8984
8985                if (bp.perm == null) {
8986                    if (bp.sourcePackage == null
8987                            || bp.sourcePackage.equals(p.info.packageName)) {
8988                        BasePermission tree = findPermissionTreeLP(p.info.name);
8989                        if (tree == null
8990                                || tree.sourcePackage.equals(p.info.packageName)) {
8991                            bp.packageSetting = pkgSetting;
8992                            bp.perm = p;
8993                            bp.uid = pkg.applicationInfo.uid;
8994                            bp.sourcePackage = p.info.packageName;
8995                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8996                            if (chatty) {
8997                                if (r == null) {
8998                                    r = new StringBuilder(256);
8999                                } else {
9000                                    r.append(' ');
9001                                }
9002                                r.append(p.info.name);
9003                            }
9004                        } else {
9005                            Slog.w(TAG, "Permission " + p.info.name + " from package "
9006                                    + p.info.packageName + " ignored: base tree "
9007                                    + tree.name + " is from package "
9008                                    + tree.sourcePackage);
9009                        }
9010                    } else {
9011                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9012                                + p.info.packageName + " ignored: original from "
9013                                + bp.sourcePackage);
9014                    }
9015                } else if (chatty) {
9016                    if (r == null) {
9017                        r = new StringBuilder(256);
9018                    } else {
9019                        r.append(' ');
9020                    }
9021                    r.append("DUP:");
9022                    r.append(p.info.name);
9023                }
9024                if (bp.perm == p) {
9025                    bp.protectionLevel = p.info.protectionLevel;
9026                }
9027            }
9028
9029            if (r != null) {
9030                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
9031            }
9032
9033            N = pkg.instrumentation.size();
9034            r = null;
9035            for (i=0; i<N; i++) {
9036                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9037                a.info.packageName = pkg.applicationInfo.packageName;
9038                a.info.sourceDir = pkg.applicationInfo.sourceDir;
9039                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9040                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9041                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9042                a.info.dataDir = pkg.applicationInfo.dataDir;
9043                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9044                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9045                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9046                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9047                mInstrumentation.put(a.getComponentName(), a);
9048                if (chatty) {
9049                    if (r == null) {
9050                        r = new StringBuilder(256);
9051                    } else {
9052                        r.append(' ');
9053                    }
9054                    r.append(a.info.name);
9055                }
9056            }
9057            if (r != null) {
9058                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9059            }
9060
9061            if (pkg.protectedBroadcasts != null) {
9062                N = pkg.protectedBroadcasts.size();
9063                for (i=0; i<N; i++) {
9064                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9065                }
9066            }
9067
9068            // Create idmap files for pairs of (packages, overlay packages).
9069            // Note: "android", ie framework-res.apk, is handled by native layers.
9070            if (pkg.mOverlayTarget != null) {
9071                // This is an overlay package.
9072                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9073                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9074                        mOverlays.put(pkg.mOverlayTarget,
9075                                new ArrayMap<String, PackageParser.Package>());
9076                    }
9077                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9078                    map.put(pkg.packageName, pkg);
9079                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9080                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9081                        createIdmapFailed = true;
9082                    }
9083                }
9084            } else if (mOverlays.containsKey(pkg.packageName) &&
9085                    !pkg.packageName.equals("android")) {
9086                // This is a regular package, with one or more known overlay packages.
9087                createIdmapsForPackageLI(pkg);
9088            }
9089        }
9090
9091        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9092
9093        if (createIdmapFailed) {
9094            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9095                    "scanPackageLI failed to createIdmap");
9096        }
9097    }
9098
9099    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9100            PackageParser.Package update, int[] userIds) {
9101        if (existing.applicationInfo == null || update.applicationInfo == null) {
9102            // This isn't due to an app installation.
9103            return;
9104        }
9105
9106        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9107        final File newCodePath = new File(update.applicationInfo.getCodePath());
9108
9109        // The codePath hasn't changed, so there's nothing for us to do.
9110        if (Objects.equals(oldCodePath, newCodePath)) {
9111            return;
9112        }
9113
9114        File canonicalNewCodePath;
9115        try {
9116            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9117        } catch (IOException e) {
9118            Slog.w(TAG, "Failed to get canonical path.", e);
9119            return;
9120        }
9121
9122        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9123        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9124        // that the last component of the path (i.e, the name) doesn't need canonicalization
9125        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9126        // but may change in the future. Hopefully this function won't exist at that point.
9127        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9128                oldCodePath.getName());
9129
9130        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9131        // with "@".
9132        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9133        if (!oldMarkerPrefix.endsWith("@")) {
9134            oldMarkerPrefix += "@";
9135        }
9136        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9137        if (!newMarkerPrefix.endsWith("@")) {
9138            newMarkerPrefix += "@";
9139        }
9140
9141        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9142        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9143        for (String updatedPath : updatedPaths) {
9144            String updatedPathName = new File(updatedPath).getName();
9145            markerSuffixes.add(updatedPathName.replace('/', '@'));
9146        }
9147
9148        for (int userId : userIds) {
9149            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9150
9151            for (String markerSuffix : markerSuffixes) {
9152                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9153                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9154                if (oldForeignUseMark.exists()) {
9155                    try {
9156                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9157                                newForeignUseMark.getAbsolutePath());
9158                    } catch (ErrnoException e) {
9159                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9160                        oldForeignUseMark.delete();
9161                    }
9162                }
9163            }
9164        }
9165    }
9166
9167    /**
9168     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9169     * is derived purely on the basis of the contents of {@code scanFile} and
9170     * {@code cpuAbiOverride}.
9171     *
9172     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9173     */
9174    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9175                                 String cpuAbiOverride, boolean extractLibs,
9176                                 File appLib32InstallDir)
9177            throws PackageManagerException {
9178        // TODO: We can probably be smarter about this stuff. For installed apps,
9179        // we can calculate this information at install time once and for all. For
9180        // system apps, we can probably assume that this information doesn't change
9181        // after the first boot scan. As things stand, we do lots of unnecessary work.
9182
9183        // Give ourselves some initial paths; we'll come back for another
9184        // pass once we've determined ABI below.
9185        setNativeLibraryPaths(pkg, appLib32InstallDir);
9186
9187        // We would never need to extract libs for forward-locked and external packages,
9188        // since the container service will do it for us. We shouldn't attempt to
9189        // extract libs from system app when it was not updated.
9190        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9191                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9192            extractLibs = false;
9193        }
9194
9195        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9196        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9197
9198        NativeLibraryHelper.Handle handle = null;
9199        try {
9200            handle = NativeLibraryHelper.Handle.create(pkg);
9201            // TODO(multiArch): This can be null for apps that didn't go through the
9202            // usual installation process. We can calculate it again, like we
9203            // do during install time.
9204            //
9205            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9206            // unnecessary.
9207            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9208
9209            // Null out the abis so that they can be recalculated.
9210            pkg.applicationInfo.primaryCpuAbi = null;
9211            pkg.applicationInfo.secondaryCpuAbi = null;
9212            if (isMultiArch(pkg.applicationInfo)) {
9213                // Warn if we've set an abiOverride for multi-lib packages..
9214                // By definition, we need to copy both 32 and 64 bit libraries for
9215                // such packages.
9216                if (pkg.cpuAbiOverride != null
9217                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9218                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9219                }
9220
9221                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9222                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9223                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9224                    if (extractLibs) {
9225                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9226                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9227                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9228                                useIsaSpecificSubdirs);
9229                    } else {
9230                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9231                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9232                    }
9233                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9234                }
9235
9236                maybeThrowExceptionForMultiArchCopy(
9237                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9238
9239                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9240                    if (extractLibs) {
9241                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9242                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9243                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9244                                useIsaSpecificSubdirs);
9245                    } else {
9246                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9247                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9248                    }
9249                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9250                }
9251
9252                maybeThrowExceptionForMultiArchCopy(
9253                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9254
9255                if (abi64 >= 0) {
9256                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9257                }
9258
9259                if (abi32 >= 0) {
9260                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9261                    if (abi64 >= 0) {
9262                        if (pkg.use32bitAbi) {
9263                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9264                            pkg.applicationInfo.primaryCpuAbi = abi;
9265                        } else {
9266                            pkg.applicationInfo.secondaryCpuAbi = abi;
9267                        }
9268                    } else {
9269                        pkg.applicationInfo.primaryCpuAbi = abi;
9270                    }
9271                }
9272
9273            } else {
9274                String[] abiList = (cpuAbiOverride != null) ?
9275                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9276
9277                // Enable gross and lame hacks for apps that are built with old
9278                // SDK tools. We must scan their APKs for renderscript bitcode and
9279                // not launch them if it's present. Don't bother checking on devices
9280                // that don't have 64 bit support.
9281                boolean needsRenderScriptOverride = false;
9282                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9283                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9284                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9285                    needsRenderScriptOverride = true;
9286                }
9287
9288                final int copyRet;
9289                if (extractLibs) {
9290                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9291                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9292                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9293                } else {
9294                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9295                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9296                }
9297                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9298
9299                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9300                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9301                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9302                }
9303
9304                if (copyRet >= 0) {
9305                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9306                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9307                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9308                } else if (needsRenderScriptOverride) {
9309                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9310                }
9311            }
9312        } catch (IOException ioe) {
9313            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9314        } finally {
9315            IoUtils.closeQuietly(handle);
9316        }
9317
9318        // Now that we've calculated the ABIs and determined if it's an internal app,
9319        // we will go ahead and populate the nativeLibraryPath.
9320        setNativeLibraryPaths(pkg, appLib32InstallDir);
9321    }
9322
9323    /**
9324     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9325     * i.e, so that all packages can be run inside a single process if required.
9326     *
9327     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9328     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9329     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9330     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9331     * updating a package that belongs to a shared user.
9332     *
9333     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9334     * adds unnecessary complexity.
9335     */
9336    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9337            PackageParser.Package scannedPackage) {
9338        String requiredInstructionSet = null;
9339        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9340            requiredInstructionSet = VMRuntime.getInstructionSet(
9341                     scannedPackage.applicationInfo.primaryCpuAbi);
9342        }
9343
9344        PackageSetting requirer = null;
9345        for (PackageSetting ps : packagesForUser) {
9346            // If packagesForUser contains scannedPackage, we skip it. This will happen
9347            // when scannedPackage is an update of an existing package. Without this check,
9348            // we will never be able to change the ABI of any package belonging to a shared
9349            // user, even if it's compatible with other packages.
9350            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9351                if (ps.primaryCpuAbiString == null) {
9352                    continue;
9353                }
9354
9355                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9356                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9357                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9358                    // this but there's not much we can do.
9359                    String errorMessage = "Instruction set mismatch, "
9360                            + ((requirer == null) ? "[caller]" : requirer)
9361                            + " requires " + requiredInstructionSet + " whereas " + ps
9362                            + " requires " + instructionSet;
9363                    Slog.w(TAG, errorMessage);
9364                }
9365
9366                if (requiredInstructionSet == null) {
9367                    requiredInstructionSet = instructionSet;
9368                    requirer = ps;
9369                }
9370            }
9371        }
9372
9373        if (requiredInstructionSet != null) {
9374            String adjustedAbi;
9375            if (requirer != null) {
9376                // requirer != null implies that either scannedPackage was null or that scannedPackage
9377                // did not require an ABI, in which case we have to adjust scannedPackage to match
9378                // the ABI of the set (which is the same as requirer's ABI)
9379                adjustedAbi = requirer.primaryCpuAbiString;
9380                if (scannedPackage != null) {
9381                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9382                }
9383            } else {
9384                // requirer == null implies that we're updating all ABIs in the set to
9385                // match scannedPackage.
9386                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9387            }
9388
9389            for (PackageSetting ps : packagesForUser) {
9390                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9391                    if (ps.primaryCpuAbiString != null) {
9392                        continue;
9393                    }
9394
9395                    ps.primaryCpuAbiString = adjustedAbi;
9396                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9397                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9398                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9399                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9400                                + " (requirer="
9401                                + (requirer == null ? "null" : requirer.pkg.packageName)
9402                                + ", scannedPackage="
9403                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9404                                + ")");
9405                        try {
9406                            mInstaller.rmdex(ps.codePathString,
9407                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9408                        } catch (InstallerException ignored) {
9409                        }
9410                    }
9411                }
9412            }
9413        }
9414    }
9415
9416    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9417        synchronized (mPackages) {
9418            mResolverReplaced = true;
9419            // Set up information for custom user intent resolution activity.
9420            mResolveActivity.applicationInfo = pkg.applicationInfo;
9421            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9422            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9423            mResolveActivity.processName = pkg.applicationInfo.packageName;
9424            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9425            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9426                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9427            mResolveActivity.theme = 0;
9428            mResolveActivity.exported = true;
9429            mResolveActivity.enabled = true;
9430            mResolveInfo.activityInfo = mResolveActivity;
9431            mResolveInfo.priority = 0;
9432            mResolveInfo.preferredOrder = 0;
9433            mResolveInfo.match = 0;
9434            mResolveComponentName = mCustomResolverComponentName;
9435            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9436                    mResolveComponentName);
9437        }
9438    }
9439
9440    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9441        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9442
9443        // Set up information for ephemeral installer activity
9444        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9445        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9446        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9447        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9448        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9449        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9450                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9451        mEphemeralInstallerActivity.theme = 0;
9452        mEphemeralInstallerActivity.exported = true;
9453        mEphemeralInstallerActivity.enabled = true;
9454        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9455        mEphemeralInstallerInfo.priority = 0;
9456        mEphemeralInstallerInfo.preferredOrder = 1;
9457        mEphemeralInstallerInfo.isDefault = true;
9458        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9459                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9460
9461        if (DEBUG_EPHEMERAL) {
9462            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9463        }
9464    }
9465
9466    private static String calculateBundledApkRoot(final String codePathString) {
9467        final File codePath = new File(codePathString);
9468        final File codeRoot;
9469        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9470            codeRoot = Environment.getRootDirectory();
9471        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9472            codeRoot = Environment.getOemDirectory();
9473        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9474            codeRoot = Environment.getVendorDirectory();
9475        } else {
9476            // Unrecognized code path; take its top real segment as the apk root:
9477            // e.g. /something/app/blah.apk => /something
9478            try {
9479                File f = codePath.getCanonicalFile();
9480                File parent = f.getParentFile();    // non-null because codePath is a file
9481                File tmp;
9482                while ((tmp = parent.getParentFile()) != null) {
9483                    f = parent;
9484                    parent = tmp;
9485                }
9486                codeRoot = f;
9487                Slog.w(TAG, "Unrecognized code path "
9488                        + codePath + " - using " + codeRoot);
9489            } catch (IOException e) {
9490                // Can't canonicalize the code path -- shenanigans?
9491                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9492                return Environment.getRootDirectory().getPath();
9493            }
9494        }
9495        return codeRoot.getPath();
9496    }
9497
9498    /**
9499     * Derive and set the location of native libraries for the given package,
9500     * which varies depending on where and how the package was installed.
9501     */
9502    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
9503        final ApplicationInfo info = pkg.applicationInfo;
9504        final String codePath = pkg.codePath;
9505        final File codeFile = new File(codePath);
9506        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9507        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9508
9509        info.nativeLibraryRootDir = null;
9510        info.nativeLibraryRootRequiresIsa = false;
9511        info.nativeLibraryDir = null;
9512        info.secondaryNativeLibraryDir = null;
9513
9514        if (isApkFile(codeFile)) {
9515            // Monolithic install
9516            if (bundledApp) {
9517                // If "/system/lib64/apkname" exists, assume that is the per-package
9518                // native library directory to use; otherwise use "/system/lib/apkname".
9519                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9520                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9521                        getPrimaryInstructionSet(info));
9522
9523                // This is a bundled system app so choose the path based on the ABI.
9524                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9525                // is just the default path.
9526                final String apkName = deriveCodePathName(codePath);
9527                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9528                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9529                        apkName).getAbsolutePath();
9530
9531                if (info.secondaryCpuAbi != null) {
9532                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9533                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9534                            secondaryLibDir, apkName).getAbsolutePath();
9535                }
9536            } else if (asecApp) {
9537                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9538                        .getAbsolutePath();
9539            } else {
9540                final String apkName = deriveCodePathName(codePath);
9541                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
9542                        .getAbsolutePath();
9543            }
9544
9545            info.nativeLibraryRootRequiresIsa = false;
9546            info.nativeLibraryDir = info.nativeLibraryRootDir;
9547        } else {
9548            // Cluster install
9549            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9550            info.nativeLibraryRootRequiresIsa = true;
9551
9552            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9553                    getPrimaryInstructionSet(info)).getAbsolutePath();
9554
9555            if (info.secondaryCpuAbi != null) {
9556                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9557                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9558            }
9559        }
9560    }
9561
9562    /**
9563     * Calculate the abis and roots for a bundled app. These can uniquely
9564     * be determined from the contents of the system partition, i.e whether
9565     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9566     * of this information, and instead assume that the system was built
9567     * sensibly.
9568     */
9569    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9570                                           PackageSetting pkgSetting) {
9571        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9572
9573        // If "/system/lib64/apkname" exists, assume that is the per-package
9574        // native library directory to use; otherwise use "/system/lib/apkname".
9575        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9576        setBundledAppAbi(pkg, apkRoot, apkName);
9577        // pkgSetting might be null during rescan following uninstall of updates
9578        // to a bundled app, so accommodate that possibility.  The settings in
9579        // that case will be established later from the parsed package.
9580        //
9581        // If the settings aren't null, sync them up with what we've just derived.
9582        // note that apkRoot isn't stored in the package settings.
9583        if (pkgSetting != null) {
9584            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9585            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9586        }
9587    }
9588
9589    /**
9590     * Deduces the ABI of a bundled app and sets the relevant fields on the
9591     * parsed pkg object.
9592     *
9593     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9594     *        under which system libraries are installed.
9595     * @param apkName the name of the installed package.
9596     */
9597    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9598        final File codeFile = new File(pkg.codePath);
9599
9600        final boolean has64BitLibs;
9601        final boolean has32BitLibs;
9602        if (isApkFile(codeFile)) {
9603            // Monolithic install
9604            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9605            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9606        } else {
9607            // Cluster install
9608            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9609            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9610                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9611                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9612                has64BitLibs = (new File(rootDir, isa)).exists();
9613            } else {
9614                has64BitLibs = false;
9615            }
9616            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9617                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9618                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9619                has32BitLibs = (new File(rootDir, isa)).exists();
9620            } else {
9621                has32BitLibs = false;
9622            }
9623        }
9624
9625        if (has64BitLibs && !has32BitLibs) {
9626            // The package has 64 bit libs, but not 32 bit libs. Its primary
9627            // ABI should be 64 bit. We can safely assume here that the bundled
9628            // native libraries correspond to the most preferred ABI in the list.
9629
9630            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9631            pkg.applicationInfo.secondaryCpuAbi = null;
9632        } else if (has32BitLibs && !has64BitLibs) {
9633            // The package has 32 bit libs but not 64 bit libs. Its primary
9634            // ABI should be 32 bit.
9635
9636            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9637            pkg.applicationInfo.secondaryCpuAbi = null;
9638        } else if (has32BitLibs && has64BitLibs) {
9639            // The application has both 64 and 32 bit bundled libraries. We check
9640            // here that the app declares multiArch support, and warn if it doesn't.
9641            //
9642            // We will be lenient here and record both ABIs. The primary will be the
9643            // ABI that's higher on the list, i.e, a device that's configured to prefer
9644            // 64 bit apps will see a 64 bit primary ABI,
9645
9646            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9647                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9648            }
9649
9650            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9651                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9652                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9653            } else {
9654                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9655                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9656            }
9657        } else {
9658            pkg.applicationInfo.primaryCpuAbi = null;
9659            pkg.applicationInfo.secondaryCpuAbi = null;
9660        }
9661    }
9662
9663    private void killApplication(String pkgName, int appId, String reason) {
9664        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9665    }
9666
9667    private void killApplication(String pkgName, int appId, int userId, String reason) {
9668        // Request the ActivityManager to kill the process(only for existing packages)
9669        // so that we do not end up in a confused state while the user is still using the older
9670        // version of the application while the new one gets installed.
9671        final long token = Binder.clearCallingIdentity();
9672        try {
9673            IActivityManager am = ActivityManagerNative.getDefault();
9674            if (am != null) {
9675                try {
9676                    am.killApplication(pkgName, appId, userId, reason);
9677                } catch (RemoteException e) {
9678                }
9679            }
9680        } finally {
9681            Binder.restoreCallingIdentity(token);
9682        }
9683    }
9684
9685    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9686        // Remove the parent package setting
9687        PackageSetting ps = (PackageSetting) pkg.mExtras;
9688        if (ps != null) {
9689            removePackageLI(ps, chatty);
9690        }
9691        // Remove the child package setting
9692        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9693        for (int i = 0; i < childCount; i++) {
9694            PackageParser.Package childPkg = pkg.childPackages.get(i);
9695            ps = (PackageSetting) childPkg.mExtras;
9696            if (ps != null) {
9697                removePackageLI(ps, chatty);
9698            }
9699        }
9700    }
9701
9702    void removePackageLI(PackageSetting ps, boolean chatty) {
9703        if (DEBUG_INSTALL) {
9704            if (chatty)
9705                Log.d(TAG, "Removing package " + ps.name);
9706        }
9707
9708        // writer
9709        synchronized (mPackages) {
9710            mPackages.remove(ps.name);
9711            final PackageParser.Package pkg = ps.pkg;
9712            if (pkg != null) {
9713                cleanPackageDataStructuresLILPw(pkg, chatty);
9714            }
9715        }
9716    }
9717
9718    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9719        if (DEBUG_INSTALL) {
9720            if (chatty)
9721                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9722        }
9723
9724        // writer
9725        synchronized (mPackages) {
9726            // Remove the parent package
9727            mPackages.remove(pkg.applicationInfo.packageName);
9728            cleanPackageDataStructuresLILPw(pkg, chatty);
9729
9730            // Remove the child packages
9731            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9732            for (int i = 0; i < childCount; i++) {
9733                PackageParser.Package childPkg = pkg.childPackages.get(i);
9734                mPackages.remove(childPkg.applicationInfo.packageName);
9735                cleanPackageDataStructuresLILPw(childPkg, chatty);
9736            }
9737        }
9738    }
9739
9740    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9741        int N = pkg.providers.size();
9742        StringBuilder r = null;
9743        int i;
9744        for (i=0; i<N; i++) {
9745            PackageParser.Provider p = pkg.providers.get(i);
9746            mProviders.removeProvider(p);
9747            if (p.info.authority == null) {
9748
9749                /* There was another ContentProvider with this authority when
9750                 * this app was installed so this authority is null,
9751                 * Ignore it as we don't have to unregister the provider.
9752                 */
9753                continue;
9754            }
9755            String names[] = p.info.authority.split(";");
9756            for (int j = 0; j < names.length; j++) {
9757                if (mProvidersByAuthority.get(names[j]) == p) {
9758                    mProvidersByAuthority.remove(names[j]);
9759                    if (DEBUG_REMOVE) {
9760                        if (chatty)
9761                            Log.d(TAG, "Unregistered content provider: " + names[j]
9762                                    + ", className = " + p.info.name + ", isSyncable = "
9763                                    + p.info.isSyncable);
9764                    }
9765                }
9766            }
9767            if (DEBUG_REMOVE && chatty) {
9768                if (r == null) {
9769                    r = new StringBuilder(256);
9770                } else {
9771                    r.append(' ');
9772                }
9773                r.append(p.info.name);
9774            }
9775        }
9776        if (r != null) {
9777            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9778        }
9779
9780        N = pkg.services.size();
9781        r = null;
9782        for (i=0; i<N; i++) {
9783            PackageParser.Service s = pkg.services.get(i);
9784            mServices.removeService(s);
9785            if (chatty) {
9786                if (r == null) {
9787                    r = new StringBuilder(256);
9788                } else {
9789                    r.append(' ');
9790                }
9791                r.append(s.info.name);
9792            }
9793        }
9794        if (r != null) {
9795            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9796        }
9797
9798        N = pkg.receivers.size();
9799        r = null;
9800        for (i=0; i<N; i++) {
9801            PackageParser.Activity a = pkg.receivers.get(i);
9802            mReceivers.removeActivity(a, "receiver");
9803            if (DEBUG_REMOVE && chatty) {
9804                if (r == null) {
9805                    r = new StringBuilder(256);
9806                } else {
9807                    r.append(' ');
9808                }
9809                r.append(a.info.name);
9810            }
9811        }
9812        if (r != null) {
9813            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9814        }
9815
9816        N = pkg.activities.size();
9817        r = null;
9818        for (i=0; i<N; i++) {
9819            PackageParser.Activity a = pkg.activities.get(i);
9820            mActivities.removeActivity(a, "activity");
9821            if (DEBUG_REMOVE && chatty) {
9822                if (r == null) {
9823                    r = new StringBuilder(256);
9824                } else {
9825                    r.append(' ');
9826                }
9827                r.append(a.info.name);
9828            }
9829        }
9830        if (r != null) {
9831            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9832        }
9833
9834        N = pkg.permissions.size();
9835        r = null;
9836        for (i=0; i<N; i++) {
9837            PackageParser.Permission p = pkg.permissions.get(i);
9838            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9839            if (bp == null) {
9840                bp = mSettings.mPermissionTrees.get(p.info.name);
9841            }
9842            if (bp != null && bp.perm == p) {
9843                bp.perm = null;
9844                if (DEBUG_REMOVE && chatty) {
9845                    if (r == null) {
9846                        r = new StringBuilder(256);
9847                    } else {
9848                        r.append(' ');
9849                    }
9850                    r.append(p.info.name);
9851                }
9852            }
9853            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9854                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9855                if (appOpPkgs != null) {
9856                    appOpPkgs.remove(pkg.packageName);
9857                }
9858            }
9859        }
9860        if (r != null) {
9861            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9862        }
9863
9864        N = pkg.requestedPermissions.size();
9865        r = null;
9866        for (i=0; i<N; i++) {
9867            String perm = pkg.requestedPermissions.get(i);
9868            BasePermission bp = mSettings.mPermissions.get(perm);
9869            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9870                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9871                if (appOpPkgs != null) {
9872                    appOpPkgs.remove(pkg.packageName);
9873                    if (appOpPkgs.isEmpty()) {
9874                        mAppOpPermissionPackages.remove(perm);
9875                    }
9876                }
9877            }
9878        }
9879        if (r != null) {
9880            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9881        }
9882
9883        N = pkg.instrumentation.size();
9884        r = null;
9885        for (i=0; i<N; i++) {
9886            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9887            mInstrumentation.remove(a.getComponentName());
9888            if (DEBUG_REMOVE && chatty) {
9889                if (r == null) {
9890                    r = new StringBuilder(256);
9891                } else {
9892                    r.append(' ');
9893                }
9894                r.append(a.info.name);
9895            }
9896        }
9897        if (r != null) {
9898            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9899        }
9900
9901        r = null;
9902        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9903            // Only system apps can hold shared libraries.
9904            if (pkg.libraryNames != null) {
9905                for (i=0; i<pkg.libraryNames.size(); i++) {
9906                    String name = pkg.libraryNames.get(i);
9907                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9908                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9909                        mSharedLibraries.remove(name);
9910                        if (DEBUG_REMOVE && chatty) {
9911                            if (r == null) {
9912                                r = new StringBuilder(256);
9913                            } else {
9914                                r.append(' ');
9915                            }
9916                            r.append(name);
9917                        }
9918                    }
9919                }
9920            }
9921        }
9922        if (r != null) {
9923            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9924        }
9925    }
9926
9927    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9928        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9929            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9930                return true;
9931            }
9932        }
9933        return false;
9934    }
9935
9936    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9937    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9938    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9939
9940    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9941        // Update the parent permissions
9942        updatePermissionsLPw(pkg.packageName, pkg, flags);
9943        // Update the child permissions
9944        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9945        for (int i = 0; i < childCount; i++) {
9946            PackageParser.Package childPkg = pkg.childPackages.get(i);
9947            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9948        }
9949    }
9950
9951    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9952            int flags) {
9953        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9954        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9955    }
9956
9957    private void updatePermissionsLPw(String changingPkg,
9958            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9959        // Make sure there are no dangling permission trees.
9960        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9961        while (it.hasNext()) {
9962            final BasePermission bp = it.next();
9963            if (bp.packageSetting == null) {
9964                // We may not yet have parsed the package, so just see if
9965                // we still know about its settings.
9966                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9967            }
9968            if (bp.packageSetting == null) {
9969                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9970                        + " from package " + bp.sourcePackage);
9971                it.remove();
9972            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9973                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9974                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9975                            + " from package " + bp.sourcePackage);
9976                    flags |= UPDATE_PERMISSIONS_ALL;
9977                    it.remove();
9978                }
9979            }
9980        }
9981
9982        // Make sure all dynamic permissions have been assigned to a package,
9983        // and make sure there are no dangling permissions.
9984        it = mSettings.mPermissions.values().iterator();
9985        while (it.hasNext()) {
9986            final BasePermission bp = it.next();
9987            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9988                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9989                        + bp.name + " pkg=" + bp.sourcePackage
9990                        + " info=" + bp.pendingInfo);
9991                if (bp.packageSetting == null && bp.pendingInfo != null) {
9992                    final BasePermission tree = findPermissionTreeLP(bp.name);
9993                    if (tree != null && tree.perm != null) {
9994                        bp.packageSetting = tree.packageSetting;
9995                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9996                                new PermissionInfo(bp.pendingInfo));
9997                        bp.perm.info.packageName = tree.perm.info.packageName;
9998                        bp.perm.info.name = bp.name;
9999                        bp.uid = tree.uid;
10000                    }
10001                }
10002            }
10003            if (bp.packageSetting == null) {
10004                // We may not yet have parsed the package, so just see if
10005                // we still know about its settings.
10006                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10007            }
10008            if (bp.packageSetting == null) {
10009                Slog.w(TAG, "Removing dangling permission: " + bp.name
10010                        + " from package " + bp.sourcePackage);
10011                it.remove();
10012            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10013                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10014                    Slog.i(TAG, "Removing old permission: " + bp.name
10015                            + " from package " + bp.sourcePackage);
10016                    flags |= UPDATE_PERMISSIONS_ALL;
10017                    it.remove();
10018                }
10019            }
10020        }
10021
10022        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10023        // Now update the permissions for all packages, in particular
10024        // replace the granted permissions of the system packages.
10025        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10026            for (PackageParser.Package pkg : mPackages.values()) {
10027                if (pkg != pkgInfo) {
10028                    // Only replace for packages on requested volume
10029                    final String volumeUuid = getVolumeUuidForPackage(pkg);
10030                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10031                            && Objects.equals(replaceVolumeUuid, volumeUuid);
10032                    grantPermissionsLPw(pkg, replace, changingPkg);
10033                }
10034            }
10035        }
10036
10037        if (pkgInfo != null) {
10038            // Only replace for packages on requested volume
10039            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10040            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10041                    && Objects.equals(replaceVolumeUuid, volumeUuid);
10042            grantPermissionsLPw(pkgInfo, replace, changingPkg);
10043        }
10044        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10045    }
10046
10047    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10048            String packageOfInterest) {
10049        // IMPORTANT: There are two types of permissions: install and runtime.
10050        // Install time permissions are granted when the app is installed to
10051        // all device users and users added in the future. Runtime permissions
10052        // are granted at runtime explicitly to specific users. Normal and signature
10053        // protected permissions are install time permissions. Dangerous permissions
10054        // are install permissions if the app's target SDK is Lollipop MR1 or older,
10055        // otherwise they are runtime permissions. This function does not manage
10056        // runtime permissions except for the case an app targeting Lollipop MR1
10057        // being upgraded to target a newer SDK, in which case dangerous permissions
10058        // are transformed from install time to runtime ones.
10059
10060        final PackageSetting ps = (PackageSetting) pkg.mExtras;
10061        if (ps == null) {
10062            return;
10063        }
10064
10065        PermissionsState permissionsState = ps.getPermissionsState();
10066        PermissionsState origPermissions = permissionsState;
10067
10068        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10069
10070        boolean runtimePermissionsRevoked = false;
10071        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10072
10073        boolean changedInstallPermission = false;
10074
10075        if (replace) {
10076            ps.installPermissionsFixed = false;
10077            if (!ps.isSharedUser()) {
10078                origPermissions = new PermissionsState(permissionsState);
10079                permissionsState.reset();
10080            } else {
10081                // We need to know only about runtime permission changes since the
10082                // calling code always writes the install permissions state but
10083                // the runtime ones are written only if changed. The only cases of
10084                // changed runtime permissions here are promotion of an install to
10085                // runtime and revocation of a runtime from a shared user.
10086                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10087                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10088                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10089                    runtimePermissionsRevoked = true;
10090                }
10091            }
10092        }
10093
10094        permissionsState.setGlobalGids(mGlobalGids);
10095
10096        final int N = pkg.requestedPermissions.size();
10097        for (int i=0; i<N; i++) {
10098            final String name = pkg.requestedPermissions.get(i);
10099            final BasePermission bp = mSettings.mPermissions.get(name);
10100
10101            if (DEBUG_INSTALL) {
10102                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10103            }
10104
10105            if (bp == null || bp.packageSetting == null) {
10106                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10107                    Slog.w(TAG, "Unknown permission " + name
10108                            + " in package " + pkg.packageName);
10109                }
10110                continue;
10111            }
10112
10113            final String perm = bp.name;
10114            boolean allowedSig = false;
10115            int grant = GRANT_DENIED;
10116
10117            // Keep track of app op permissions.
10118            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10119                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10120                if (pkgs == null) {
10121                    pkgs = new ArraySet<>();
10122                    mAppOpPermissionPackages.put(bp.name, pkgs);
10123                }
10124                pkgs.add(pkg.packageName);
10125            }
10126
10127            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10128            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10129                    >= Build.VERSION_CODES.M;
10130            switch (level) {
10131                case PermissionInfo.PROTECTION_NORMAL: {
10132                    // For all apps normal permissions are install time ones.
10133                    grant = GRANT_INSTALL;
10134                } break;
10135
10136                case PermissionInfo.PROTECTION_DANGEROUS: {
10137                    // If a permission review is required for legacy apps we represent
10138                    // their permissions as always granted runtime ones since we need
10139                    // to keep the review required permission flag per user while an
10140                    // install permission's state is shared across all users.
10141                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
10142                        // For legacy apps dangerous permissions are install time ones.
10143                        grant = GRANT_INSTALL;
10144                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10145                        // For legacy apps that became modern, install becomes runtime.
10146                        grant = GRANT_UPGRADE;
10147                    } else if (mPromoteSystemApps
10148                            && isSystemApp(ps)
10149                            && mExistingSystemPackages.contains(ps.name)) {
10150                        // For legacy system apps, install becomes runtime.
10151                        // We cannot check hasInstallPermission() for system apps since those
10152                        // permissions were granted implicitly and not persisted pre-M.
10153                        grant = GRANT_UPGRADE;
10154                    } else {
10155                        // For modern apps keep runtime permissions unchanged.
10156                        grant = GRANT_RUNTIME;
10157                    }
10158                } break;
10159
10160                case PermissionInfo.PROTECTION_SIGNATURE: {
10161                    // For all apps signature permissions are install time ones.
10162                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10163                    if (allowedSig) {
10164                        grant = GRANT_INSTALL;
10165                    }
10166                } break;
10167            }
10168
10169            if (DEBUG_INSTALL) {
10170                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10171            }
10172
10173            if (grant != GRANT_DENIED) {
10174                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10175                    // If this is an existing, non-system package, then
10176                    // we can't add any new permissions to it.
10177                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10178                        // Except...  if this is a permission that was added
10179                        // to the platform (note: need to only do this when
10180                        // updating the platform).
10181                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10182                            grant = GRANT_DENIED;
10183                        }
10184                    }
10185                }
10186
10187                switch (grant) {
10188                    case GRANT_INSTALL: {
10189                        // Revoke this as runtime permission to handle the case of
10190                        // a runtime permission being downgraded to an install one.
10191                        // Also in permission review mode we keep dangerous permissions
10192                        // for legacy apps
10193                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10194                            if (origPermissions.getRuntimePermissionState(
10195                                    bp.name, userId) != null) {
10196                                // Revoke the runtime permission and clear the flags.
10197                                origPermissions.revokeRuntimePermission(bp, userId);
10198                                origPermissions.updatePermissionFlags(bp, userId,
10199                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10200                                // If we revoked a permission permission, we have to write.
10201                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10202                                        changedRuntimePermissionUserIds, userId);
10203                            }
10204                        }
10205                        // Grant an install permission.
10206                        if (permissionsState.grantInstallPermission(bp) !=
10207                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10208                            changedInstallPermission = true;
10209                        }
10210                    } break;
10211
10212                    case GRANT_RUNTIME: {
10213                        // Grant previously granted runtime permissions.
10214                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10215                            PermissionState permissionState = origPermissions
10216                                    .getRuntimePermissionState(bp.name, userId);
10217                            int flags = permissionState != null
10218                                    ? permissionState.getFlags() : 0;
10219                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10220                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10221                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10222                                    // If we cannot put the permission as it was, we have to write.
10223                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10224                                            changedRuntimePermissionUserIds, userId);
10225                                }
10226                                // If the app supports runtime permissions no need for a review.
10227                                if (mPermissionReviewRequired
10228                                        && appSupportsRuntimePermissions
10229                                        && (flags & PackageManager
10230                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10231                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10232                                    // Since we changed the flags, we have to write.
10233                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10234                                            changedRuntimePermissionUserIds, userId);
10235                                }
10236                            } else if (mPermissionReviewRequired
10237                                    && !appSupportsRuntimePermissions) {
10238                                // For legacy apps that need a permission review, every new
10239                                // runtime permission is granted but it is pending a review.
10240                                // We also need to review only platform defined runtime
10241                                // permissions as these are the only ones the platform knows
10242                                // how to disable the API to simulate revocation as legacy
10243                                // apps don't expect to run with revoked permissions.
10244                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10245                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10246                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10247                                        // We changed the flags, hence have to write.
10248                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10249                                                changedRuntimePermissionUserIds, userId);
10250                                    }
10251                                }
10252                                if (permissionsState.grantRuntimePermission(bp, userId)
10253                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10254                                    // We changed the permission, hence have to write.
10255                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10256                                            changedRuntimePermissionUserIds, userId);
10257                                }
10258                            }
10259                            // Propagate the permission flags.
10260                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10261                        }
10262                    } break;
10263
10264                    case GRANT_UPGRADE: {
10265                        // Grant runtime permissions for a previously held install permission.
10266                        PermissionState permissionState = origPermissions
10267                                .getInstallPermissionState(bp.name);
10268                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10269
10270                        if (origPermissions.revokeInstallPermission(bp)
10271                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10272                            // We will be transferring the permission flags, so clear them.
10273                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10274                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10275                            changedInstallPermission = true;
10276                        }
10277
10278                        // If the permission is not to be promoted to runtime we ignore it and
10279                        // also its other flags as they are not applicable to install permissions.
10280                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10281                            for (int userId : currentUserIds) {
10282                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10283                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10284                                    // Transfer the permission flags.
10285                                    permissionsState.updatePermissionFlags(bp, userId,
10286                                            flags, flags);
10287                                    // If we granted the permission, we have to write.
10288                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10289                                            changedRuntimePermissionUserIds, userId);
10290                                }
10291                            }
10292                        }
10293                    } break;
10294
10295                    default: {
10296                        if (packageOfInterest == null
10297                                || packageOfInterest.equals(pkg.packageName)) {
10298                            Slog.w(TAG, "Not granting permission " + perm
10299                                    + " to package " + pkg.packageName
10300                                    + " because it was previously installed without");
10301                        }
10302                    } break;
10303                }
10304            } else {
10305                if (permissionsState.revokeInstallPermission(bp) !=
10306                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10307                    // Also drop the permission flags.
10308                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10309                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10310                    changedInstallPermission = true;
10311                    Slog.i(TAG, "Un-granting permission " + perm
10312                            + " from package " + pkg.packageName
10313                            + " (protectionLevel=" + bp.protectionLevel
10314                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10315                            + ")");
10316                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10317                    // Don't print warning for app op permissions, since it is fine for them
10318                    // not to be granted, there is a UI for the user to decide.
10319                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10320                        Slog.w(TAG, "Not granting permission " + perm
10321                                + " to package " + pkg.packageName
10322                                + " (protectionLevel=" + bp.protectionLevel
10323                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10324                                + ")");
10325                    }
10326                }
10327            }
10328        }
10329
10330        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10331                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10332            // This is the first that we have heard about this package, so the
10333            // permissions we have now selected are fixed until explicitly
10334            // changed.
10335            ps.installPermissionsFixed = true;
10336        }
10337
10338        // Persist the runtime permissions state for users with changes. If permissions
10339        // were revoked because no app in the shared user declares them we have to
10340        // write synchronously to avoid losing runtime permissions state.
10341        for (int userId : changedRuntimePermissionUserIds) {
10342            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10343        }
10344    }
10345
10346    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10347        boolean allowed = false;
10348        final int NP = PackageParser.NEW_PERMISSIONS.length;
10349        for (int ip=0; ip<NP; ip++) {
10350            final PackageParser.NewPermissionInfo npi
10351                    = PackageParser.NEW_PERMISSIONS[ip];
10352            if (npi.name.equals(perm)
10353                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10354                allowed = true;
10355                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10356                        + pkg.packageName);
10357                break;
10358            }
10359        }
10360        return allowed;
10361    }
10362
10363    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10364            BasePermission bp, PermissionsState origPermissions) {
10365        boolean allowed;
10366        allowed = (compareSignatures(
10367                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10368                        == PackageManager.SIGNATURE_MATCH)
10369                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10370                        == PackageManager.SIGNATURE_MATCH);
10371        if (!allowed && (bp.protectionLevel
10372                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10373            if (isSystemApp(pkg)) {
10374                // For updated system applications, a system permission
10375                // is granted only if it had been defined by the original application.
10376                if (pkg.isUpdatedSystemApp()) {
10377                    final PackageSetting sysPs = mSettings
10378                            .getDisabledSystemPkgLPr(pkg.packageName);
10379                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10380                        // If the original was granted this permission, we take
10381                        // that grant decision as read and propagate it to the
10382                        // update.
10383                        if (sysPs.isPrivileged()) {
10384                            allowed = true;
10385                        }
10386                    } else {
10387                        // The system apk may have been updated with an older
10388                        // version of the one on the data partition, but which
10389                        // granted a new system permission that it didn't have
10390                        // before.  In this case we do want to allow the app to
10391                        // now get the new permission if the ancestral apk is
10392                        // privileged to get it.
10393                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10394                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10395                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10396                                    allowed = true;
10397                                    break;
10398                                }
10399                            }
10400                        }
10401                        // Also if a privileged parent package on the system image or any of
10402                        // its children requested a privileged permission, the updated child
10403                        // packages can also get the permission.
10404                        if (pkg.parentPackage != null) {
10405                            final PackageSetting disabledSysParentPs = mSettings
10406                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10407                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10408                                    && disabledSysParentPs.isPrivileged()) {
10409                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10410                                    allowed = true;
10411                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10412                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10413                                    for (int i = 0; i < count; i++) {
10414                                        PackageParser.Package disabledSysChildPkg =
10415                                                disabledSysParentPs.pkg.childPackages.get(i);
10416                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10417                                                perm)) {
10418                                            allowed = true;
10419                                            break;
10420                                        }
10421                                    }
10422                                }
10423                            }
10424                        }
10425                    }
10426                } else {
10427                    allowed = isPrivilegedApp(pkg);
10428                }
10429            }
10430        }
10431        if (!allowed) {
10432            if (!allowed && (bp.protectionLevel
10433                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10434                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10435                // If this was a previously normal/dangerous permission that got moved
10436                // to a system permission as part of the runtime permission redesign, then
10437                // we still want to blindly grant it to old apps.
10438                allowed = true;
10439            }
10440            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10441                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10442                // If this permission is to be granted to the system installer and
10443                // this app is an installer, then it gets the permission.
10444                allowed = true;
10445            }
10446            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10447                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10448                // If this permission is to be granted to the system verifier and
10449                // this app is a verifier, then it gets the permission.
10450                allowed = true;
10451            }
10452            if (!allowed && (bp.protectionLevel
10453                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10454                    && isSystemApp(pkg)) {
10455                // Any pre-installed system app is allowed to get this permission.
10456                allowed = true;
10457            }
10458            if (!allowed && (bp.protectionLevel
10459                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10460                // For development permissions, a development permission
10461                // is granted only if it was already granted.
10462                allowed = origPermissions.hasInstallPermission(perm);
10463            }
10464            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10465                    && pkg.packageName.equals(mSetupWizardPackage)) {
10466                // If this permission is to be granted to the system setup wizard and
10467                // this app is a setup wizard, then it gets the permission.
10468                allowed = true;
10469            }
10470        }
10471        return allowed;
10472    }
10473
10474    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10475        final int permCount = pkg.requestedPermissions.size();
10476        for (int j = 0; j < permCount; j++) {
10477            String requestedPermission = pkg.requestedPermissions.get(j);
10478            if (permission.equals(requestedPermission)) {
10479                return true;
10480            }
10481        }
10482        return false;
10483    }
10484
10485    final class ActivityIntentResolver
10486            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10487        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10488                boolean defaultOnly, int userId) {
10489            if (!sUserManager.exists(userId)) return null;
10490            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10491            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10492        }
10493
10494        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10495                int userId) {
10496            if (!sUserManager.exists(userId)) return null;
10497            mFlags = flags;
10498            return super.queryIntent(intent, resolvedType,
10499                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10500        }
10501
10502        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10503                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10504            if (!sUserManager.exists(userId)) return null;
10505            if (packageActivities == null) {
10506                return null;
10507            }
10508            mFlags = flags;
10509            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10510            final int N = packageActivities.size();
10511            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10512                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10513
10514            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10515            for (int i = 0; i < N; ++i) {
10516                intentFilters = packageActivities.get(i).intents;
10517                if (intentFilters != null && intentFilters.size() > 0) {
10518                    PackageParser.ActivityIntentInfo[] array =
10519                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10520                    intentFilters.toArray(array);
10521                    listCut.add(array);
10522                }
10523            }
10524            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10525        }
10526
10527        /**
10528         * Finds a privileged activity that matches the specified activity names.
10529         */
10530        private PackageParser.Activity findMatchingActivity(
10531                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10532            for (PackageParser.Activity sysActivity : activityList) {
10533                if (sysActivity.info.name.equals(activityInfo.name)) {
10534                    return sysActivity;
10535                }
10536                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10537                    return sysActivity;
10538                }
10539                if (sysActivity.info.targetActivity != null) {
10540                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10541                        return sysActivity;
10542                    }
10543                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10544                        return sysActivity;
10545                    }
10546                }
10547            }
10548            return null;
10549        }
10550
10551        public class IterGenerator<E> {
10552            public Iterator<E> generate(ActivityIntentInfo info) {
10553                return null;
10554            }
10555        }
10556
10557        public class ActionIterGenerator extends IterGenerator<String> {
10558            @Override
10559            public Iterator<String> generate(ActivityIntentInfo info) {
10560                return info.actionsIterator();
10561            }
10562        }
10563
10564        public class CategoriesIterGenerator extends IterGenerator<String> {
10565            @Override
10566            public Iterator<String> generate(ActivityIntentInfo info) {
10567                return info.categoriesIterator();
10568            }
10569        }
10570
10571        public class SchemesIterGenerator extends IterGenerator<String> {
10572            @Override
10573            public Iterator<String> generate(ActivityIntentInfo info) {
10574                return info.schemesIterator();
10575            }
10576        }
10577
10578        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10579            @Override
10580            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10581                return info.authoritiesIterator();
10582            }
10583        }
10584
10585        /**
10586         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10587         * MODIFIED. Do not pass in a list that should not be changed.
10588         */
10589        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10590                IterGenerator<T> generator, Iterator<T> searchIterator) {
10591            // loop through the set of actions; every one must be found in the intent filter
10592            while (searchIterator.hasNext()) {
10593                // we must have at least one filter in the list to consider a match
10594                if (intentList.size() == 0) {
10595                    break;
10596                }
10597
10598                final T searchAction = searchIterator.next();
10599
10600                // loop through the set of intent filters
10601                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10602                while (intentIter.hasNext()) {
10603                    final ActivityIntentInfo intentInfo = intentIter.next();
10604                    boolean selectionFound = false;
10605
10606                    // loop through the intent filter's selection criteria; at least one
10607                    // of them must match the searched criteria
10608                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10609                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10610                        final T intentSelection = intentSelectionIter.next();
10611                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10612                            selectionFound = true;
10613                            break;
10614                        }
10615                    }
10616
10617                    // the selection criteria wasn't found in this filter's set; this filter
10618                    // is not a potential match
10619                    if (!selectionFound) {
10620                        intentIter.remove();
10621                    }
10622                }
10623            }
10624        }
10625
10626        private boolean isProtectedAction(ActivityIntentInfo filter) {
10627            final Iterator<String> actionsIter = filter.actionsIterator();
10628            while (actionsIter != null && actionsIter.hasNext()) {
10629                final String filterAction = actionsIter.next();
10630                if (PROTECTED_ACTIONS.contains(filterAction)) {
10631                    return true;
10632                }
10633            }
10634            return false;
10635        }
10636
10637        /**
10638         * Adjusts the priority of the given intent filter according to policy.
10639         * <p>
10640         * <ul>
10641         * <li>The priority for non privileged applications is capped to '0'</li>
10642         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10643         * <li>The priority for unbundled updates to privileged applications is capped to the
10644         *      priority defined on the system partition</li>
10645         * </ul>
10646         * <p>
10647         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10648         * allowed to obtain any priority on any action.
10649         */
10650        private void adjustPriority(
10651                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10652            // nothing to do; priority is fine as-is
10653            if (intent.getPriority() <= 0) {
10654                return;
10655            }
10656
10657            final ActivityInfo activityInfo = intent.activity.info;
10658            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10659
10660            final boolean privilegedApp =
10661                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10662            if (!privilegedApp) {
10663                // non-privileged applications can never define a priority >0
10664                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10665                        + " package: " + applicationInfo.packageName
10666                        + " activity: " + intent.activity.className
10667                        + " origPrio: " + intent.getPriority());
10668                intent.setPriority(0);
10669                return;
10670            }
10671
10672            if (systemActivities == null) {
10673                // the system package is not disabled; we're parsing the system partition
10674                if (isProtectedAction(intent)) {
10675                    if (mDeferProtectedFilters) {
10676                        // We can't deal with these just yet. No component should ever obtain a
10677                        // >0 priority for a protected actions, with ONE exception -- the setup
10678                        // wizard. The setup wizard, however, cannot be known until we're able to
10679                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10680                        // until all intent filters have been processed. Chicken, meet egg.
10681                        // Let the filter temporarily have a high priority and rectify the
10682                        // priorities after all system packages have been scanned.
10683                        mProtectedFilters.add(intent);
10684                        if (DEBUG_FILTERS) {
10685                            Slog.i(TAG, "Protected action; save for later;"
10686                                    + " package: " + applicationInfo.packageName
10687                                    + " activity: " + intent.activity.className
10688                                    + " origPrio: " + intent.getPriority());
10689                        }
10690                        return;
10691                    } else {
10692                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10693                            Slog.i(TAG, "No setup wizard;"
10694                                + " All protected intents capped to priority 0");
10695                        }
10696                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10697                            if (DEBUG_FILTERS) {
10698                                Slog.i(TAG, "Found setup wizard;"
10699                                    + " allow priority " + intent.getPriority() + ";"
10700                                    + " package: " + intent.activity.info.packageName
10701                                    + " activity: " + intent.activity.className
10702                                    + " priority: " + intent.getPriority());
10703                            }
10704                            // setup wizard gets whatever it wants
10705                            return;
10706                        }
10707                        Slog.w(TAG, "Protected action; cap priority to 0;"
10708                                + " package: " + intent.activity.info.packageName
10709                                + " activity: " + intent.activity.className
10710                                + " origPrio: " + intent.getPriority());
10711                        intent.setPriority(0);
10712                        return;
10713                    }
10714                }
10715                // privileged apps on the system image get whatever priority they request
10716                return;
10717            }
10718
10719            // privileged app unbundled update ... try to find the same activity
10720            final PackageParser.Activity foundActivity =
10721                    findMatchingActivity(systemActivities, activityInfo);
10722            if (foundActivity == null) {
10723                // this is a new activity; it cannot obtain >0 priority
10724                if (DEBUG_FILTERS) {
10725                    Slog.i(TAG, "New activity; cap priority to 0;"
10726                            + " package: " + applicationInfo.packageName
10727                            + " activity: " + intent.activity.className
10728                            + " origPrio: " + intent.getPriority());
10729                }
10730                intent.setPriority(0);
10731                return;
10732            }
10733
10734            // found activity, now check for filter equivalence
10735
10736            // a shallow copy is enough; we modify the list, not its contents
10737            final List<ActivityIntentInfo> intentListCopy =
10738                    new ArrayList<>(foundActivity.intents);
10739            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10740
10741            // find matching action subsets
10742            final Iterator<String> actionsIterator = intent.actionsIterator();
10743            if (actionsIterator != null) {
10744                getIntentListSubset(
10745                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10746                if (intentListCopy.size() == 0) {
10747                    // no more intents to match; we're not equivalent
10748                    if (DEBUG_FILTERS) {
10749                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10750                                + " package: " + applicationInfo.packageName
10751                                + " activity: " + intent.activity.className
10752                                + " origPrio: " + intent.getPriority());
10753                    }
10754                    intent.setPriority(0);
10755                    return;
10756                }
10757            }
10758
10759            // find matching category subsets
10760            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10761            if (categoriesIterator != null) {
10762                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10763                        categoriesIterator);
10764                if (intentListCopy.size() == 0) {
10765                    // no more intents to match; we're not equivalent
10766                    if (DEBUG_FILTERS) {
10767                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10768                                + " package: " + applicationInfo.packageName
10769                                + " activity: " + intent.activity.className
10770                                + " origPrio: " + intent.getPriority());
10771                    }
10772                    intent.setPriority(0);
10773                    return;
10774                }
10775            }
10776
10777            // find matching schemes subsets
10778            final Iterator<String> schemesIterator = intent.schemesIterator();
10779            if (schemesIterator != null) {
10780                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10781                        schemesIterator);
10782                if (intentListCopy.size() == 0) {
10783                    // no more intents to match; we're not equivalent
10784                    if (DEBUG_FILTERS) {
10785                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10786                                + " package: " + applicationInfo.packageName
10787                                + " activity: " + intent.activity.className
10788                                + " origPrio: " + intent.getPriority());
10789                    }
10790                    intent.setPriority(0);
10791                    return;
10792                }
10793            }
10794
10795            // find matching authorities subsets
10796            final Iterator<IntentFilter.AuthorityEntry>
10797                    authoritiesIterator = intent.authoritiesIterator();
10798            if (authoritiesIterator != null) {
10799                getIntentListSubset(intentListCopy,
10800                        new AuthoritiesIterGenerator(),
10801                        authoritiesIterator);
10802                if (intentListCopy.size() == 0) {
10803                    // no more intents to match; we're not equivalent
10804                    if (DEBUG_FILTERS) {
10805                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10806                                + " package: " + applicationInfo.packageName
10807                                + " activity: " + intent.activity.className
10808                                + " origPrio: " + intent.getPriority());
10809                    }
10810                    intent.setPriority(0);
10811                    return;
10812                }
10813            }
10814
10815            // we found matching filter(s); app gets the max priority of all intents
10816            int cappedPriority = 0;
10817            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10818                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10819            }
10820            if (intent.getPriority() > cappedPriority) {
10821                if (DEBUG_FILTERS) {
10822                    Slog.i(TAG, "Found matching filter(s);"
10823                            + " cap priority to " + cappedPriority + ";"
10824                            + " package: " + applicationInfo.packageName
10825                            + " activity: " + intent.activity.className
10826                            + " origPrio: " + intent.getPriority());
10827                }
10828                intent.setPriority(cappedPriority);
10829                return;
10830            }
10831            // all this for nothing; the requested priority was <= what was on the system
10832        }
10833
10834        public final void addActivity(PackageParser.Activity a, String type) {
10835            mActivities.put(a.getComponentName(), a);
10836            if (DEBUG_SHOW_INFO)
10837                Log.v(
10838                TAG, "  " + type + " " +
10839                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10840            if (DEBUG_SHOW_INFO)
10841                Log.v(TAG, "    Class=" + a.info.name);
10842            final int NI = a.intents.size();
10843            for (int j=0; j<NI; j++) {
10844                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10845                if ("activity".equals(type)) {
10846                    final PackageSetting ps =
10847                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10848                    final List<PackageParser.Activity> systemActivities =
10849                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10850                    adjustPriority(systemActivities, intent);
10851                }
10852                if (DEBUG_SHOW_INFO) {
10853                    Log.v(TAG, "    IntentFilter:");
10854                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10855                }
10856                if (!intent.debugCheck()) {
10857                    Log.w(TAG, "==> For Activity " + a.info.name);
10858                }
10859                addFilter(intent);
10860            }
10861        }
10862
10863        public final void removeActivity(PackageParser.Activity a, String type) {
10864            mActivities.remove(a.getComponentName());
10865            if (DEBUG_SHOW_INFO) {
10866                Log.v(TAG, "  " + type + " "
10867                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10868                                : a.info.name) + ":");
10869                Log.v(TAG, "    Class=" + a.info.name);
10870            }
10871            final int NI = a.intents.size();
10872            for (int j=0; j<NI; j++) {
10873                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10874                if (DEBUG_SHOW_INFO) {
10875                    Log.v(TAG, "    IntentFilter:");
10876                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10877                }
10878                removeFilter(intent);
10879            }
10880        }
10881
10882        @Override
10883        protected boolean allowFilterResult(
10884                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10885            ActivityInfo filterAi = filter.activity.info;
10886            for (int i=dest.size()-1; i>=0; i--) {
10887                ActivityInfo destAi = dest.get(i).activityInfo;
10888                if (destAi.name == filterAi.name
10889                        && destAi.packageName == filterAi.packageName) {
10890                    return false;
10891                }
10892            }
10893            return true;
10894        }
10895
10896        @Override
10897        protected ActivityIntentInfo[] newArray(int size) {
10898            return new ActivityIntentInfo[size];
10899        }
10900
10901        @Override
10902        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10903            if (!sUserManager.exists(userId)) return true;
10904            PackageParser.Package p = filter.activity.owner;
10905            if (p != null) {
10906                PackageSetting ps = (PackageSetting)p.mExtras;
10907                if (ps != null) {
10908                    // System apps are never considered stopped for purposes of
10909                    // filtering, because there may be no way for the user to
10910                    // actually re-launch them.
10911                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10912                            && ps.getStopped(userId);
10913                }
10914            }
10915            return false;
10916        }
10917
10918        @Override
10919        protected boolean isPackageForFilter(String packageName,
10920                PackageParser.ActivityIntentInfo info) {
10921            return packageName.equals(info.activity.owner.packageName);
10922        }
10923
10924        @Override
10925        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10926                int match, int userId) {
10927            if (!sUserManager.exists(userId)) return null;
10928            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10929                return null;
10930            }
10931            final PackageParser.Activity activity = info.activity;
10932            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10933            if (ps == null) {
10934                return null;
10935            }
10936            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10937                    ps.readUserState(userId), userId);
10938            if (ai == null) {
10939                return null;
10940            }
10941            final ResolveInfo res = new ResolveInfo();
10942            res.activityInfo = ai;
10943            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10944                res.filter = info;
10945            }
10946            if (info != null) {
10947                res.handleAllWebDataURI = info.handleAllWebDataURI();
10948            }
10949            res.priority = info.getPriority();
10950            res.preferredOrder = activity.owner.mPreferredOrder;
10951            //System.out.println("Result: " + res.activityInfo.className +
10952            //                   " = " + res.priority);
10953            res.match = match;
10954            res.isDefault = info.hasDefault;
10955            res.labelRes = info.labelRes;
10956            res.nonLocalizedLabel = info.nonLocalizedLabel;
10957            if (userNeedsBadging(userId)) {
10958                res.noResourceId = true;
10959            } else {
10960                res.icon = info.icon;
10961            }
10962            res.iconResourceId = info.icon;
10963            res.system = res.activityInfo.applicationInfo.isSystemApp();
10964            return res;
10965        }
10966
10967        @Override
10968        protected void sortResults(List<ResolveInfo> results) {
10969            Collections.sort(results, mResolvePrioritySorter);
10970        }
10971
10972        @Override
10973        protected void dumpFilter(PrintWriter out, String prefix,
10974                PackageParser.ActivityIntentInfo filter) {
10975            out.print(prefix); out.print(
10976                    Integer.toHexString(System.identityHashCode(filter.activity)));
10977                    out.print(' ');
10978                    filter.activity.printComponentShortName(out);
10979                    out.print(" filter ");
10980                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10981        }
10982
10983        @Override
10984        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10985            return filter.activity;
10986        }
10987
10988        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10989            PackageParser.Activity activity = (PackageParser.Activity)label;
10990            out.print(prefix); out.print(
10991                    Integer.toHexString(System.identityHashCode(activity)));
10992                    out.print(' ');
10993                    activity.printComponentShortName(out);
10994            if (count > 1) {
10995                out.print(" ("); out.print(count); out.print(" filters)");
10996            }
10997            out.println();
10998        }
10999
11000        // Keys are String (activity class name), values are Activity.
11001        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11002                = new ArrayMap<ComponentName, PackageParser.Activity>();
11003        private int mFlags;
11004    }
11005
11006    private final class ServiceIntentResolver
11007            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11008        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11009                boolean defaultOnly, int userId) {
11010            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11011            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11012        }
11013
11014        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11015                int userId) {
11016            if (!sUserManager.exists(userId)) return null;
11017            mFlags = flags;
11018            return super.queryIntent(intent, resolvedType,
11019                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11020        }
11021
11022        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11023                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11024            if (!sUserManager.exists(userId)) return null;
11025            if (packageServices == null) {
11026                return null;
11027            }
11028            mFlags = flags;
11029            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11030            final int N = packageServices.size();
11031            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11032                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11033
11034            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11035            for (int i = 0; i < N; ++i) {
11036                intentFilters = packageServices.get(i).intents;
11037                if (intentFilters != null && intentFilters.size() > 0) {
11038                    PackageParser.ServiceIntentInfo[] array =
11039                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
11040                    intentFilters.toArray(array);
11041                    listCut.add(array);
11042                }
11043            }
11044            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11045        }
11046
11047        public final void addService(PackageParser.Service s) {
11048            mServices.put(s.getComponentName(), s);
11049            if (DEBUG_SHOW_INFO) {
11050                Log.v(TAG, "  "
11051                        + (s.info.nonLocalizedLabel != null
11052                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11053                Log.v(TAG, "    Class=" + s.info.name);
11054            }
11055            final int NI = s.intents.size();
11056            int j;
11057            for (j=0; j<NI; j++) {
11058                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11059                if (DEBUG_SHOW_INFO) {
11060                    Log.v(TAG, "    IntentFilter:");
11061                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11062                }
11063                if (!intent.debugCheck()) {
11064                    Log.w(TAG, "==> For Service " + s.info.name);
11065                }
11066                addFilter(intent);
11067            }
11068        }
11069
11070        public final void removeService(PackageParser.Service s) {
11071            mServices.remove(s.getComponentName());
11072            if (DEBUG_SHOW_INFO) {
11073                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11074                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11075                Log.v(TAG, "    Class=" + s.info.name);
11076            }
11077            final int NI = s.intents.size();
11078            int j;
11079            for (j=0; j<NI; j++) {
11080                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11081                if (DEBUG_SHOW_INFO) {
11082                    Log.v(TAG, "    IntentFilter:");
11083                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11084                }
11085                removeFilter(intent);
11086            }
11087        }
11088
11089        @Override
11090        protected boolean allowFilterResult(
11091                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11092            ServiceInfo filterSi = filter.service.info;
11093            for (int i=dest.size()-1; i>=0; i--) {
11094                ServiceInfo destAi = dest.get(i).serviceInfo;
11095                if (destAi.name == filterSi.name
11096                        && destAi.packageName == filterSi.packageName) {
11097                    return false;
11098                }
11099            }
11100            return true;
11101        }
11102
11103        @Override
11104        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11105            return new PackageParser.ServiceIntentInfo[size];
11106        }
11107
11108        @Override
11109        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11110            if (!sUserManager.exists(userId)) return true;
11111            PackageParser.Package p = filter.service.owner;
11112            if (p != null) {
11113                PackageSetting ps = (PackageSetting)p.mExtras;
11114                if (ps != null) {
11115                    // System apps are never considered stopped for purposes of
11116                    // filtering, because there may be no way for the user to
11117                    // actually re-launch them.
11118                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11119                            && ps.getStopped(userId);
11120                }
11121            }
11122            return false;
11123        }
11124
11125        @Override
11126        protected boolean isPackageForFilter(String packageName,
11127                PackageParser.ServiceIntentInfo info) {
11128            return packageName.equals(info.service.owner.packageName);
11129        }
11130
11131        @Override
11132        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11133                int match, int userId) {
11134            if (!sUserManager.exists(userId)) return null;
11135            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11136            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11137                return null;
11138            }
11139            final PackageParser.Service service = info.service;
11140            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11141            if (ps == null) {
11142                return null;
11143            }
11144            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11145                    ps.readUserState(userId), userId);
11146            if (si == null) {
11147                return null;
11148            }
11149            final ResolveInfo res = new ResolveInfo();
11150            res.serviceInfo = si;
11151            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11152                res.filter = filter;
11153            }
11154            res.priority = info.getPriority();
11155            res.preferredOrder = service.owner.mPreferredOrder;
11156            res.match = match;
11157            res.isDefault = info.hasDefault;
11158            res.labelRes = info.labelRes;
11159            res.nonLocalizedLabel = info.nonLocalizedLabel;
11160            res.icon = info.icon;
11161            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11162            return res;
11163        }
11164
11165        @Override
11166        protected void sortResults(List<ResolveInfo> results) {
11167            Collections.sort(results, mResolvePrioritySorter);
11168        }
11169
11170        @Override
11171        protected void dumpFilter(PrintWriter out, String prefix,
11172                PackageParser.ServiceIntentInfo filter) {
11173            out.print(prefix); out.print(
11174                    Integer.toHexString(System.identityHashCode(filter.service)));
11175                    out.print(' ');
11176                    filter.service.printComponentShortName(out);
11177                    out.print(" filter ");
11178                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11179        }
11180
11181        @Override
11182        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11183            return filter.service;
11184        }
11185
11186        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11187            PackageParser.Service service = (PackageParser.Service)label;
11188            out.print(prefix); out.print(
11189                    Integer.toHexString(System.identityHashCode(service)));
11190                    out.print(' ');
11191                    service.printComponentShortName(out);
11192            if (count > 1) {
11193                out.print(" ("); out.print(count); out.print(" filters)");
11194            }
11195            out.println();
11196        }
11197
11198//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11199//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11200//            final List<ResolveInfo> retList = Lists.newArrayList();
11201//            while (i.hasNext()) {
11202//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11203//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11204//                    retList.add(resolveInfo);
11205//                }
11206//            }
11207//            return retList;
11208//        }
11209
11210        // Keys are String (activity class name), values are Activity.
11211        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11212                = new ArrayMap<ComponentName, PackageParser.Service>();
11213        private int mFlags;
11214    };
11215
11216    private final class ProviderIntentResolver
11217            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11218        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11219                boolean defaultOnly, int userId) {
11220            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11221            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11222        }
11223
11224        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11225                int userId) {
11226            if (!sUserManager.exists(userId))
11227                return null;
11228            mFlags = flags;
11229            return super.queryIntent(intent, resolvedType,
11230                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11231        }
11232
11233        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11234                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11235            if (!sUserManager.exists(userId))
11236                return null;
11237            if (packageProviders == null) {
11238                return null;
11239            }
11240            mFlags = flags;
11241            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11242            final int N = packageProviders.size();
11243            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11244                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11245
11246            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11247            for (int i = 0; i < N; ++i) {
11248                intentFilters = packageProviders.get(i).intents;
11249                if (intentFilters != null && intentFilters.size() > 0) {
11250                    PackageParser.ProviderIntentInfo[] array =
11251                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11252                    intentFilters.toArray(array);
11253                    listCut.add(array);
11254                }
11255            }
11256            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11257        }
11258
11259        public final void addProvider(PackageParser.Provider p) {
11260            if (mProviders.containsKey(p.getComponentName())) {
11261                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11262                return;
11263            }
11264
11265            mProviders.put(p.getComponentName(), p);
11266            if (DEBUG_SHOW_INFO) {
11267                Log.v(TAG, "  "
11268                        + (p.info.nonLocalizedLabel != null
11269                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11270                Log.v(TAG, "    Class=" + p.info.name);
11271            }
11272            final int NI = p.intents.size();
11273            int j;
11274            for (j = 0; j < NI; j++) {
11275                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11276                if (DEBUG_SHOW_INFO) {
11277                    Log.v(TAG, "    IntentFilter:");
11278                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11279                }
11280                if (!intent.debugCheck()) {
11281                    Log.w(TAG, "==> For Provider " + p.info.name);
11282                }
11283                addFilter(intent);
11284            }
11285        }
11286
11287        public final void removeProvider(PackageParser.Provider p) {
11288            mProviders.remove(p.getComponentName());
11289            if (DEBUG_SHOW_INFO) {
11290                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11291                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11292                Log.v(TAG, "    Class=" + p.info.name);
11293            }
11294            final int NI = p.intents.size();
11295            int j;
11296            for (j = 0; j < NI; j++) {
11297                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11298                if (DEBUG_SHOW_INFO) {
11299                    Log.v(TAG, "    IntentFilter:");
11300                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11301                }
11302                removeFilter(intent);
11303            }
11304        }
11305
11306        @Override
11307        protected boolean allowFilterResult(
11308                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11309            ProviderInfo filterPi = filter.provider.info;
11310            for (int i = dest.size() - 1; i >= 0; i--) {
11311                ProviderInfo destPi = dest.get(i).providerInfo;
11312                if (destPi.name == filterPi.name
11313                        && destPi.packageName == filterPi.packageName) {
11314                    return false;
11315                }
11316            }
11317            return true;
11318        }
11319
11320        @Override
11321        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11322            return new PackageParser.ProviderIntentInfo[size];
11323        }
11324
11325        @Override
11326        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11327            if (!sUserManager.exists(userId))
11328                return true;
11329            PackageParser.Package p = filter.provider.owner;
11330            if (p != null) {
11331                PackageSetting ps = (PackageSetting) p.mExtras;
11332                if (ps != null) {
11333                    // System apps are never considered stopped for purposes of
11334                    // filtering, because there may be no way for the user to
11335                    // actually re-launch them.
11336                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11337                            && ps.getStopped(userId);
11338                }
11339            }
11340            return false;
11341        }
11342
11343        @Override
11344        protected boolean isPackageForFilter(String packageName,
11345                PackageParser.ProviderIntentInfo info) {
11346            return packageName.equals(info.provider.owner.packageName);
11347        }
11348
11349        @Override
11350        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11351                int match, int userId) {
11352            if (!sUserManager.exists(userId))
11353                return null;
11354            final PackageParser.ProviderIntentInfo info = filter;
11355            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11356                return null;
11357            }
11358            final PackageParser.Provider provider = info.provider;
11359            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11360            if (ps == null) {
11361                return null;
11362            }
11363            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11364                    ps.readUserState(userId), userId);
11365            if (pi == null) {
11366                return null;
11367            }
11368            final ResolveInfo res = new ResolveInfo();
11369            res.providerInfo = pi;
11370            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11371                res.filter = filter;
11372            }
11373            res.priority = info.getPriority();
11374            res.preferredOrder = provider.owner.mPreferredOrder;
11375            res.match = match;
11376            res.isDefault = info.hasDefault;
11377            res.labelRes = info.labelRes;
11378            res.nonLocalizedLabel = info.nonLocalizedLabel;
11379            res.icon = info.icon;
11380            res.system = res.providerInfo.applicationInfo.isSystemApp();
11381            return res;
11382        }
11383
11384        @Override
11385        protected void sortResults(List<ResolveInfo> results) {
11386            Collections.sort(results, mResolvePrioritySorter);
11387        }
11388
11389        @Override
11390        protected void dumpFilter(PrintWriter out, String prefix,
11391                PackageParser.ProviderIntentInfo filter) {
11392            out.print(prefix);
11393            out.print(
11394                    Integer.toHexString(System.identityHashCode(filter.provider)));
11395            out.print(' ');
11396            filter.provider.printComponentShortName(out);
11397            out.print(" filter ");
11398            out.println(Integer.toHexString(System.identityHashCode(filter)));
11399        }
11400
11401        @Override
11402        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11403            return filter.provider;
11404        }
11405
11406        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11407            PackageParser.Provider provider = (PackageParser.Provider)label;
11408            out.print(prefix); out.print(
11409                    Integer.toHexString(System.identityHashCode(provider)));
11410                    out.print(' ');
11411                    provider.printComponentShortName(out);
11412            if (count > 1) {
11413                out.print(" ("); out.print(count); out.print(" filters)");
11414            }
11415            out.println();
11416        }
11417
11418        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11419                = new ArrayMap<ComponentName, PackageParser.Provider>();
11420        private int mFlags;
11421    }
11422
11423    private static final class EphemeralIntentResolver
11424            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11425        /**
11426         * The result that has the highest defined order. Ordering applies on a
11427         * per-package basis. Mapping is from package name to Pair of order and
11428         * EphemeralResolveInfo.
11429         * <p>
11430         * NOTE: This is implemented as a field variable for convenience and efficiency.
11431         * By having a field variable, we're able to track filter ordering as soon as
11432         * a non-zero order is defined. Otherwise, multiple loops across the result set
11433         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11434         * this needs to be contained entirely within {@link #filterResults()}.
11435         */
11436        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11437
11438        @Override
11439        protected EphemeralResolveIntentInfo[] newArray(int size) {
11440            return new EphemeralResolveIntentInfo[size];
11441        }
11442
11443        @Override
11444        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11445            return true;
11446        }
11447
11448        @Override
11449        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11450                int userId) {
11451            if (!sUserManager.exists(userId)) {
11452                return null;
11453            }
11454            final String packageName = info.getEphemeralResolveInfo().getPackageName();
11455            final Integer order = info.getOrder();
11456            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11457                    mOrderResult.get(packageName);
11458            // ordering is enabled and this item's order isn't high enough
11459            if (lastOrderResult != null && lastOrderResult.first >= order) {
11460                return null;
11461            }
11462            final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11463            if (order > 0) {
11464                // non-zero order, enable ordering
11465                mOrderResult.put(packageName, new Pair<>(order, res));
11466            }
11467            return res;
11468        }
11469
11470        @Override
11471        protected void filterResults(List<EphemeralResolveInfo> results) {
11472            // only do work if ordering is enabled [most of the time it won't be]
11473            if (mOrderResult.size() == 0) {
11474                return;
11475            }
11476            int resultSize = results.size();
11477            for (int i = 0; i < resultSize; i++) {
11478                final EphemeralResolveInfo info = results.get(i);
11479                final String packageName = info.getPackageName();
11480                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11481                if (savedInfo == null) {
11482                    // package doesn't having ordering
11483                    continue;
11484                }
11485                if (savedInfo.second == info) {
11486                    // circled back to the highest ordered item; remove from order list
11487                    mOrderResult.remove(savedInfo);
11488                    if (mOrderResult.size() == 0) {
11489                        // no more ordered items
11490                        break;
11491                    }
11492                    continue;
11493                }
11494                // item has a worse order, remove it from the result list
11495                results.remove(i);
11496                resultSize--;
11497                i--;
11498            }
11499        }
11500    }
11501
11502    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11503            new Comparator<ResolveInfo>() {
11504        public int compare(ResolveInfo r1, ResolveInfo r2) {
11505            int v1 = r1.priority;
11506            int v2 = r2.priority;
11507            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11508            if (v1 != v2) {
11509                return (v1 > v2) ? -1 : 1;
11510            }
11511            v1 = r1.preferredOrder;
11512            v2 = r2.preferredOrder;
11513            if (v1 != v2) {
11514                return (v1 > v2) ? -1 : 1;
11515            }
11516            if (r1.isDefault != r2.isDefault) {
11517                return r1.isDefault ? -1 : 1;
11518            }
11519            v1 = r1.match;
11520            v2 = r2.match;
11521            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11522            if (v1 != v2) {
11523                return (v1 > v2) ? -1 : 1;
11524            }
11525            if (r1.system != r2.system) {
11526                return r1.system ? -1 : 1;
11527            }
11528            if (r1.activityInfo != null) {
11529                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11530            }
11531            if (r1.serviceInfo != null) {
11532                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11533            }
11534            if (r1.providerInfo != null) {
11535                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11536            }
11537            return 0;
11538        }
11539    };
11540
11541    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11542            new Comparator<ProviderInfo>() {
11543        public int compare(ProviderInfo p1, ProviderInfo p2) {
11544            final int v1 = p1.initOrder;
11545            final int v2 = p2.initOrder;
11546            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11547        }
11548    };
11549
11550    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11551            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11552            final int[] userIds) {
11553        mHandler.post(new Runnable() {
11554            @Override
11555            public void run() {
11556                try {
11557                    final IActivityManager am = ActivityManagerNative.getDefault();
11558                    if (am == null) return;
11559                    final int[] resolvedUserIds;
11560                    if (userIds == null) {
11561                        resolvedUserIds = am.getRunningUserIds();
11562                    } else {
11563                        resolvedUserIds = userIds;
11564                    }
11565                    for (int id : resolvedUserIds) {
11566                        final Intent intent = new Intent(action,
11567                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11568                        if (extras != null) {
11569                            intent.putExtras(extras);
11570                        }
11571                        if (targetPkg != null) {
11572                            intent.setPackage(targetPkg);
11573                        }
11574                        // Modify the UID when posting to other users
11575                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11576                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11577                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11578                            intent.putExtra(Intent.EXTRA_UID, uid);
11579                        }
11580                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11581                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11582                        if (DEBUG_BROADCASTS) {
11583                            RuntimeException here = new RuntimeException("here");
11584                            here.fillInStackTrace();
11585                            Slog.d(TAG, "Sending to user " + id + ": "
11586                                    + intent.toShortString(false, true, false, false)
11587                                    + " " + intent.getExtras(), here);
11588                        }
11589                        am.broadcastIntent(null, intent, null, finishedReceiver,
11590                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11591                                null, finishedReceiver != null, false, id);
11592                    }
11593                } catch (RemoteException ex) {
11594                }
11595            }
11596        });
11597    }
11598
11599    /**
11600     * Check if the external storage media is available. This is true if there
11601     * is a mounted external storage medium or if the external storage is
11602     * emulated.
11603     */
11604    private boolean isExternalMediaAvailable() {
11605        return mMediaMounted || Environment.isExternalStorageEmulated();
11606    }
11607
11608    @Override
11609    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11610        // writer
11611        synchronized (mPackages) {
11612            if (!isExternalMediaAvailable()) {
11613                // If the external storage is no longer mounted at this point,
11614                // the caller may not have been able to delete all of this
11615                // packages files and can not delete any more.  Bail.
11616                return null;
11617            }
11618            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11619            if (lastPackage != null) {
11620                pkgs.remove(lastPackage);
11621            }
11622            if (pkgs.size() > 0) {
11623                return pkgs.get(0);
11624            }
11625        }
11626        return null;
11627    }
11628
11629    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11630        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11631                userId, andCode ? 1 : 0, packageName);
11632        if (mSystemReady) {
11633            msg.sendToTarget();
11634        } else {
11635            if (mPostSystemReadyMessages == null) {
11636                mPostSystemReadyMessages = new ArrayList<>();
11637            }
11638            mPostSystemReadyMessages.add(msg);
11639        }
11640    }
11641
11642    void startCleaningPackages() {
11643        // reader
11644        if (!isExternalMediaAvailable()) {
11645            return;
11646        }
11647        synchronized (mPackages) {
11648            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11649                return;
11650            }
11651        }
11652        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11653        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11654        IActivityManager am = ActivityManagerNative.getDefault();
11655        if (am != null) {
11656            try {
11657                am.startService(null, intent, null, mContext.getOpPackageName(),
11658                        UserHandle.USER_SYSTEM);
11659            } catch (RemoteException e) {
11660            }
11661        }
11662    }
11663
11664    @Override
11665    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11666            int installFlags, String installerPackageName, int userId) {
11667        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11668
11669        final int callingUid = Binder.getCallingUid();
11670        enforceCrossUserPermission(callingUid, userId,
11671                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11672
11673        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11674            try {
11675                if (observer != null) {
11676                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11677                }
11678            } catch (RemoteException re) {
11679            }
11680            return;
11681        }
11682
11683        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11684            installFlags |= PackageManager.INSTALL_FROM_ADB;
11685
11686        } else {
11687            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11688            // about installerPackageName.
11689
11690            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11691            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11692        }
11693
11694        UserHandle user;
11695        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11696            user = UserHandle.ALL;
11697        } else {
11698            user = new UserHandle(userId);
11699        }
11700
11701        // Only system components can circumvent runtime permissions when installing.
11702        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11703                && mContext.checkCallingOrSelfPermission(Manifest.permission
11704                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11705            throw new SecurityException("You need the "
11706                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11707                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11708        }
11709
11710        final File originFile = new File(originPath);
11711        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11712
11713        final Message msg = mHandler.obtainMessage(INIT_COPY);
11714        final VerificationInfo verificationInfo = new VerificationInfo(
11715                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11716        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11717                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11718                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11719                null /*certificates*/);
11720        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11721        msg.obj = params;
11722
11723        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11724                System.identityHashCode(msg.obj));
11725        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11726                System.identityHashCode(msg.obj));
11727
11728        mHandler.sendMessage(msg);
11729    }
11730
11731    void installStage(String packageName, File stagedDir, String stagedCid,
11732            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11733            String installerPackageName, int installerUid, UserHandle user,
11734            Certificate[][] certificates) {
11735        if (DEBUG_EPHEMERAL) {
11736            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11737                Slog.d(TAG, "Ephemeral install of " + packageName);
11738            }
11739        }
11740        final VerificationInfo verificationInfo = new VerificationInfo(
11741                sessionParams.originatingUri, sessionParams.referrerUri,
11742                sessionParams.originatingUid, installerUid);
11743
11744        final OriginInfo origin;
11745        if (stagedDir != null) {
11746            origin = OriginInfo.fromStagedFile(stagedDir);
11747        } else {
11748            origin = OriginInfo.fromStagedContainer(stagedCid);
11749        }
11750
11751        final Message msg = mHandler.obtainMessage(INIT_COPY);
11752        final InstallParams params = new InstallParams(origin, null, observer,
11753                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11754                verificationInfo, user, sessionParams.abiOverride,
11755                sessionParams.grantedRuntimePermissions, certificates);
11756        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11757        msg.obj = params;
11758
11759        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11760                System.identityHashCode(msg.obj));
11761        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11762                System.identityHashCode(msg.obj));
11763
11764        mHandler.sendMessage(msg);
11765    }
11766
11767    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11768            int userId) {
11769        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11770        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11771    }
11772
11773    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11774            int appId, int userId) {
11775        Bundle extras = new Bundle(1);
11776        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11777
11778        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11779                packageName, extras, 0, null, null, new int[] {userId});
11780        try {
11781            IActivityManager am = ActivityManagerNative.getDefault();
11782            if (isSystem && am.isUserRunning(userId, 0)) {
11783                // The just-installed/enabled app is bundled on the system, so presumed
11784                // to be able to run automatically without needing an explicit launch.
11785                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11786                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11787                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11788                        .setPackage(packageName);
11789                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11790                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11791            }
11792        } catch (RemoteException e) {
11793            // shouldn't happen
11794            Slog.w(TAG, "Unable to bootstrap installed package", e);
11795        }
11796    }
11797
11798    @Override
11799    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11800            int userId) {
11801        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11802        PackageSetting pkgSetting;
11803        final int uid = Binder.getCallingUid();
11804        enforceCrossUserPermission(uid, userId,
11805                true /* requireFullPermission */, true /* checkShell */,
11806                "setApplicationHiddenSetting for user " + userId);
11807
11808        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11809            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11810            return false;
11811        }
11812
11813        long callingId = Binder.clearCallingIdentity();
11814        try {
11815            boolean sendAdded = false;
11816            boolean sendRemoved = false;
11817            // writer
11818            synchronized (mPackages) {
11819                pkgSetting = mSettings.mPackages.get(packageName);
11820                if (pkgSetting == null) {
11821                    return false;
11822                }
11823                // Do not allow "android" is being disabled
11824                if ("android".equals(packageName)) {
11825                    Slog.w(TAG, "Cannot hide package: android");
11826                    return false;
11827                }
11828                // Only allow protected packages to hide themselves.
11829                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11830                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11831                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11832                    return false;
11833                }
11834
11835                if (pkgSetting.getHidden(userId) != hidden) {
11836                    pkgSetting.setHidden(hidden, userId);
11837                    mSettings.writePackageRestrictionsLPr(userId);
11838                    if (hidden) {
11839                        sendRemoved = true;
11840                    } else {
11841                        sendAdded = true;
11842                    }
11843                }
11844            }
11845            if (sendAdded) {
11846                sendPackageAddedForUser(packageName, pkgSetting, userId);
11847                return true;
11848            }
11849            if (sendRemoved) {
11850                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11851                        "hiding pkg");
11852                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11853                return true;
11854            }
11855        } finally {
11856            Binder.restoreCallingIdentity(callingId);
11857        }
11858        return false;
11859    }
11860
11861    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11862            int userId) {
11863        final PackageRemovedInfo info = new PackageRemovedInfo();
11864        info.removedPackage = packageName;
11865        info.removedUsers = new int[] {userId};
11866        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11867        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11868    }
11869
11870    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11871        if (pkgList.length > 0) {
11872            Bundle extras = new Bundle(1);
11873            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11874
11875            sendPackageBroadcast(
11876                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11877                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11878                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11879                    new int[] {userId});
11880        }
11881    }
11882
11883    /**
11884     * Returns true if application is not found or there was an error. Otherwise it returns
11885     * the hidden state of the package for the given user.
11886     */
11887    @Override
11888    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11889        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11890        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11891                true /* requireFullPermission */, false /* checkShell */,
11892                "getApplicationHidden for user " + userId);
11893        PackageSetting pkgSetting;
11894        long callingId = Binder.clearCallingIdentity();
11895        try {
11896            // writer
11897            synchronized (mPackages) {
11898                pkgSetting = mSettings.mPackages.get(packageName);
11899                if (pkgSetting == null) {
11900                    return true;
11901                }
11902                return pkgSetting.getHidden(userId);
11903            }
11904        } finally {
11905            Binder.restoreCallingIdentity(callingId);
11906        }
11907    }
11908
11909    /**
11910     * @hide
11911     */
11912    @Override
11913    public int installExistingPackageAsUser(String packageName, int userId) {
11914        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11915                null);
11916        PackageSetting pkgSetting;
11917        final int uid = Binder.getCallingUid();
11918        enforceCrossUserPermission(uid, userId,
11919                true /* requireFullPermission */, true /* checkShell */,
11920                "installExistingPackage for user " + userId);
11921        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11922            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11923        }
11924
11925        long callingId = Binder.clearCallingIdentity();
11926        try {
11927            boolean installed = false;
11928
11929            // writer
11930            synchronized (mPackages) {
11931                pkgSetting = mSettings.mPackages.get(packageName);
11932                if (pkgSetting == null) {
11933                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11934                }
11935                if (!pkgSetting.getInstalled(userId)) {
11936                    pkgSetting.setInstalled(true, userId);
11937                    pkgSetting.setHidden(false, userId);
11938                    mSettings.writePackageRestrictionsLPr(userId);
11939                    installed = true;
11940                }
11941            }
11942
11943            if (installed) {
11944                if (pkgSetting.pkg != null) {
11945                    synchronized (mInstallLock) {
11946                        // We don't need to freeze for a brand new install
11947                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11948                    }
11949                }
11950                sendPackageAddedForUser(packageName, pkgSetting, userId);
11951            }
11952        } finally {
11953            Binder.restoreCallingIdentity(callingId);
11954        }
11955
11956        return PackageManager.INSTALL_SUCCEEDED;
11957    }
11958
11959    boolean isUserRestricted(int userId, String restrictionKey) {
11960        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11961        if (restrictions.getBoolean(restrictionKey, false)) {
11962            Log.w(TAG, "User is restricted: " + restrictionKey);
11963            return true;
11964        }
11965        return false;
11966    }
11967
11968    @Override
11969    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11970            int userId) {
11971        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11972        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11973                true /* requireFullPermission */, true /* checkShell */,
11974                "setPackagesSuspended for user " + userId);
11975
11976        if (ArrayUtils.isEmpty(packageNames)) {
11977            return packageNames;
11978        }
11979
11980        // List of package names for whom the suspended state has changed.
11981        List<String> changedPackages = new ArrayList<>(packageNames.length);
11982        // List of package names for whom the suspended state is not set as requested in this
11983        // method.
11984        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11985        long callingId = Binder.clearCallingIdentity();
11986        try {
11987            for (int i = 0; i < packageNames.length; i++) {
11988                String packageName = packageNames[i];
11989                boolean changed = false;
11990                final int appId;
11991                synchronized (mPackages) {
11992                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11993                    if (pkgSetting == null) {
11994                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11995                                + "\". Skipping suspending/un-suspending.");
11996                        unactionedPackages.add(packageName);
11997                        continue;
11998                    }
11999                    appId = pkgSetting.appId;
12000                    if (pkgSetting.getSuspended(userId) != suspended) {
12001                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
12002                            unactionedPackages.add(packageName);
12003                            continue;
12004                        }
12005                        pkgSetting.setSuspended(suspended, userId);
12006                        mSettings.writePackageRestrictionsLPr(userId);
12007                        changed = true;
12008                        changedPackages.add(packageName);
12009                    }
12010                }
12011
12012                if (changed && suspended) {
12013                    killApplication(packageName, UserHandle.getUid(userId, appId),
12014                            "suspending package");
12015                }
12016            }
12017        } finally {
12018            Binder.restoreCallingIdentity(callingId);
12019        }
12020
12021        if (!changedPackages.isEmpty()) {
12022            sendPackagesSuspendedForUser(changedPackages.toArray(
12023                    new String[changedPackages.size()]), userId, suspended);
12024        }
12025
12026        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12027    }
12028
12029    @Override
12030    public boolean isPackageSuspendedForUser(String packageName, int userId) {
12031        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12032                true /* requireFullPermission */, false /* checkShell */,
12033                "isPackageSuspendedForUser for user " + userId);
12034        synchronized (mPackages) {
12035            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12036            if (pkgSetting == null) {
12037                throw new IllegalArgumentException("Unknown target package: " + packageName);
12038            }
12039            return pkgSetting.getSuspended(userId);
12040        }
12041    }
12042
12043    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12044        if (isPackageDeviceAdmin(packageName, userId)) {
12045            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12046                    + "\": has an active device admin");
12047            return false;
12048        }
12049
12050        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12051        if (packageName.equals(activeLauncherPackageName)) {
12052            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12053                    + "\": contains the active launcher");
12054            return false;
12055        }
12056
12057        if (packageName.equals(mRequiredInstallerPackage)) {
12058            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12059                    + "\": required for package installation");
12060            return false;
12061        }
12062
12063        if (packageName.equals(mRequiredUninstallerPackage)) {
12064            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12065                    + "\": required for package uninstallation");
12066            return false;
12067        }
12068
12069        if (packageName.equals(mRequiredVerifierPackage)) {
12070            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12071                    + "\": required for package verification");
12072            return false;
12073        }
12074
12075        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12076            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12077                    + "\": is the default dialer");
12078            return false;
12079        }
12080
12081        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12082            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12083                    + "\": protected package");
12084            return false;
12085        }
12086
12087        return true;
12088    }
12089
12090    private String getActiveLauncherPackageName(int userId) {
12091        Intent intent = new Intent(Intent.ACTION_MAIN);
12092        intent.addCategory(Intent.CATEGORY_HOME);
12093        ResolveInfo resolveInfo = resolveIntent(
12094                intent,
12095                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12096                PackageManager.MATCH_DEFAULT_ONLY,
12097                userId);
12098
12099        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12100    }
12101
12102    private String getDefaultDialerPackageName(int userId) {
12103        synchronized (mPackages) {
12104            return mSettings.getDefaultDialerPackageNameLPw(userId);
12105        }
12106    }
12107
12108    @Override
12109    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12110        mContext.enforceCallingOrSelfPermission(
12111                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12112                "Only package verification agents can verify applications");
12113
12114        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12115        final PackageVerificationResponse response = new PackageVerificationResponse(
12116                verificationCode, Binder.getCallingUid());
12117        msg.arg1 = id;
12118        msg.obj = response;
12119        mHandler.sendMessage(msg);
12120    }
12121
12122    @Override
12123    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12124            long millisecondsToDelay) {
12125        mContext.enforceCallingOrSelfPermission(
12126                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12127                "Only package verification agents can extend verification timeouts");
12128
12129        final PackageVerificationState state = mPendingVerification.get(id);
12130        final PackageVerificationResponse response = new PackageVerificationResponse(
12131                verificationCodeAtTimeout, Binder.getCallingUid());
12132
12133        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12134            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12135        }
12136        if (millisecondsToDelay < 0) {
12137            millisecondsToDelay = 0;
12138        }
12139        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12140                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12141            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12142        }
12143
12144        if ((state != null) && !state.timeoutExtended()) {
12145            state.extendTimeout();
12146
12147            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12148            msg.arg1 = id;
12149            msg.obj = response;
12150            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12151        }
12152    }
12153
12154    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12155            int verificationCode, UserHandle user) {
12156        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12157        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12158        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12159        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12160        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12161
12162        mContext.sendBroadcastAsUser(intent, user,
12163                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12164    }
12165
12166    private ComponentName matchComponentForVerifier(String packageName,
12167            List<ResolveInfo> receivers) {
12168        ActivityInfo targetReceiver = null;
12169
12170        final int NR = receivers.size();
12171        for (int i = 0; i < NR; i++) {
12172            final ResolveInfo info = receivers.get(i);
12173            if (info.activityInfo == null) {
12174                continue;
12175            }
12176
12177            if (packageName.equals(info.activityInfo.packageName)) {
12178                targetReceiver = info.activityInfo;
12179                break;
12180            }
12181        }
12182
12183        if (targetReceiver == null) {
12184            return null;
12185        }
12186
12187        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12188    }
12189
12190    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12191            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12192        if (pkgInfo.verifiers.length == 0) {
12193            return null;
12194        }
12195
12196        final int N = pkgInfo.verifiers.length;
12197        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12198        for (int i = 0; i < N; i++) {
12199            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12200
12201            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12202                    receivers);
12203            if (comp == null) {
12204                continue;
12205            }
12206
12207            final int verifierUid = getUidForVerifier(verifierInfo);
12208            if (verifierUid == -1) {
12209                continue;
12210            }
12211
12212            if (DEBUG_VERIFY) {
12213                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12214                        + " with the correct signature");
12215            }
12216            sufficientVerifiers.add(comp);
12217            verificationState.addSufficientVerifier(verifierUid);
12218        }
12219
12220        return sufficientVerifiers;
12221    }
12222
12223    private int getUidForVerifier(VerifierInfo verifierInfo) {
12224        synchronized (mPackages) {
12225            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12226            if (pkg == null) {
12227                return -1;
12228            } else if (pkg.mSignatures.length != 1) {
12229                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12230                        + " has more than one signature; ignoring");
12231                return -1;
12232            }
12233
12234            /*
12235             * If the public key of the package's signature does not match
12236             * our expected public key, then this is a different package and
12237             * we should skip.
12238             */
12239
12240            final byte[] expectedPublicKey;
12241            try {
12242                final Signature verifierSig = pkg.mSignatures[0];
12243                final PublicKey publicKey = verifierSig.getPublicKey();
12244                expectedPublicKey = publicKey.getEncoded();
12245            } catch (CertificateException e) {
12246                return -1;
12247            }
12248
12249            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12250
12251            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12252                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12253                        + " does not have the expected public key; ignoring");
12254                return -1;
12255            }
12256
12257            return pkg.applicationInfo.uid;
12258        }
12259    }
12260
12261    @Override
12262    public void finishPackageInstall(int token, boolean didLaunch) {
12263        enforceSystemOrRoot("Only the system is allowed to finish installs");
12264
12265        if (DEBUG_INSTALL) {
12266            Slog.v(TAG, "BM finishing package install for " + token);
12267        }
12268        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12269
12270        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12271        mHandler.sendMessage(msg);
12272    }
12273
12274    /**
12275     * Get the verification agent timeout.
12276     *
12277     * @return verification timeout in milliseconds
12278     */
12279    private long getVerificationTimeout() {
12280        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12281                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12282                DEFAULT_VERIFICATION_TIMEOUT);
12283    }
12284
12285    /**
12286     * Get the default verification agent response code.
12287     *
12288     * @return default verification response code
12289     */
12290    private int getDefaultVerificationResponse() {
12291        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12292                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12293                DEFAULT_VERIFICATION_RESPONSE);
12294    }
12295
12296    /**
12297     * Check whether or not package verification has been enabled.
12298     *
12299     * @return true if verification should be performed
12300     */
12301    private boolean isVerificationEnabled(int userId, int installFlags) {
12302        if (!DEFAULT_VERIFY_ENABLE) {
12303            return false;
12304        }
12305        // Ephemeral apps don't get the full verification treatment
12306        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12307            if (DEBUG_EPHEMERAL) {
12308                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12309            }
12310            return false;
12311        }
12312
12313        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12314
12315        // Check if installing from ADB
12316        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12317            // Do not run verification in a test harness environment
12318            if (ActivityManager.isRunningInTestHarness()) {
12319                return false;
12320            }
12321            if (ensureVerifyAppsEnabled) {
12322                return true;
12323            }
12324            // Check if the developer does not want package verification for ADB installs
12325            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12326                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12327                return false;
12328            }
12329        }
12330
12331        if (ensureVerifyAppsEnabled) {
12332            return true;
12333        }
12334
12335        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12336                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12337    }
12338
12339    @Override
12340    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12341            throws RemoteException {
12342        mContext.enforceCallingOrSelfPermission(
12343                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12344                "Only intentfilter verification agents can verify applications");
12345
12346        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12347        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12348                Binder.getCallingUid(), verificationCode, failedDomains);
12349        msg.arg1 = id;
12350        msg.obj = response;
12351        mHandler.sendMessage(msg);
12352    }
12353
12354    @Override
12355    public int getIntentVerificationStatus(String packageName, int userId) {
12356        synchronized (mPackages) {
12357            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12358        }
12359    }
12360
12361    @Override
12362    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12363        mContext.enforceCallingOrSelfPermission(
12364                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12365
12366        boolean result = false;
12367        synchronized (mPackages) {
12368            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12369        }
12370        if (result) {
12371            scheduleWritePackageRestrictionsLocked(userId);
12372        }
12373        return result;
12374    }
12375
12376    @Override
12377    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12378            String packageName) {
12379        synchronized (mPackages) {
12380            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12381        }
12382    }
12383
12384    @Override
12385    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12386        if (TextUtils.isEmpty(packageName)) {
12387            return ParceledListSlice.emptyList();
12388        }
12389        synchronized (mPackages) {
12390            PackageParser.Package pkg = mPackages.get(packageName);
12391            if (pkg == null || pkg.activities == null) {
12392                return ParceledListSlice.emptyList();
12393            }
12394            final int count = pkg.activities.size();
12395            ArrayList<IntentFilter> result = new ArrayList<>();
12396            for (int n=0; n<count; n++) {
12397                PackageParser.Activity activity = pkg.activities.get(n);
12398                if (activity.intents != null && activity.intents.size() > 0) {
12399                    result.addAll(activity.intents);
12400                }
12401            }
12402            return new ParceledListSlice<>(result);
12403        }
12404    }
12405
12406    @Override
12407    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12408        mContext.enforceCallingOrSelfPermission(
12409                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12410
12411        synchronized (mPackages) {
12412            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12413            if (packageName != null) {
12414                result |= updateIntentVerificationStatus(packageName,
12415                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12416                        userId);
12417                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12418                        packageName, userId);
12419            }
12420            return result;
12421        }
12422    }
12423
12424    @Override
12425    public String getDefaultBrowserPackageName(int userId) {
12426        synchronized (mPackages) {
12427            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12428        }
12429    }
12430
12431    /**
12432     * Get the "allow unknown sources" setting.
12433     *
12434     * @return the current "allow unknown sources" setting
12435     */
12436    private int getUnknownSourcesSettings() {
12437        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12438                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12439                -1);
12440    }
12441
12442    @Override
12443    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12444        final int uid = Binder.getCallingUid();
12445        // writer
12446        synchronized (mPackages) {
12447            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12448            if (targetPackageSetting == null) {
12449                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12450            }
12451
12452            PackageSetting installerPackageSetting;
12453            if (installerPackageName != null) {
12454                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12455                if (installerPackageSetting == null) {
12456                    throw new IllegalArgumentException("Unknown installer package: "
12457                            + installerPackageName);
12458                }
12459            } else {
12460                installerPackageSetting = null;
12461            }
12462
12463            Signature[] callerSignature;
12464            Object obj = mSettings.getUserIdLPr(uid);
12465            if (obj != null) {
12466                if (obj instanceof SharedUserSetting) {
12467                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12468                } else if (obj instanceof PackageSetting) {
12469                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12470                } else {
12471                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12472                }
12473            } else {
12474                throw new SecurityException("Unknown calling UID: " + uid);
12475            }
12476
12477            // Verify: can't set installerPackageName to a package that is
12478            // not signed with the same cert as the caller.
12479            if (installerPackageSetting != null) {
12480                if (compareSignatures(callerSignature,
12481                        installerPackageSetting.signatures.mSignatures)
12482                        != PackageManager.SIGNATURE_MATCH) {
12483                    throw new SecurityException(
12484                            "Caller does not have same cert as new installer package "
12485                            + installerPackageName);
12486                }
12487            }
12488
12489            // Verify: if target already has an installer package, it must
12490            // be signed with the same cert as the caller.
12491            if (targetPackageSetting.installerPackageName != null) {
12492                PackageSetting setting = mSettings.mPackages.get(
12493                        targetPackageSetting.installerPackageName);
12494                // If the currently set package isn't valid, then it's always
12495                // okay to change it.
12496                if (setting != null) {
12497                    if (compareSignatures(callerSignature,
12498                            setting.signatures.mSignatures)
12499                            != PackageManager.SIGNATURE_MATCH) {
12500                        throw new SecurityException(
12501                                "Caller does not have same cert as old installer package "
12502                                + targetPackageSetting.installerPackageName);
12503                    }
12504                }
12505            }
12506
12507            // Okay!
12508            targetPackageSetting.installerPackageName = installerPackageName;
12509            if (installerPackageName != null) {
12510                mSettings.mInstallerPackages.add(installerPackageName);
12511            }
12512            scheduleWriteSettingsLocked();
12513        }
12514    }
12515
12516    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12517        // Queue up an async operation since the package installation may take a little while.
12518        mHandler.post(new Runnable() {
12519            public void run() {
12520                mHandler.removeCallbacks(this);
12521                 // Result object to be returned
12522                PackageInstalledInfo res = new PackageInstalledInfo();
12523                res.setReturnCode(currentStatus);
12524                res.uid = -1;
12525                res.pkg = null;
12526                res.removedInfo = null;
12527                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12528                    args.doPreInstall(res.returnCode);
12529                    synchronized (mInstallLock) {
12530                        installPackageTracedLI(args, res);
12531                    }
12532                    args.doPostInstall(res.returnCode, res.uid);
12533                }
12534
12535                // A restore should be performed at this point if (a) the install
12536                // succeeded, (b) the operation is not an update, and (c) the new
12537                // package has not opted out of backup participation.
12538                final boolean update = res.removedInfo != null
12539                        && res.removedInfo.removedPackage != null;
12540                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12541                boolean doRestore = !update
12542                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12543
12544                // Set up the post-install work request bookkeeping.  This will be used
12545                // and cleaned up by the post-install event handling regardless of whether
12546                // there's a restore pass performed.  Token values are >= 1.
12547                int token;
12548                if (mNextInstallToken < 0) mNextInstallToken = 1;
12549                token = mNextInstallToken++;
12550
12551                PostInstallData data = new PostInstallData(args, res);
12552                mRunningInstalls.put(token, data);
12553                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12554
12555                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12556                    // Pass responsibility to the Backup Manager.  It will perform a
12557                    // restore if appropriate, then pass responsibility back to the
12558                    // Package Manager to run the post-install observer callbacks
12559                    // and broadcasts.
12560                    IBackupManager bm = IBackupManager.Stub.asInterface(
12561                            ServiceManager.getService(Context.BACKUP_SERVICE));
12562                    if (bm != null) {
12563                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12564                                + " to BM for possible restore");
12565                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12566                        try {
12567                            // TODO: http://b/22388012
12568                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12569                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12570                            } else {
12571                                doRestore = false;
12572                            }
12573                        } catch (RemoteException e) {
12574                            // can't happen; the backup manager is local
12575                        } catch (Exception e) {
12576                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12577                            doRestore = false;
12578                        }
12579                    } else {
12580                        Slog.e(TAG, "Backup Manager not found!");
12581                        doRestore = false;
12582                    }
12583                }
12584
12585                if (!doRestore) {
12586                    // No restore possible, or the Backup Manager was mysteriously not
12587                    // available -- just fire the post-install work request directly.
12588                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12589
12590                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12591
12592                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12593                    mHandler.sendMessage(msg);
12594                }
12595            }
12596        });
12597    }
12598
12599    /**
12600     * Callback from PackageSettings whenever an app is first transitioned out of the
12601     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12602     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12603     * here whether the app is the target of an ongoing install, and only send the
12604     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12605     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12606     * handling.
12607     */
12608    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12609        // Serialize this with the rest of the install-process message chain.  In the
12610        // restore-at-install case, this Runnable will necessarily run before the
12611        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12612        // are coherent.  In the non-restore case, the app has already completed install
12613        // and been launched through some other means, so it is not in a problematic
12614        // state for observers to see the FIRST_LAUNCH signal.
12615        mHandler.post(new Runnable() {
12616            @Override
12617            public void run() {
12618                for (int i = 0; i < mRunningInstalls.size(); i++) {
12619                    final PostInstallData data = mRunningInstalls.valueAt(i);
12620                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12621                        continue;
12622                    }
12623                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12624                        // right package; but is it for the right user?
12625                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12626                            if (userId == data.res.newUsers[uIndex]) {
12627                                if (DEBUG_BACKUP) {
12628                                    Slog.i(TAG, "Package " + pkgName
12629                                            + " being restored so deferring FIRST_LAUNCH");
12630                                }
12631                                return;
12632                            }
12633                        }
12634                    }
12635                }
12636                // didn't find it, so not being restored
12637                if (DEBUG_BACKUP) {
12638                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12639                }
12640                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12641            }
12642        });
12643    }
12644
12645    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12646        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12647                installerPkg, null, userIds);
12648    }
12649
12650    private abstract class HandlerParams {
12651        private static final int MAX_RETRIES = 4;
12652
12653        /**
12654         * Number of times startCopy() has been attempted and had a non-fatal
12655         * error.
12656         */
12657        private int mRetries = 0;
12658
12659        /** User handle for the user requesting the information or installation. */
12660        private final UserHandle mUser;
12661        String traceMethod;
12662        int traceCookie;
12663
12664        HandlerParams(UserHandle user) {
12665            mUser = user;
12666        }
12667
12668        UserHandle getUser() {
12669            return mUser;
12670        }
12671
12672        HandlerParams setTraceMethod(String traceMethod) {
12673            this.traceMethod = traceMethod;
12674            return this;
12675        }
12676
12677        HandlerParams setTraceCookie(int traceCookie) {
12678            this.traceCookie = traceCookie;
12679            return this;
12680        }
12681
12682        final boolean startCopy() {
12683            boolean res;
12684            try {
12685                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12686
12687                if (++mRetries > MAX_RETRIES) {
12688                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12689                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12690                    handleServiceError();
12691                    return false;
12692                } else {
12693                    handleStartCopy();
12694                    res = true;
12695                }
12696            } catch (RemoteException e) {
12697                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12698                mHandler.sendEmptyMessage(MCS_RECONNECT);
12699                res = false;
12700            }
12701            handleReturnCode();
12702            return res;
12703        }
12704
12705        final void serviceError() {
12706            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12707            handleServiceError();
12708            handleReturnCode();
12709        }
12710
12711        abstract void handleStartCopy() throws RemoteException;
12712        abstract void handleServiceError();
12713        abstract void handleReturnCode();
12714    }
12715
12716    class MeasureParams extends HandlerParams {
12717        private final PackageStats mStats;
12718        private boolean mSuccess;
12719
12720        private final IPackageStatsObserver mObserver;
12721
12722        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12723            super(new UserHandle(stats.userHandle));
12724            mObserver = observer;
12725            mStats = stats;
12726        }
12727
12728        @Override
12729        public String toString() {
12730            return "MeasureParams{"
12731                + Integer.toHexString(System.identityHashCode(this))
12732                + " " + mStats.packageName + "}";
12733        }
12734
12735        @Override
12736        void handleStartCopy() throws RemoteException {
12737            synchronized (mInstallLock) {
12738                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12739            }
12740
12741            if (mSuccess) {
12742                boolean mounted = false;
12743                try {
12744                    final String status = Environment.getExternalStorageState();
12745                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12746                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12747                } catch (Exception e) {
12748                }
12749
12750                if (mounted) {
12751                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12752
12753                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12754                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12755
12756                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12757                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12758
12759                    // Always subtract cache size, since it's a subdirectory
12760                    mStats.externalDataSize -= mStats.externalCacheSize;
12761
12762                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12763                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12764
12765                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12766                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12767                }
12768            }
12769        }
12770
12771        @Override
12772        void handleReturnCode() {
12773            if (mObserver != null) {
12774                try {
12775                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12776                } catch (RemoteException e) {
12777                    Slog.i(TAG, "Observer no longer exists.");
12778                }
12779            }
12780        }
12781
12782        @Override
12783        void handleServiceError() {
12784            Slog.e(TAG, "Could not measure application " + mStats.packageName
12785                            + " external storage");
12786        }
12787    }
12788
12789    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12790            throws RemoteException {
12791        long result = 0;
12792        for (File path : paths) {
12793            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12794        }
12795        return result;
12796    }
12797
12798    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12799        for (File path : paths) {
12800            try {
12801                mcs.clearDirectory(path.getAbsolutePath());
12802            } catch (RemoteException e) {
12803            }
12804        }
12805    }
12806
12807    static class OriginInfo {
12808        /**
12809         * Location where install is coming from, before it has been
12810         * copied/renamed into place. This could be a single monolithic APK
12811         * file, or a cluster directory. This location may be untrusted.
12812         */
12813        final File file;
12814        final String cid;
12815
12816        /**
12817         * Flag indicating that {@link #file} or {@link #cid} has already been
12818         * staged, meaning downstream users don't need to defensively copy the
12819         * contents.
12820         */
12821        final boolean staged;
12822
12823        /**
12824         * Flag indicating that {@link #file} or {@link #cid} is an already
12825         * installed app that is being moved.
12826         */
12827        final boolean existing;
12828
12829        final String resolvedPath;
12830        final File resolvedFile;
12831
12832        static OriginInfo fromNothing() {
12833            return new OriginInfo(null, null, false, false);
12834        }
12835
12836        static OriginInfo fromUntrustedFile(File file) {
12837            return new OriginInfo(file, null, false, false);
12838        }
12839
12840        static OriginInfo fromExistingFile(File file) {
12841            return new OriginInfo(file, null, false, true);
12842        }
12843
12844        static OriginInfo fromStagedFile(File file) {
12845            return new OriginInfo(file, null, true, false);
12846        }
12847
12848        static OriginInfo fromStagedContainer(String cid) {
12849            return new OriginInfo(null, cid, true, false);
12850        }
12851
12852        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12853            this.file = file;
12854            this.cid = cid;
12855            this.staged = staged;
12856            this.existing = existing;
12857
12858            if (cid != null) {
12859                resolvedPath = PackageHelper.getSdDir(cid);
12860                resolvedFile = new File(resolvedPath);
12861            } else if (file != null) {
12862                resolvedPath = file.getAbsolutePath();
12863                resolvedFile = file;
12864            } else {
12865                resolvedPath = null;
12866                resolvedFile = null;
12867            }
12868        }
12869    }
12870
12871    static class MoveInfo {
12872        final int moveId;
12873        final String fromUuid;
12874        final String toUuid;
12875        final String packageName;
12876        final String dataAppName;
12877        final int appId;
12878        final String seinfo;
12879        final int targetSdkVersion;
12880
12881        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12882                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12883            this.moveId = moveId;
12884            this.fromUuid = fromUuid;
12885            this.toUuid = toUuid;
12886            this.packageName = packageName;
12887            this.dataAppName = dataAppName;
12888            this.appId = appId;
12889            this.seinfo = seinfo;
12890            this.targetSdkVersion = targetSdkVersion;
12891        }
12892    }
12893
12894    static class VerificationInfo {
12895        /** A constant used to indicate that a uid value is not present. */
12896        public static final int NO_UID = -1;
12897
12898        /** URI referencing where the package was downloaded from. */
12899        final Uri originatingUri;
12900
12901        /** HTTP referrer URI associated with the originatingURI. */
12902        final Uri referrer;
12903
12904        /** UID of the application that the install request originated from. */
12905        final int originatingUid;
12906
12907        /** UID of application requesting the install */
12908        final int installerUid;
12909
12910        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12911            this.originatingUri = originatingUri;
12912            this.referrer = referrer;
12913            this.originatingUid = originatingUid;
12914            this.installerUid = installerUid;
12915        }
12916    }
12917
12918    class InstallParams extends HandlerParams {
12919        final OriginInfo origin;
12920        final MoveInfo move;
12921        final IPackageInstallObserver2 observer;
12922        int installFlags;
12923        final String installerPackageName;
12924        final String volumeUuid;
12925        private InstallArgs mArgs;
12926        private int mRet;
12927        final String packageAbiOverride;
12928        final String[] grantedRuntimePermissions;
12929        final VerificationInfo verificationInfo;
12930        final Certificate[][] certificates;
12931
12932        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12933                int installFlags, String installerPackageName, String volumeUuid,
12934                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12935                String[] grantedPermissions, Certificate[][] certificates) {
12936            super(user);
12937            this.origin = origin;
12938            this.move = move;
12939            this.observer = observer;
12940            this.installFlags = installFlags;
12941            this.installerPackageName = installerPackageName;
12942            this.volumeUuid = volumeUuid;
12943            this.verificationInfo = verificationInfo;
12944            this.packageAbiOverride = packageAbiOverride;
12945            this.grantedRuntimePermissions = grantedPermissions;
12946            this.certificates = certificates;
12947        }
12948
12949        @Override
12950        public String toString() {
12951            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12952                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12953        }
12954
12955        private int installLocationPolicy(PackageInfoLite pkgLite) {
12956            String packageName = pkgLite.packageName;
12957            int installLocation = pkgLite.installLocation;
12958            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12959            // reader
12960            synchronized (mPackages) {
12961                // Currently installed package which the new package is attempting to replace or
12962                // null if no such package is installed.
12963                PackageParser.Package installedPkg = mPackages.get(packageName);
12964                // Package which currently owns the data which the new package will own if installed.
12965                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12966                // will be null whereas dataOwnerPkg will contain information about the package
12967                // which was uninstalled while keeping its data.
12968                PackageParser.Package dataOwnerPkg = installedPkg;
12969                if (dataOwnerPkg  == null) {
12970                    PackageSetting ps = mSettings.mPackages.get(packageName);
12971                    if (ps != null) {
12972                        dataOwnerPkg = ps.pkg;
12973                    }
12974                }
12975
12976                if (dataOwnerPkg != null) {
12977                    // If installed, the package will get access to data left on the device by its
12978                    // predecessor. As a security measure, this is permited only if this is not a
12979                    // version downgrade or if the predecessor package is marked as debuggable and
12980                    // a downgrade is explicitly requested.
12981                    //
12982                    // On debuggable platform builds, downgrades are permitted even for
12983                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12984                    // not offer security guarantees and thus it's OK to disable some security
12985                    // mechanisms to make debugging/testing easier on those builds. However, even on
12986                    // debuggable builds downgrades of packages are permitted only if requested via
12987                    // installFlags. This is because we aim to keep the behavior of debuggable
12988                    // platform builds as close as possible to the behavior of non-debuggable
12989                    // platform builds.
12990                    final boolean downgradeRequested =
12991                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12992                    final boolean packageDebuggable =
12993                                (dataOwnerPkg.applicationInfo.flags
12994                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12995                    final boolean downgradePermitted =
12996                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12997                    if (!downgradePermitted) {
12998                        try {
12999                            checkDowngrade(dataOwnerPkg, pkgLite);
13000                        } catch (PackageManagerException e) {
13001                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13002                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13003                        }
13004                    }
13005                }
13006
13007                if (installedPkg != null) {
13008                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13009                        // Check for updated system application.
13010                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13011                            if (onSd) {
13012                                Slog.w(TAG, "Cannot install update to system app on sdcard");
13013                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13014                            }
13015                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13016                        } else {
13017                            if (onSd) {
13018                                // Install flag overrides everything.
13019                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13020                            }
13021                            // If current upgrade specifies particular preference
13022                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13023                                // Application explicitly specified internal.
13024                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13025                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13026                                // App explictly prefers external. Let policy decide
13027                            } else {
13028                                // Prefer previous location
13029                                if (isExternal(installedPkg)) {
13030                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13031                                }
13032                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13033                            }
13034                        }
13035                    } else {
13036                        // Invalid install. Return error code
13037                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13038                    }
13039                }
13040            }
13041            // All the special cases have been taken care of.
13042            // Return result based on recommended install location.
13043            if (onSd) {
13044                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13045            }
13046            return pkgLite.recommendedInstallLocation;
13047        }
13048
13049        /*
13050         * Invoke remote method to get package information and install
13051         * location values. Override install location based on default
13052         * policy if needed and then create install arguments based
13053         * on the install location.
13054         */
13055        public void handleStartCopy() throws RemoteException {
13056            int ret = PackageManager.INSTALL_SUCCEEDED;
13057
13058            // If we're already staged, we've firmly committed to an install location
13059            if (origin.staged) {
13060                if (origin.file != null) {
13061                    installFlags |= PackageManager.INSTALL_INTERNAL;
13062                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13063                } else if (origin.cid != null) {
13064                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13065                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13066                } else {
13067                    throw new IllegalStateException("Invalid stage location");
13068                }
13069            }
13070
13071            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13072            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13073            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13074            PackageInfoLite pkgLite = null;
13075
13076            if (onInt && onSd) {
13077                // Check if both bits are set.
13078                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13079                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13080            } else if (onSd && ephemeral) {
13081                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13082                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13083            } else {
13084                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13085                        packageAbiOverride);
13086
13087                if (DEBUG_EPHEMERAL && ephemeral) {
13088                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13089                }
13090
13091                /*
13092                 * If we have too little free space, try to free cache
13093                 * before giving up.
13094                 */
13095                if (!origin.staged && pkgLite.recommendedInstallLocation
13096                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13097                    // TODO: focus freeing disk space on the target device
13098                    final StorageManager storage = StorageManager.from(mContext);
13099                    final long lowThreshold = storage.getStorageLowBytes(
13100                            Environment.getDataDirectory());
13101
13102                    final long sizeBytes = mContainerService.calculateInstalledSize(
13103                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13104
13105                    try {
13106                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13107                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13108                                installFlags, packageAbiOverride);
13109                    } catch (InstallerException e) {
13110                        Slog.w(TAG, "Failed to free cache", e);
13111                    }
13112
13113                    /*
13114                     * The cache free must have deleted the file we
13115                     * downloaded to install.
13116                     *
13117                     * TODO: fix the "freeCache" call to not delete
13118                     *       the file we care about.
13119                     */
13120                    if (pkgLite.recommendedInstallLocation
13121                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13122                        pkgLite.recommendedInstallLocation
13123                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13124                    }
13125                }
13126            }
13127
13128            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13129                int loc = pkgLite.recommendedInstallLocation;
13130                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13131                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13132                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13133                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13134                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13135                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13136                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13137                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13138                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13139                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13140                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13141                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13142                } else {
13143                    // Override with defaults if needed.
13144                    loc = installLocationPolicy(pkgLite);
13145                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13146                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13147                    } else if (!onSd && !onInt) {
13148                        // Override install location with flags
13149                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13150                            // Set the flag to install on external media.
13151                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13152                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13153                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13154                            if (DEBUG_EPHEMERAL) {
13155                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13156                            }
13157                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13158                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13159                                    |PackageManager.INSTALL_INTERNAL);
13160                        } else {
13161                            // Make sure the flag for installing on external
13162                            // media is unset
13163                            installFlags |= PackageManager.INSTALL_INTERNAL;
13164                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13165                        }
13166                    }
13167                }
13168            }
13169
13170            final InstallArgs args = createInstallArgs(this);
13171            mArgs = args;
13172
13173            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13174                // TODO: http://b/22976637
13175                // Apps installed for "all" users use the device owner to verify the app
13176                UserHandle verifierUser = getUser();
13177                if (verifierUser == UserHandle.ALL) {
13178                    verifierUser = UserHandle.SYSTEM;
13179                }
13180
13181                /*
13182                 * Determine if we have any installed package verifiers. If we
13183                 * do, then we'll defer to them to verify the packages.
13184                 */
13185                final int requiredUid = mRequiredVerifierPackage == null ? -1
13186                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13187                                verifierUser.getIdentifier());
13188                if (!origin.existing && requiredUid != -1
13189                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13190                    final Intent verification = new Intent(
13191                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13192                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13193                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13194                            PACKAGE_MIME_TYPE);
13195                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13196
13197                    // Query all live verifiers based on current user state
13198                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13199                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13200
13201                    if (DEBUG_VERIFY) {
13202                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13203                                + verification.toString() + " with " + pkgLite.verifiers.length
13204                                + " optional verifiers");
13205                    }
13206
13207                    final int verificationId = mPendingVerificationToken++;
13208
13209                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13210
13211                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13212                            installerPackageName);
13213
13214                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13215                            installFlags);
13216
13217                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13218                            pkgLite.packageName);
13219
13220                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13221                            pkgLite.versionCode);
13222
13223                    if (verificationInfo != null) {
13224                        if (verificationInfo.originatingUri != null) {
13225                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13226                                    verificationInfo.originatingUri);
13227                        }
13228                        if (verificationInfo.referrer != null) {
13229                            verification.putExtra(Intent.EXTRA_REFERRER,
13230                                    verificationInfo.referrer);
13231                        }
13232                        if (verificationInfo.originatingUid >= 0) {
13233                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13234                                    verificationInfo.originatingUid);
13235                        }
13236                        if (verificationInfo.installerUid >= 0) {
13237                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13238                                    verificationInfo.installerUid);
13239                        }
13240                    }
13241
13242                    final PackageVerificationState verificationState = new PackageVerificationState(
13243                            requiredUid, args);
13244
13245                    mPendingVerification.append(verificationId, verificationState);
13246
13247                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13248                            receivers, verificationState);
13249
13250                    /*
13251                     * If any sufficient verifiers were listed in the package
13252                     * manifest, attempt to ask them.
13253                     */
13254                    if (sufficientVerifiers != null) {
13255                        final int N = sufficientVerifiers.size();
13256                        if (N == 0) {
13257                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13258                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13259                        } else {
13260                            for (int i = 0; i < N; i++) {
13261                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13262
13263                                final Intent sufficientIntent = new Intent(verification);
13264                                sufficientIntent.setComponent(verifierComponent);
13265                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13266                            }
13267                        }
13268                    }
13269
13270                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13271                            mRequiredVerifierPackage, receivers);
13272                    if (ret == PackageManager.INSTALL_SUCCEEDED
13273                            && mRequiredVerifierPackage != null) {
13274                        Trace.asyncTraceBegin(
13275                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13276                        /*
13277                         * Send the intent to the required verification agent,
13278                         * but only start the verification timeout after the
13279                         * target BroadcastReceivers have run.
13280                         */
13281                        verification.setComponent(requiredVerifierComponent);
13282                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13283                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13284                                new BroadcastReceiver() {
13285                                    @Override
13286                                    public void onReceive(Context context, Intent intent) {
13287                                        final Message msg = mHandler
13288                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13289                                        msg.arg1 = verificationId;
13290                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13291                                    }
13292                                }, null, 0, null, null);
13293
13294                        /*
13295                         * We don't want the copy to proceed until verification
13296                         * succeeds, so null out this field.
13297                         */
13298                        mArgs = null;
13299                    }
13300                } else {
13301                    /*
13302                     * No package verification is enabled, so immediately start
13303                     * the remote call to initiate copy using temporary file.
13304                     */
13305                    ret = args.copyApk(mContainerService, true);
13306                }
13307            }
13308
13309            mRet = ret;
13310        }
13311
13312        @Override
13313        void handleReturnCode() {
13314            // If mArgs is null, then MCS couldn't be reached. When it
13315            // reconnects, it will try again to install. At that point, this
13316            // will succeed.
13317            if (mArgs != null) {
13318                processPendingInstall(mArgs, mRet);
13319            }
13320        }
13321
13322        @Override
13323        void handleServiceError() {
13324            mArgs = createInstallArgs(this);
13325            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13326        }
13327
13328        public boolean isForwardLocked() {
13329            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13330        }
13331    }
13332
13333    /**
13334     * Used during creation of InstallArgs
13335     *
13336     * @param installFlags package installation flags
13337     * @return true if should be installed on external storage
13338     */
13339    private static boolean installOnExternalAsec(int installFlags) {
13340        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13341            return false;
13342        }
13343        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13344            return true;
13345        }
13346        return false;
13347    }
13348
13349    /**
13350     * Used during creation of InstallArgs
13351     *
13352     * @param installFlags package installation flags
13353     * @return true if should be installed as forward locked
13354     */
13355    private static boolean installForwardLocked(int installFlags) {
13356        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13357    }
13358
13359    private InstallArgs createInstallArgs(InstallParams params) {
13360        if (params.move != null) {
13361            return new MoveInstallArgs(params);
13362        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13363            return new AsecInstallArgs(params);
13364        } else {
13365            return new FileInstallArgs(params);
13366        }
13367    }
13368
13369    /**
13370     * Create args that describe an existing installed package. Typically used
13371     * when cleaning up old installs, or used as a move source.
13372     */
13373    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13374            String resourcePath, String[] instructionSets) {
13375        final boolean isInAsec;
13376        if (installOnExternalAsec(installFlags)) {
13377            /* Apps on SD card are always in ASEC containers. */
13378            isInAsec = true;
13379        } else if (installForwardLocked(installFlags)
13380                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13381            /*
13382             * Forward-locked apps are only in ASEC containers if they're the
13383             * new style
13384             */
13385            isInAsec = true;
13386        } else {
13387            isInAsec = false;
13388        }
13389
13390        if (isInAsec) {
13391            return new AsecInstallArgs(codePath, instructionSets,
13392                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13393        } else {
13394            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13395        }
13396    }
13397
13398    static abstract class InstallArgs {
13399        /** @see InstallParams#origin */
13400        final OriginInfo origin;
13401        /** @see InstallParams#move */
13402        final MoveInfo move;
13403
13404        final IPackageInstallObserver2 observer;
13405        // Always refers to PackageManager flags only
13406        final int installFlags;
13407        final String installerPackageName;
13408        final String volumeUuid;
13409        final UserHandle user;
13410        final String abiOverride;
13411        final String[] installGrantPermissions;
13412        /** If non-null, drop an async trace when the install completes */
13413        final String traceMethod;
13414        final int traceCookie;
13415        final Certificate[][] certificates;
13416
13417        // The list of instruction sets supported by this app. This is currently
13418        // only used during the rmdex() phase to clean up resources. We can get rid of this
13419        // if we move dex files under the common app path.
13420        /* nullable */ String[] instructionSets;
13421
13422        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13423                int installFlags, String installerPackageName, String volumeUuid,
13424                UserHandle user, String[] instructionSets,
13425                String abiOverride, String[] installGrantPermissions,
13426                String traceMethod, int traceCookie, Certificate[][] certificates) {
13427            this.origin = origin;
13428            this.move = move;
13429            this.installFlags = installFlags;
13430            this.observer = observer;
13431            this.installerPackageName = installerPackageName;
13432            this.volumeUuid = volumeUuid;
13433            this.user = user;
13434            this.instructionSets = instructionSets;
13435            this.abiOverride = abiOverride;
13436            this.installGrantPermissions = installGrantPermissions;
13437            this.traceMethod = traceMethod;
13438            this.traceCookie = traceCookie;
13439            this.certificates = certificates;
13440        }
13441
13442        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13443        abstract int doPreInstall(int status);
13444
13445        /**
13446         * Rename package into final resting place. All paths on the given
13447         * scanned package should be updated to reflect the rename.
13448         */
13449        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13450        abstract int doPostInstall(int status, int uid);
13451
13452        /** @see PackageSettingBase#codePathString */
13453        abstract String getCodePath();
13454        /** @see PackageSettingBase#resourcePathString */
13455        abstract String getResourcePath();
13456
13457        // Need installer lock especially for dex file removal.
13458        abstract void cleanUpResourcesLI();
13459        abstract boolean doPostDeleteLI(boolean delete);
13460
13461        /**
13462         * Called before the source arguments are copied. This is used mostly
13463         * for MoveParams when it needs to read the source file to put it in the
13464         * destination.
13465         */
13466        int doPreCopy() {
13467            return PackageManager.INSTALL_SUCCEEDED;
13468        }
13469
13470        /**
13471         * Called after the source arguments are copied. This is used mostly for
13472         * MoveParams when it needs to read the source file to put it in the
13473         * destination.
13474         */
13475        int doPostCopy(int uid) {
13476            return PackageManager.INSTALL_SUCCEEDED;
13477        }
13478
13479        protected boolean isFwdLocked() {
13480            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13481        }
13482
13483        protected boolean isExternalAsec() {
13484            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13485        }
13486
13487        protected boolean isEphemeral() {
13488            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13489        }
13490
13491        UserHandle getUser() {
13492            return user;
13493        }
13494    }
13495
13496    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13497        if (!allCodePaths.isEmpty()) {
13498            if (instructionSets == null) {
13499                throw new IllegalStateException("instructionSet == null");
13500            }
13501            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13502            for (String codePath : allCodePaths) {
13503                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13504                    try {
13505                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13506                    } catch (InstallerException ignored) {
13507                    }
13508                }
13509            }
13510        }
13511    }
13512
13513    /**
13514     * Logic to handle installation of non-ASEC applications, including copying
13515     * and renaming logic.
13516     */
13517    class FileInstallArgs extends InstallArgs {
13518        private File codeFile;
13519        private File resourceFile;
13520
13521        // Example topology:
13522        // /data/app/com.example/base.apk
13523        // /data/app/com.example/split_foo.apk
13524        // /data/app/com.example/lib/arm/libfoo.so
13525        // /data/app/com.example/lib/arm64/libfoo.so
13526        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13527
13528        /** New install */
13529        FileInstallArgs(InstallParams params) {
13530            super(params.origin, params.move, params.observer, params.installFlags,
13531                    params.installerPackageName, params.volumeUuid,
13532                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13533                    params.grantedRuntimePermissions,
13534                    params.traceMethod, params.traceCookie, params.certificates);
13535            if (isFwdLocked()) {
13536                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13537            }
13538        }
13539
13540        /** Existing install */
13541        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13542            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13543                    null, null, null, 0, null /*certificates*/);
13544            this.codeFile = (codePath != null) ? new File(codePath) : null;
13545            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13546        }
13547
13548        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13549            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13550            try {
13551                return doCopyApk(imcs, temp);
13552            } finally {
13553                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13554            }
13555        }
13556
13557        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13558            if (origin.staged) {
13559                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13560                codeFile = origin.file;
13561                resourceFile = origin.file;
13562                return PackageManager.INSTALL_SUCCEEDED;
13563            }
13564
13565            try {
13566                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13567                final File tempDir =
13568                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13569                codeFile = tempDir;
13570                resourceFile = tempDir;
13571            } catch (IOException e) {
13572                Slog.w(TAG, "Failed to create copy file: " + e);
13573                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13574            }
13575
13576            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13577                @Override
13578                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13579                    if (!FileUtils.isValidExtFilename(name)) {
13580                        throw new IllegalArgumentException("Invalid filename: " + name);
13581                    }
13582                    try {
13583                        final File file = new File(codeFile, name);
13584                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13585                                O_RDWR | O_CREAT, 0644);
13586                        Os.chmod(file.getAbsolutePath(), 0644);
13587                        return new ParcelFileDescriptor(fd);
13588                    } catch (ErrnoException e) {
13589                        throw new RemoteException("Failed to open: " + e.getMessage());
13590                    }
13591                }
13592            };
13593
13594            int ret = PackageManager.INSTALL_SUCCEEDED;
13595            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13596            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13597                Slog.e(TAG, "Failed to copy package");
13598                return ret;
13599            }
13600
13601            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13602            NativeLibraryHelper.Handle handle = null;
13603            try {
13604                handle = NativeLibraryHelper.Handle.create(codeFile);
13605                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13606                        abiOverride);
13607            } catch (IOException e) {
13608                Slog.e(TAG, "Copying native libraries failed", e);
13609                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13610            } finally {
13611                IoUtils.closeQuietly(handle);
13612            }
13613
13614            return ret;
13615        }
13616
13617        int doPreInstall(int status) {
13618            if (status != PackageManager.INSTALL_SUCCEEDED) {
13619                cleanUp();
13620            }
13621            return status;
13622        }
13623
13624        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13625            if (status != PackageManager.INSTALL_SUCCEEDED) {
13626                cleanUp();
13627                return false;
13628            }
13629
13630            final File targetDir = codeFile.getParentFile();
13631            final File beforeCodeFile = codeFile;
13632            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13633
13634            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13635            try {
13636                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13637            } catch (ErrnoException e) {
13638                Slog.w(TAG, "Failed to rename", e);
13639                return false;
13640            }
13641
13642            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13643                Slog.w(TAG, "Failed to restorecon");
13644                return false;
13645            }
13646
13647            // Reflect the rename internally
13648            codeFile = afterCodeFile;
13649            resourceFile = afterCodeFile;
13650
13651            // Reflect the rename in scanned details
13652            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13653            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13654                    afterCodeFile, pkg.baseCodePath));
13655            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13656                    afterCodeFile, pkg.splitCodePaths));
13657
13658            // Reflect the rename in app info
13659            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13660            pkg.setApplicationInfoCodePath(pkg.codePath);
13661            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13662            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13663            pkg.setApplicationInfoResourcePath(pkg.codePath);
13664            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13665            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13666
13667            return true;
13668        }
13669
13670        int doPostInstall(int status, int uid) {
13671            if (status != PackageManager.INSTALL_SUCCEEDED) {
13672                cleanUp();
13673            }
13674            return status;
13675        }
13676
13677        @Override
13678        String getCodePath() {
13679            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13680        }
13681
13682        @Override
13683        String getResourcePath() {
13684            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13685        }
13686
13687        private boolean cleanUp() {
13688            if (codeFile == null || !codeFile.exists()) {
13689                return false;
13690            }
13691
13692            removeCodePathLI(codeFile);
13693
13694            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13695                resourceFile.delete();
13696            }
13697
13698            return true;
13699        }
13700
13701        void cleanUpResourcesLI() {
13702            // Try enumerating all code paths before deleting
13703            List<String> allCodePaths = Collections.EMPTY_LIST;
13704            if (codeFile != null && codeFile.exists()) {
13705                try {
13706                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13707                    allCodePaths = pkg.getAllCodePaths();
13708                } catch (PackageParserException e) {
13709                    // Ignored; we tried our best
13710                }
13711            }
13712
13713            cleanUp();
13714            removeDexFiles(allCodePaths, instructionSets);
13715        }
13716
13717        boolean doPostDeleteLI(boolean delete) {
13718            // XXX err, shouldn't we respect the delete flag?
13719            cleanUpResourcesLI();
13720            return true;
13721        }
13722    }
13723
13724    private boolean isAsecExternal(String cid) {
13725        final String asecPath = PackageHelper.getSdFilesystem(cid);
13726        return !asecPath.startsWith(mAsecInternalPath);
13727    }
13728
13729    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13730            PackageManagerException {
13731        if (copyRet < 0) {
13732            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13733                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13734                throw new PackageManagerException(copyRet, message);
13735            }
13736        }
13737    }
13738
13739    /**
13740     * Extract the MountService "container ID" from the full code path of an
13741     * .apk.
13742     */
13743    static String cidFromCodePath(String fullCodePath) {
13744        int eidx = fullCodePath.lastIndexOf("/");
13745        String subStr1 = fullCodePath.substring(0, eidx);
13746        int sidx = subStr1.lastIndexOf("/");
13747        return subStr1.substring(sidx+1, eidx);
13748    }
13749
13750    /**
13751     * Logic to handle installation of ASEC applications, including copying and
13752     * renaming logic.
13753     */
13754    class AsecInstallArgs extends InstallArgs {
13755        static final String RES_FILE_NAME = "pkg.apk";
13756        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13757
13758        String cid;
13759        String packagePath;
13760        String resourcePath;
13761
13762        /** New install */
13763        AsecInstallArgs(InstallParams params) {
13764            super(params.origin, params.move, params.observer, params.installFlags,
13765                    params.installerPackageName, params.volumeUuid,
13766                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13767                    params.grantedRuntimePermissions,
13768                    params.traceMethod, params.traceCookie, params.certificates);
13769        }
13770
13771        /** Existing install */
13772        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13773                        boolean isExternal, boolean isForwardLocked) {
13774            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13775              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13776                    instructionSets, null, null, null, 0, null /*certificates*/);
13777            // Hackily pretend we're still looking at a full code path
13778            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13779                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13780            }
13781
13782            // Extract cid from fullCodePath
13783            int eidx = fullCodePath.lastIndexOf("/");
13784            String subStr1 = fullCodePath.substring(0, eidx);
13785            int sidx = subStr1.lastIndexOf("/");
13786            cid = subStr1.substring(sidx+1, eidx);
13787            setMountPath(subStr1);
13788        }
13789
13790        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13791            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13792              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13793                    instructionSets, null, null, null, 0, null /*certificates*/);
13794            this.cid = cid;
13795            setMountPath(PackageHelper.getSdDir(cid));
13796        }
13797
13798        void createCopyFile() {
13799            cid = mInstallerService.allocateExternalStageCidLegacy();
13800        }
13801
13802        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13803            if (origin.staged && origin.cid != null) {
13804                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13805                cid = origin.cid;
13806                setMountPath(PackageHelper.getSdDir(cid));
13807                return PackageManager.INSTALL_SUCCEEDED;
13808            }
13809
13810            if (temp) {
13811                createCopyFile();
13812            } else {
13813                /*
13814                 * Pre-emptively destroy the container since it's destroyed if
13815                 * copying fails due to it existing anyway.
13816                 */
13817                PackageHelper.destroySdDir(cid);
13818            }
13819
13820            final String newMountPath = imcs.copyPackageToContainer(
13821                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13822                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13823
13824            if (newMountPath != null) {
13825                setMountPath(newMountPath);
13826                return PackageManager.INSTALL_SUCCEEDED;
13827            } else {
13828                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13829            }
13830        }
13831
13832        @Override
13833        String getCodePath() {
13834            return packagePath;
13835        }
13836
13837        @Override
13838        String getResourcePath() {
13839            return resourcePath;
13840        }
13841
13842        int doPreInstall(int status) {
13843            if (status != PackageManager.INSTALL_SUCCEEDED) {
13844                // Destroy container
13845                PackageHelper.destroySdDir(cid);
13846            } else {
13847                boolean mounted = PackageHelper.isContainerMounted(cid);
13848                if (!mounted) {
13849                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13850                            Process.SYSTEM_UID);
13851                    if (newMountPath != null) {
13852                        setMountPath(newMountPath);
13853                    } else {
13854                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13855                    }
13856                }
13857            }
13858            return status;
13859        }
13860
13861        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13862            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13863            String newMountPath = null;
13864            if (PackageHelper.isContainerMounted(cid)) {
13865                // Unmount the container
13866                if (!PackageHelper.unMountSdDir(cid)) {
13867                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13868                    return false;
13869                }
13870            }
13871            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13872                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13873                        " which might be stale. Will try to clean up.");
13874                // Clean up the stale container and proceed to recreate.
13875                if (!PackageHelper.destroySdDir(newCacheId)) {
13876                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13877                    return false;
13878                }
13879                // Successfully cleaned up stale container. Try to rename again.
13880                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13881                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13882                            + " inspite of cleaning it up.");
13883                    return false;
13884                }
13885            }
13886            if (!PackageHelper.isContainerMounted(newCacheId)) {
13887                Slog.w(TAG, "Mounting container " + newCacheId);
13888                newMountPath = PackageHelper.mountSdDir(newCacheId,
13889                        getEncryptKey(), Process.SYSTEM_UID);
13890            } else {
13891                newMountPath = PackageHelper.getSdDir(newCacheId);
13892            }
13893            if (newMountPath == null) {
13894                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13895                return false;
13896            }
13897            Log.i(TAG, "Succesfully renamed " + cid +
13898                    " to " + newCacheId +
13899                    " at new path: " + newMountPath);
13900            cid = newCacheId;
13901
13902            final File beforeCodeFile = new File(packagePath);
13903            setMountPath(newMountPath);
13904            final File afterCodeFile = new File(packagePath);
13905
13906            // Reflect the rename in scanned details
13907            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13908            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13909                    afterCodeFile, pkg.baseCodePath));
13910            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13911                    afterCodeFile, pkg.splitCodePaths));
13912
13913            // Reflect the rename in app info
13914            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13915            pkg.setApplicationInfoCodePath(pkg.codePath);
13916            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13917            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13918            pkg.setApplicationInfoResourcePath(pkg.codePath);
13919            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13920            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13921
13922            return true;
13923        }
13924
13925        private void setMountPath(String mountPath) {
13926            final File mountFile = new File(mountPath);
13927
13928            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13929            if (monolithicFile.exists()) {
13930                packagePath = monolithicFile.getAbsolutePath();
13931                if (isFwdLocked()) {
13932                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13933                } else {
13934                    resourcePath = packagePath;
13935                }
13936            } else {
13937                packagePath = mountFile.getAbsolutePath();
13938                resourcePath = packagePath;
13939            }
13940        }
13941
13942        int doPostInstall(int status, int uid) {
13943            if (status != PackageManager.INSTALL_SUCCEEDED) {
13944                cleanUp();
13945            } else {
13946                final int groupOwner;
13947                final String protectedFile;
13948                if (isFwdLocked()) {
13949                    groupOwner = UserHandle.getSharedAppGid(uid);
13950                    protectedFile = RES_FILE_NAME;
13951                } else {
13952                    groupOwner = -1;
13953                    protectedFile = null;
13954                }
13955
13956                if (uid < Process.FIRST_APPLICATION_UID
13957                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13958                    Slog.e(TAG, "Failed to finalize " + cid);
13959                    PackageHelper.destroySdDir(cid);
13960                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13961                }
13962
13963                boolean mounted = PackageHelper.isContainerMounted(cid);
13964                if (!mounted) {
13965                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13966                }
13967            }
13968            return status;
13969        }
13970
13971        private void cleanUp() {
13972            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13973
13974            // Destroy secure container
13975            PackageHelper.destroySdDir(cid);
13976        }
13977
13978        private List<String> getAllCodePaths() {
13979            final File codeFile = new File(getCodePath());
13980            if (codeFile != null && codeFile.exists()) {
13981                try {
13982                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13983                    return pkg.getAllCodePaths();
13984                } catch (PackageParserException e) {
13985                    // Ignored; we tried our best
13986                }
13987            }
13988            return Collections.EMPTY_LIST;
13989        }
13990
13991        void cleanUpResourcesLI() {
13992            // Enumerate all code paths before deleting
13993            cleanUpResourcesLI(getAllCodePaths());
13994        }
13995
13996        private void cleanUpResourcesLI(List<String> allCodePaths) {
13997            cleanUp();
13998            removeDexFiles(allCodePaths, instructionSets);
13999        }
14000
14001        String getPackageName() {
14002            return getAsecPackageName(cid);
14003        }
14004
14005        boolean doPostDeleteLI(boolean delete) {
14006            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14007            final List<String> allCodePaths = getAllCodePaths();
14008            boolean mounted = PackageHelper.isContainerMounted(cid);
14009            if (mounted) {
14010                // Unmount first
14011                if (PackageHelper.unMountSdDir(cid)) {
14012                    mounted = false;
14013                }
14014            }
14015            if (!mounted && delete) {
14016                cleanUpResourcesLI(allCodePaths);
14017            }
14018            return !mounted;
14019        }
14020
14021        @Override
14022        int doPreCopy() {
14023            if (isFwdLocked()) {
14024                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14025                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14026                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14027                }
14028            }
14029
14030            return PackageManager.INSTALL_SUCCEEDED;
14031        }
14032
14033        @Override
14034        int doPostCopy(int uid) {
14035            if (isFwdLocked()) {
14036                if (uid < Process.FIRST_APPLICATION_UID
14037                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14038                                RES_FILE_NAME)) {
14039                    Slog.e(TAG, "Failed to finalize " + cid);
14040                    PackageHelper.destroySdDir(cid);
14041                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14042                }
14043            }
14044
14045            return PackageManager.INSTALL_SUCCEEDED;
14046        }
14047    }
14048
14049    /**
14050     * Logic to handle movement of existing installed applications.
14051     */
14052    class MoveInstallArgs extends InstallArgs {
14053        private File codeFile;
14054        private File resourceFile;
14055
14056        /** New install */
14057        MoveInstallArgs(InstallParams params) {
14058            super(params.origin, params.move, params.observer, params.installFlags,
14059                    params.installerPackageName, params.volumeUuid,
14060                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14061                    params.grantedRuntimePermissions,
14062                    params.traceMethod, params.traceCookie, params.certificates);
14063        }
14064
14065        int copyApk(IMediaContainerService imcs, boolean temp) {
14066            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14067                    + move.fromUuid + " to " + move.toUuid);
14068            synchronized (mInstaller) {
14069                try {
14070                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14071                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14072                } catch (InstallerException e) {
14073                    Slog.w(TAG, "Failed to move app", e);
14074                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14075                }
14076            }
14077
14078            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14079            resourceFile = codeFile;
14080            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14081
14082            return PackageManager.INSTALL_SUCCEEDED;
14083        }
14084
14085        int doPreInstall(int status) {
14086            if (status != PackageManager.INSTALL_SUCCEEDED) {
14087                cleanUp(move.toUuid);
14088            }
14089            return status;
14090        }
14091
14092        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14093            if (status != PackageManager.INSTALL_SUCCEEDED) {
14094                cleanUp(move.toUuid);
14095                return false;
14096            }
14097
14098            // Reflect the move in app info
14099            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14100            pkg.setApplicationInfoCodePath(pkg.codePath);
14101            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14102            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14103            pkg.setApplicationInfoResourcePath(pkg.codePath);
14104            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14105            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14106
14107            return true;
14108        }
14109
14110        int doPostInstall(int status, int uid) {
14111            if (status == PackageManager.INSTALL_SUCCEEDED) {
14112                cleanUp(move.fromUuid);
14113            } else {
14114                cleanUp(move.toUuid);
14115            }
14116            return status;
14117        }
14118
14119        @Override
14120        String getCodePath() {
14121            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14122        }
14123
14124        @Override
14125        String getResourcePath() {
14126            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14127        }
14128
14129        private boolean cleanUp(String volumeUuid) {
14130            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14131                    move.dataAppName);
14132            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14133            final int[] userIds = sUserManager.getUserIds();
14134            synchronized (mInstallLock) {
14135                // Clean up both app data and code
14136                // All package moves are frozen until finished
14137                for (int userId : userIds) {
14138                    try {
14139                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14140                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14141                    } catch (InstallerException e) {
14142                        Slog.w(TAG, String.valueOf(e));
14143                    }
14144                }
14145                removeCodePathLI(codeFile);
14146            }
14147            return true;
14148        }
14149
14150        void cleanUpResourcesLI() {
14151            throw new UnsupportedOperationException();
14152        }
14153
14154        boolean doPostDeleteLI(boolean delete) {
14155            throw new UnsupportedOperationException();
14156        }
14157    }
14158
14159    static String getAsecPackageName(String packageCid) {
14160        int idx = packageCid.lastIndexOf("-");
14161        if (idx == -1) {
14162            return packageCid;
14163        }
14164        return packageCid.substring(0, idx);
14165    }
14166
14167    // Utility method used to create code paths based on package name and available index.
14168    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14169        String idxStr = "";
14170        int idx = 1;
14171        // Fall back to default value of idx=1 if prefix is not
14172        // part of oldCodePath
14173        if (oldCodePath != null) {
14174            String subStr = oldCodePath;
14175            // Drop the suffix right away
14176            if (suffix != null && subStr.endsWith(suffix)) {
14177                subStr = subStr.substring(0, subStr.length() - suffix.length());
14178            }
14179            // If oldCodePath already contains prefix find out the
14180            // ending index to either increment or decrement.
14181            int sidx = subStr.lastIndexOf(prefix);
14182            if (sidx != -1) {
14183                subStr = subStr.substring(sidx + prefix.length());
14184                if (subStr != null) {
14185                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14186                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14187                    }
14188                    try {
14189                        idx = Integer.parseInt(subStr);
14190                        if (idx <= 1) {
14191                            idx++;
14192                        } else {
14193                            idx--;
14194                        }
14195                    } catch(NumberFormatException e) {
14196                    }
14197                }
14198            }
14199        }
14200        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14201        return prefix + idxStr;
14202    }
14203
14204    private File getNextCodePath(File targetDir, String packageName) {
14205        int suffix = 1;
14206        File result;
14207        do {
14208            result = new File(targetDir, packageName + "-" + suffix);
14209            suffix++;
14210        } while (result.exists());
14211        return result;
14212    }
14213
14214    // Utility method that returns the relative package path with respect
14215    // to the installation directory. Like say for /data/data/com.test-1.apk
14216    // string com.test-1 is returned.
14217    static String deriveCodePathName(String codePath) {
14218        if (codePath == null) {
14219            return null;
14220        }
14221        final File codeFile = new File(codePath);
14222        final String name = codeFile.getName();
14223        if (codeFile.isDirectory()) {
14224            return name;
14225        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14226            final int lastDot = name.lastIndexOf('.');
14227            return name.substring(0, lastDot);
14228        } else {
14229            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14230            return null;
14231        }
14232    }
14233
14234    static class PackageInstalledInfo {
14235        String name;
14236        int uid;
14237        // The set of users that originally had this package installed.
14238        int[] origUsers;
14239        // The set of users that now have this package installed.
14240        int[] newUsers;
14241        PackageParser.Package pkg;
14242        int returnCode;
14243        String returnMsg;
14244        PackageRemovedInfo removedInfo;
14245        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14246
14247        public void setError(int code, String msg) {
14248            setReturnCode(code);
14249            setReturnMessage(msg);
14250            Slog.w(TAG, msg);
14251        }
14252
14253        public void setError(String msg, PackageParserException e) {
14254            setReturnCode(e.error);
14255            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14256            Slog.w(TAG, msg, e);
14257        }
14258
14259        public void setError(String msg, PackageManagerException e) {
14260            returnCode = e.error;
14261            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14262            Slog.w(TAG, msg, e);
14263        }
14264
14265        public void setReturnCode(int returnCode) {
14266            this.returnCode = returnCode;
14267            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14268            for (int i = 0; i < childCount; i++) {
14269                addedChildPackages.valueAt(i).returnCode = returnCode;
14270            }
14271        }
14272
14273        private void setReturnMessage(String returnMsg) {
14274            this.returnMsg = returnMsg;
14275            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14276            for (int i = 0; i < childCount; i++) {
14277                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14278            }
14279        }
14280
14281        // In some error cases we want to convey more info back to the observer
14282        String origPackage;
14283        String origPermission;
14284    }
14285
14286    /*
14287     * Install a non-existing package.
14288     */
14289    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14290            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14291            PackageInstalledInfo res) {
14292        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14293
14294        // Remember this for later, in case we need to rollback this install
14295        String pkgName = pkg.packageName;
14296
14297        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14298
14299        synchronized(mPackages) {
14300            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14301            if (renamedPackage != null) {
14302                // A package with the same name is already installed, though
14303                // it has been renamed to an older name.  The package we
14304                // are trying to install should be installed as an update to
14305                // the existing one, but that has not been requested, so bail.
14306                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14307                        + " without first uninstalling package running as "
14308                        + renamedPackage);
14309                return;
14310            }
14311            if (mPackages.containsKey(pkgName)) {
14312                // Don't allow installation over an existing package with the same name.
14313                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14314                        + " without first uninstalling.");
14315                return;
14316            }
14317        }
14318
14319        try {
14320            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14321                    System.currentTimeMillis(), user);
14322
14323            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14324
14325            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14326                prepareAppDataAfterInstallLIF(newPackage);
14327
14328            } else {
14329                // Remove package from internal structures, but keep around any
14330                // data that might have already existed
14331                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14332                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14333            }
14334        } catch (PackageManagerException e) {
14335            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14336        }
14337
14338        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14339    }
14340
14341    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14342        // Can't rotate keys during boot or if sharedUser.
14343        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14344                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14345            return false;
14346        }
14347        // app is using upgradeKeySets; make sure all are valid
14348        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14349        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14350        for (int i = 0; i < upgradeKeySets.length; i++) {
14351            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14352                Slog.wtf(TAG, "Package "
14353                         + (oldPs.name != null ? oldPs.name : "<null>")
14354                         + " contains upgrade-key-set reference to unknown key-set: "
14355                         + upgradeKeySets[i]
14356                         + " reverting to signatures check.");
14357                return false;
14358            }
14359        }
14360        return true;
14361    }
14362
14363    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14364        // Upgrade keysets are being used.  Determine if new package has a superset of the
14365        // required keys.
14366        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14367        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14368        for (int i = 0; i < upgradeKeySets.length; i++) {
14369            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14370            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14371                return true;
14372            }
14373        }
14374        return false;
14375    }
14376
14377    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14378        try (DigestInputStream digestStream =
14379                new DigestInputStream(new FileInputStream(file), digest)) {
14380            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14381        }
14382    }
14383
14384    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14385            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14386        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14387
14388        final PackageParser.Package oldPackage;
14389        final String pkgName = pkg.packageName;
14390        final int[] allUsers;
14391        final int[] installedUsers;
14392
14393        synchronized(mPackages) {
14394            oldPackage = mPackages.get(pkgName);
14395            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14396
14397            // don't allow upgrade to target a release SDK from a pre-release SDK
14398            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14399                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14400            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14401                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14402            if (oldTargetsPreRelease
14403                    && !newTargetsPreRelease
14404                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14405                Slog.w(TAG, "Can't install package targeting released sdk");
14406                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14407                return;
14408            }
14409
14410            // don't allow an upgrade from full to ephemeral
14411            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14412            if (isEphemeral && !oldIsEphemeral) {
14413                // can't downgrade from full to ephemeral
14414                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14415                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14416                return;
14417            }
14418
14419            // verify signatures are valid
14420            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14421            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14422                if (!checkUpgradeKeySetLP(ps, pkg)) {
14423                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14424                            "New package not signed by keys specified by upgrade-keysets: "
14425                                    + pkgName);
14426                    return;
14427                }
14428            } else {
14429                // default to original signature matching
14430                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14431                        != PackageManager.SIGNATURE_MATCH) {
14432                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14433                            "New package has a different signature: " + pkgName);
14434                    return;
14435                }
14436            }
14437
14438            // don't allow a system upgrade unless the upgrade hash matches
14439            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14440                byte[] digestBytes = null;
14441                try {
14442                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14443                    updateDigest(digest, new File(pkg.baseCodePath));
14444                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14445                        for (String path : pkg.splitCodePaths) {
14446                            updateDigest(digest, new File(path));
14447                        }
14448                    }
14449                    digestBytes = digest.digest();
14450                } catch (NoSuchAlgorithmException | IOException e) {
14451                    res.setError(INSTALL_FAILED_INVALID_APK,
14452                            "Could not compute hash: " + pkgName);
14453                    return;
14454                }
14455                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14456                    res.setError(INSTALL_FAILED_INVALID_APK,
14457                            "New package fails restrict-update check: " + pkgName);
14458                    return;
14459                }
14460                // retain upgrade restriction
14461                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14462            }
14463
14464            // Check for shared user id changes
14465            String invalidPackageName =
14466                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14467            if (invalidPackageName != null) {
14468                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14469                        "Package " + invalidPackageName + " tried to change user "
14470                                + oldPackage.mSharedUserId);
14471                return;
14472            }
14473
14474            // In case of rollback, remember per-user/profile install state
14475            allUsers = sUserManager.getUserIds();
14476            installedUsers = ps.queryInstalledUsers(allUsers, true);
14477        }
14478
14479        // Update what is removed
14480        res.removedInfo = new PackageRemovedInfo();
14481        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14482        res.removedInfo.removedPackage = oldPackage.packageName;
14483        res.removedInfo.isUpdate = true;
14484        res.removedInfo.origUsers = installedUsers;
14485        final int childCount = (oldPackage.childPackages != null)
14486                ? oldPackage.childPackages.size() : 0;
14487        for (int i = 0; i < childCount; i++) {
14488            boolean childPackageUpdated = false;
14489            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14490            if (res.addedChildPackages != null) {
14491                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14492                if (childRes != null) {
14493                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14494                    childRes.removedInfo.removedPackage = childPkg.packageName;
14495                    childRes.removedInfo.isUpdate = true;
14496                    childPackageUpdated = true;
14497                }
14498            }
14499            if (!childPackageUpdated) {
14500                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14501                childRemovedRes.removedPackage = childPkg.packageName;
14502                childRemovedRes.isUpdate = false;
14503                childRemovedRes.dataRemoved = true;
14504                synchronized (mPackages) {
14505                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14506                    if (childPs != null) {
14507                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14508                    }
14509                }
14510                if (res.removedInfo.removedChildPackages == null) {
14511                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14512                }
14513                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14514            }
14515        }
14516
14517        boolean sysPkg = (isSystemApp(oldPackage));
14518        if (sysPkg) {
14519            // Set the system/privileged flags as needed
14520            final boolean privileged =
14521                    (oldPackage.applicationInfo.privateFlags
14522                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14523            final int systemPolicyFlags = policyFlags
14524                    | PackageParser.PARSE_IS_SYSTEM
14525                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14526
14527            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14528                    user, allUsers, installerPackageName, res);
14529        } else {
14530            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14531                    user, allUsers, installerPackageName, res);
14532        }
14533    }
14534
14535    public List<String> getPreviousCodePaths(String packageName) {
14536        final PackageSetting ps = mSettings.mPackages.get(packageName);
14537        final List<String> result = new ArrayList<String>();
14538        if (ps != null && ps.oldCodePaths != null) {
14539            result.addAll(ps.oldCodePaths);
14540        }
14541        return result;
14542    }
14543
14544    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14545            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14546            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14547        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14548                + deletedPackage);
14549
14550        String pkgName = deletedPackage.packageName;
14551        boolean deletedPkg = true;
14552        boolean addedPkg = false;
14553        boolean updatedSettings = false;
14554        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14555        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14556                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14557
14558        final long origUpdateTime = (pkg.mExtras != null)
14559                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14560
14561        // First delete the existing package while retaining the data directory
14562        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14563                res.removedInfo, true, pkg)) {
14564            // If the existing package wasn't successfully deleted
14565            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14566            deletedPkg = false;
14567        } else {
14568            // Successfully deleted the old package; proceed with replace.
14569
14570            // If deleted package lived in a container, give users a chance to
14571            // relinquish resources before killing.
14572            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14573                if (DEBUG_INSTALL) {
14574                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14575                }
14576                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14577                final ArrayList<String> pkgList = new ArrayList<String>(1);
14578                pkgList.add(deletedPackage.applicationInfo.packageName);
14579                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14580            }
14581
14582            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14583                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14584            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14585
14586            try {
14587                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14588                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14589                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14590
14591                // Update the in-memory copy of the previous code paths.
14592                PackageSetting ps = mSettings.mPackages.get(pkgName);
14593                if (!killApp) {
14594                    if (ps.oldCodePaths == null) {
14595                        ps.oldCodePaths = new ArraySet<>();
14596                    }
14597                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14598                    if (deletedPackage.splitCodePaths != null) {
14599                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14600                    }
14601                } else {
14602                    ps.oldCodePaths = null;
14603                }
14604                if (ps.childPackageNames != null) {
14605                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14606                        final String childPkgName = ps.childPackageNames.get(i);
14607                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14608                        childPs.oldCodePaths = ps.oldCodePaths;
14609                    }
14610                }
14611                prepareAppDataAfterInstallLIF(newPackage);
14612                addedPkg = true;
14613            } catch (PackageManagerException e) {
14614                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14615            }
14616        }
14617
14618        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14619            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14620
14621            // Revert all internal state mutations and added folders for the failed install
14622            if (addedPkg) {
14623                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14624                        res.removedInfo, true, null);
14625            }
14626
14627            // Restore the old package
14628            if (deletedPkg) {
14629                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14630                File restoreFile = new File(deletedPackage.codePath);
14631                // Parse old package
14632                boolean oldExternal = isExternal(deletedPackage);
14633                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14634                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14635                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14636                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14637                try {
14638                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14639                            null);
14640                } catch (PackageManagerException e) {
14641                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14642                            + e.getMessage());
14643                    return;
14644                }
14645
14646                synchronized (mPackages) {
14647                    // Ensure the installer package name up to date
14648                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14649
14650                    // Update permissions for restored package
14651                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14652
14653                    mSettings.writeLPr();
14654                }
14655
14656                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14657            }
14658        } else {
14659            synchronized (mPackages) {
14660                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14661                if (ps != null) {
14662                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14663                    if (res.removedInfo.removedChildPackages != null) {
14664                        final int childCount = res.removedInfo.removedChildPackages.size();
14665                        // Iterate in reverse as we may modify the collection
14666                        for (int i = childCount - 1; i >= 0; i--) {
14667                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14668                            if (res.addedChildPackages.containsKey(childPackageName)) {
14669                                res.removedInfo.removedChildPackages.removeAt(i);
14670                            } else {
14671                                PackageRemovedInfo childInfo = res.removedInfo
14672                                        .removedChildPackages.valueAt(i);
14673                                childInfo.removedForAllUsers = mPackages.get(
14674                                        childInfo.removedPackage) == null;
14675                            }
14676                        }
14677                    }
14678                }
14679            }
14680        }
14681    }
14682
14683    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14684            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14685            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14686        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14687                + ", old=" + deletedPackage);
14688
14689        final boolean disabledSystem;
14690
14691        // Remove existing system package
14692        removePackageLI(deletedPackage, true);
14693
14694        synchronized (mPackages) {
14695            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14696        }
14697        if (!disabledSystem) {
14698            // We didn't need to disable the .apk as a current system package,
14699            // which means we are replacing another update that is already
14700            // installed.  We need to make sure to delete the older one's .apk.
14701            res.removedInfo.args = createInstallArgsForExisting(0,
14702                    deletedPackage.applicationInfo.getCodePath(),
14703                    deletedPackage.applicationInfo.getResourcePath(),
14704                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14705        } else {
14706            res.removedInfo.args = null;
14707        }
14708
14709        // Successfully disabled the old package. Now proceed with re-installation
14710        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14711                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14712        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14713
14714        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14715        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14716                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14717
14718        PackageParser.Package newPackage = null;
14719        try {
14720            // Add the package to the internal data structures
14721            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14722
14723            // Set the update and install times
14724            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14725            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14726                    System.currentTimeMillis());
14727
14728            // Update the package dynamic state if succeeded
14729            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14730                // Now that the install succeeded make sure we remove data
14731                // directories for any child package the update removed.
14732                final int deletedChildCount = (deletedPackage.childPackages != null)
14733                        ? deletedPackage.childPackages.size() : 0;
14734                final int newChildCount = (newPackage.childPackages != null)
14735                        ? newPackage.childPackages.size() : 0;
14736                for (int i = 0; i < deletedChildCount; i++) {
14737                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14738                    boolean childPackageDeleted = true;
14739                    for (int j = 0; j < newChildCount; j++) {
14740                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14741                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14742                            childPackageDeleted = false;
14743                            break;
14744                        }
14745                    }
14746                    if (childPackageDeleted) {
14747                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14748                                deletedChildPkg.packageName);
14749                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14750                            PackageRemovedInfo removedChildRes = res.removedInfo
14751                                    .removedChildPackages.get(deletedChildPkg.packageName);
14752                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14753                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14754                        }
14755                    }
14756                }
14757
14758                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14759                prepareAppDataAfterInstallLIF(newPackage);
14760            }
14761        } catch (PackageManagerException e) {
14762            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14763            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14764        }
14765
14766        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14767            // Re installation failed. Restore old information
14768            // Remove new pkg information
14769            if (newPackage != null) {
14770                removeInstalledPackageLI(newPackage, true);
14771            }
14772            // Add back the old system package
14773            try {
14774                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14775            } catch (PackageManagerException e) {
14776                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14777            }
14778
14779            synchronized (mPackages) {
14780                if (disabledSystem) {
14781                    enableSystemPackageLPw(deletedPackage);
14782                }
14783
14784                // Ensure the installer package name up to date
14785                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14786
14787                // Update permissions for restored package
14788                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14789
14790                mSettings.writeLPr();
14791            }
14792
14793            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14794                    + " after failed upgrade");
14795        }
14796    }
14797
14798    /**
14799     * Checks whether the parent or any of the child packages have a change shared
14800     * user. For a package to be a valid update the shred users of the parent and
14801     * the children should match. We may later support changing child shared users.
14802     * @param oldPkg The updated package.
14803     * @param newPkg The update package.
14804     * @return The shared user that change between the versions.
14805     */
14806    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14807            PackageParser.Package newPkg) {
14808        // Check parent shared user
14809        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14810            return newPkg.packageName;
14811        }
14812        // Check child shared users
14813        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14814        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14815        for (int i = 0; i < newChildCount; i++) {
14816            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14817            // If this child was present, did it have the same shared user?
14818            for (int j = 0; j < oldChildCount; j++) {
14819                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14820                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14821                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14822                    return newChildPkg.packageName;
14823                }
14824            }
14825        }
14826        return null;
14827    }
14828
14829    private void removeNativeBinariesLI(PackageSetting ps) {
14830        // Remove the lib path for the parent package
14831        if (ps != null) {
14832            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14833            // Remove the lib path for the child packages
14834            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14835            for (int i = 0; i < childCount; i++) {
14836                PackageSetting childPs = null;
14837                synchronized (mPackages) {
14838                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14839                }
14840                if (childPs != null) {
14841                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14842                            .legacyNativeLibraryPathString);
14843                }
14844            }
14845        }
14846    }
14847
14848    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14849        // Enable the parent package
14850        mSettings.enableSystemPackageLPw(pkg.packageName);
14851        // Enable the child packages
14852        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14853        for (int i = 0; i < childCount; i++) {
14854            PackageParser.Package childPkg = pkg.childPackages.get(i);
14855            mSettings.enableSystemPackageLPw(childPkg.packageName);
14856        }
14857    }
14858
14859    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14860            PackageParser.Package newPkg) {
14861        // Disable the parent package (parent always replaced)
14862        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14863        // Disable the child packages
14864        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14865        for (int i = 0; i < childCount; i++) {
14866            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14867            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14868            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14869        }
14870        return disabled;
14871    }
14872
14873    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14874            String installerPackageName) {
14875        // Enable the parent package
14876        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14877        // Enable the child packages
14878        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14879        for (int i = 0; i < childCount; i++) {
14880            PackageParser.Package childPkg = pkg.childPackages.get(i);
14881            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14882        }
14883    }
14884
14885    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14886        // Collect all used permissions in the UID
14887        ArraySet<String> usedPermissions = new ArraySet<>();
14888        final int packageCount = su.packages.size();
14889        for (int i = 0; i < packageCount; i++) {
14890            PackageSetting ps = su.packages.valueAt(i);
14891            if (ps.pkg == null) {
14892                continue;
14893            }
14894            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14895            for (int j = 0; j < requestedPermCount; j++) {
14896                String permission = ps.pkg.requestedPermissions.get(j);
14897                BasePermission bp = mSettings.mPermissions.get(permission);
14898                if (bp != null) {
14899                    usedPermissions.add(permission);
14900                }
14901            }
14902        }
14903
14904        PermissionsState permissionsState = su.getPermissionsState();
14905        // Prune install permissions
14906        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14907        final int installPermCount = installPermStates.size();
14908        for (int i = installPermCount - 1; i >= 0;  i--) {
14909            PermissionState permissionState = installPermStates.get(i);
14910            if (!usedPermissions.contains(permissionState.getName())) {
14911                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14912                if (bp != null) {
14913                    permissionsState.revokeInstallPermission(bp);
14914                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14915                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14916                }
14917            }
14918        }
14919
14920        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14921
14922        // Prune runtime permissions
14923        for (int userId : allUserIds) {
14924            List<PermissionState> runtimePermStates = permissionsState
14925                    .getRuntimePermissionStates(userId);
14926            final int runtimePermCount = runtimePermStates.size();
14927            for (int i = runtimePermCount - 1; i >= 0; i--) {
14928                PermissionState permissionState = runtimePermStates.get(i);
14929                if (!usedPermissions.contains(permissionState.getName())) {
14930                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14931                    if (bp != null) {
14932                        permissionsState.revokeRuntimePermission(bp, userId);
14933                        permissionsState.updatePermissionFlags(bp, userId,
14934                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14935                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14936                                runtimePermissionChangedUserIds, userId);
14937                    }
14938                }
14939            }
14940        }
14941
14942        return runtimePermissionChangedUserIds;
14943    }
14944
14945    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14946            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14947        // Update the parent package setting
14948        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14949                res, user);
14950        // Update the child packages setting
14951        final int childCount = (newPackage.childPackages != null)
14952                ? newPackage.childPackages.size() : 0;
14953        for (int i = 0; i < childCount; i++) {
14954            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14955            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14956            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14957                    childRes.origUsers, childRes, user);
14958        }
14959    }
14960
14961    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14962            String installerPackageName, int[] allUsers, int[] installedForUsers,
14963            PackageInstalledInfo res, UserHandle user) {
14964        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14965
14966        String pkgName = newPackage.packageName;
14967        synchronized (mPackages) {
14968            //write settings. the installStatus will be incomplete at this stage.
14969            //note that the new package setting would have already been
14970            //added to mPackages. It hasn't been persisted yet.
14971            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14972            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14973            mSettings.writeLPr();
14974            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14975        }
14976
14977        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14978        synchronized (mPackages) {
14979            updatePermissionsLPw(newPackage.packageName, newPackage,
14980                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14981                            ? UPDATE_PERMISSIONS_ALL : 0));
14982            // For system-bundled packages, we assume that installing an upgraded version
14983            // of the package implies that the user actually wants to run that new code,
14984            // so we enable the package.
14985            PackageSetting ps = mSettings.mPackages.get(pkgName);
14986            final int userId = user.getIdentifier();
14987            if (ps != null) {
14988                if (isSystemApp(newPackage)) {
14989                    if (DEBUG_INSTALL) {
14990                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14991                    }
14992                    // Enable system package for requested users
14993                    if (res.origUsers != null) {
14994                        for (int origUserId : res.origUsers) {
14995                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14996                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14997                                        origUserId, installerPackageName);
14998                            }
14999                        }
15000                    }
15001                    // Also convey the prior install/uninstall state
15002                    if (allUsers != null && installedForUsers != null) {
15003                        for (int currentUserId : allUsers) {
15004                            final boolean installed = ArrayUtils.contains(
15005                                    installedForUsers, currentUserId);
15006                            if (DEBUG_INSTALL) {
15007                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15008                            }
15009                            ps.setInstalled(installed, currentUserId);
15010                        }
15011                        // these install state changes will be persisted in the
15012                        // upcoming call to mSettings.writeLPr().
15013                    }
15014                }
15015                // It's implied that when a user requests installation, they want the app to be
15016                // installed and enabled.
15017                if (userId != UserHandle.USER_ALL) {
15018                    ps.setInstalled(true, userId);
15019                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15020                }
15021            }
15022            res.name = pkgName;
15023            res.uid = newPackage.applicationInfo.uid;
15024            res.pkg = newPackage;
15025            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15026            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15027            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15028            //to update install status
15029            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15030            mSettings.writeLPr();
15031            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15032        }
15033
15034        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15035    }
15036
15037    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15038        try {
15039            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15040            installPackageLI(args, res);
15041        } finally {
15042            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15043        }
15044    }
15045
15046    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15047        final int installFlags = args.installFlags;
15048        final String installerPackageName = args.installerPackageName;
15049        final String volumeUuid = args.volumeUuid;
15050        final File tmpPackageFile = new File(args.getCodePath());
15051        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15052        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15053                || (args.volumeUuid != null));
15054        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15055        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15056        boolean replace = false;
15057        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15058        if (args.move != null) {
15059            // moving a complete application; perform an initial scan on the new install location
15060            scanFlags |= SCAN_INITIAL;
15061        }
15062        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15063            scanFlags |= SCAN_DONT_KILL_APP;
15064        }
15065
15066        // Result object to be returned
15067        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15068
15069        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15070
15071        // Sanity check
15072        if (ephemeral && (forwardLocked || onExternal)) {
15073            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15074                    + " external=" + onExternal);
15075            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15076            return;
15077        }
15078
15079        // Retrieve PackageSettings and parse package
15080        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15081                | PackageParser.PARSE_ENFORCE_CODE
15082                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15083                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15084                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15085                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15086        PackageParser pp = new PackageParser();
15087        pp.setSeparateProcesses(mSeparateProcesses);
15088        pp.setDisplayMetrics(mMetrics);
15089
15090        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15091        final PackageParser.Package pkg;
15092        try {
15093            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15094        } catch (PackageParserException e) {
15095            res.setError("Failed parse during installPackageLI", e);
15096            return;
15097        } finally {
15098            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15099        }
15100
15101        // If we are installing a clustered package add results for the children
15102        if (pkg.childPackages != null) {
15103            synchronized (mPackages) {
15104                final int childCount = pkg.childPackages.size();
15105                for (int i = 0; i < childCount; i++) {
15106                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15107                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15108                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15109                    childRes.pkg = childPkg;
15110                    childRes.name = childPkg.packageName;
15111                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15112                    if (childPs != null) {
15113                        childRes.origUsers = childPs.queryInstalledUsers(
15114                                sUserManager.getUserIds(), true);
15115                    }
15116                    if ((mPackages.containsKey(childPkg.packageName))) {
15117                        childRes.removedInfo = new PackageRemovedInfo();
15118                        childRes.removedInfo.removedPackage = childPkg.packageName;
15119                    }
15120                    if (res.addedChildPackages == null) {
15121                        res.addedChildPackages = new ArrayMap<>();
15122                    }
15123                    res.addedChildPackages.put(childPkg.packageName, childRes);
15124                }
15125            }
15126        }
15127
15128        // If package doesn't declare API override, mark that we have an install
15129        // time CPU ABI override.
15130        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15131            pkg.cpuAbiOverride = args.abiOverride;
15132        }
15133
15134        String pkgName = res.name = pkg.packageName;
15135        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15136            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15137                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15138                return;
15139            }
15140        }
15141
15142        try {
15143            // either use what we've been given or parse directly from the APK
15144            if (args.certificates != null) {
15145                try {
15146                    PackageParser.populateCertificates(pkg, args.certificates);
15147                } catch (PackageParserException e) {
15148                    // there was something wrong with the certificates we were given;
15149                    // try to pull them from the APK
15150                    PackageParser.collectCertificates(pkg, parseFlags);
15151                }
15152            } else {
15153                PackageParser.collectCertificates(pkg, parseFlags);
15154            }
15155        } catch (PackageParserException e) {
15156            res.setError("Failed collect during installPackageLI", e);
15157            return;
15158        }
15159
15160        // Get rid of all references to package scan path via parser.
15161        pp = null;
15162        String oldCodePath = null;
15163        boolean systemApp = false;
15164        synchronized (mPackages) {
15165            // Check if installing already existing package
15166            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15167                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15168                if (pkg.mOriginalPackages != null
15169                        && pkg.mOriginalPackages.contains(oldName)
15170                        && mPackages.containsKey(oldName)) {
15171                    // This package is derived from an original package,
15172                    // and this device has been updating from that original
15173                    // name.  We must continue using the original name, so
15174                    // rename the new package here.
15175                    pkg.setPackageName(oldName);
15176                    pkgName = pkg.packageName;
15177                    replace = true;
15178                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15179                            + oldName + " pkgName=" + pkgName);
15180                } else if (mPackages.containsKey(pkgName)) {
15181                    // This package, under its official name, already exists
15182                    // on the device; we should replace it.
15183                    replace = true;
15184                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15185                }
15186
15187                // Child packages are installed through the parent package
15188                if (pkg.parentPackage != null) {
15189                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15190                            "Package " + pkg.packageName + " is child of package "
15191                                    + pkg.parentPackage.parentPackage + ". Child packages "
15192                                    + "can be updated only through the parent package.");
15193                    return;
15194                }
15195
15196                if (replace) {
15197                    // Prevent apps opting out from runtime permissions
15198                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15199                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15200                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15201                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15202                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15203                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15204                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15205                                        + " doesn't support runtime permissions but the old"
15206                                        + " target SDK " + oldTargetSdk + " does.");
15207                        return;
15208                    }
15209
15210                    // Prevent installing of child packages
15211                    if (oldPackage.parentPackage != null) {
15212                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15213                                "Package " + pkg.packageName + " is child of package "
15214                                        + oldPackage.parentPackage + ". Child packages "
15215                                        + "can be updated only through the parent package.");
15216                        return;
15217                    }
15218                }
15219            }
15220
15221            PackageSetting ps = mSettings.mPackages.get(pkgName);
15222            if (ps != null) {
15223                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15224
15225                // Quick sanity check that we're signed correctly if updating;
15226                // we'll check this again later when scanning, but we want to
15227                // bail early here before tripping over redefined permissions.
15228                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15229                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15230                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15231                                + pkg.packageName + " upgrade keys do not match the "
15232                                + "previously installed version");
15233                        return;
15234                    }
15235                } else {
15236                    try {
15237                        verifySignaturesLP(ps, pkg);
15238                    } catch (PackageManagerException e) {
15239                        res.setError(e.error, e.getMessage());
15240                        return;
15241                    }
15242                }
15243
15244                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15245                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15246                    systemApp = (ps.pkg.applicationInfo.flags &
15247                            ApplicationInfo.FLAG_SYSTEM) != 0;
15248                }
15249                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15250            }
15251
15252            // Check whether the newly-scanned package wants to define an already-defined perm
15253            int N = pkg.permissions.size();
15254            for (int i = N-1; i >= 0; i--) {
15255                PackageParser.Permission perm = pkg.permissions.get(i);
15256                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15257                if (bp != null) {
15258                    // If the defining package is signed with our cert, it's okay.  This
15259                    // also includes the "updating the same package" case, of course.
15260                    // "updating same package" could also involve key-rotation.
15261                    final boolean sigsOk;
15262                    if (bp.sourcePackage.equals(pkg.packageName)
15263                            && (bp.packageSetting instanceof PackageSetting)
15264                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15265                                    scanFlags))) {
15266                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15267                    } else {
15268                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15269                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15270                    }
15271                    if (!sigsOk) {
15272                        // If the owning package is the system itself, we log but allow
15273                        // install to proceed; we fail the install on all other permission
15274                        // redefinitions.
15275                        if (!bp.sourcePackage.equals("android")) {
15276                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15277                                    + pkg.packageName + " attempting to redeclare permission "
15278                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15279                            res.origPermission = perm.info.name;
15280                            res.origPackage = bp.sourcePackage;
15281                            return;
15282                        } else {
15283                            Slog.w(TAG, "Package " + pkg.packageName
15284                                    + " attempting to redeclare system permission "
15285                                    + perm.info.name + "; ignoring new declaration");
15286                            pkg.permissions.remove(i);
15287                        }
15288                    }
15289                }
15290            }
15291        }
15292
15293        if (systemApp) {
15294            if (onExternal) {
15295                // Abort update; system app can't be replaced with app on sdcard
15296                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15297                        "Cannot install updates to system apps on sdcard");
15298                return;
15299            } else if (ephemeral) {
15300                // Abort update; system app can't be replaced with an ephemeral app
15301                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15302                        "Cannot update a system app with an ephemeral app");
15303                return;
15304            }
15305        }
15306
15307        if (args.move != null) {
15308            // We did an in-place move, so dex is ready to roll
15309            scanFlags |= SCAN_NO_DEX;
15310            scanFlags |= SCAN_MOVE;
15311
15312            synchronized (mPackages) {
15313                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15314                if (ps == null) {
15315                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15316                            "Missing settings for moved package " + pkgName);
15317                }
15318
15319                // We moved the entire application as-is, so bring over the
15320                // previously derived ABI information.
15321                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15322                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15323            }
15324
15325        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15326            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15327            scanFlags |= SCAN_NO_DEX;
15328
15329            try {
15330                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15331                    args.abiOverride : pkg.cpuAbiOverride);
15332                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15333                        true /*extractLibs*/, mAppLib32InstallDir);
15334            } catch (PackageManagerException pme) {
15335                Slog.e(TAG, "Error deriving application ABI", pme);
15336                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15337                return;
15338            }
15339
15340            // Shared libraries for the package need to be updated.
15341            synchronized (mPackages) {
15342                try {
15343                    updateSharedLibrariesLPr(pkg, null);
15344                } catch (PackageManagerException e) {
15345                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15346                }
15347            }
15348            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15349            // Do not run PackageDexOptimizer through the local performDexOpt
15350            // method because `pkg` may not be in `mPackages` yet.
15351            //
15352            // Also, don't fail application installs if the dexopt step fails.
15353            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15354                    null /* instructionSets */, false /* checkProfiles */,
15355                    getCompilerFilterForReason(REASON_INSTALL),
15356                    getOrCreateCompilerPackageStats(pkg));
15357            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15358
15359            // Notify BackgroundDexOptService that the package has been changed.
15360            // If this is an update of a package which used to fail to compile,
15361            // BDOS will remove it from its blacklist.
15362            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15363        }
15364
15365        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15366            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15367            return;
15368        }
15369
15370        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15371
15372        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15373                "installPackageLI")) {
15374            if (replace) {
15375                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15376                        installerPackageName, res);
15377            } else {
15378                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15379                        args.user, installerPackageName, volumeUuid, res);
15380            }
15381        }
15382        synchronized (mPackages) {
15383            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15384            if (ps != null) {
15385                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15386            }
15387
15388            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15389            for (int i = 0; i < childCount; i++) {
15390                PackageParser.Package childPkg = pkg.childPackages.get(i);
15391                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15392                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15393                if (childPs != null) {
15394                    childRes.newUsers = childPs.queryInstalledUsers(
15395                            sUserManager.getUserIds(), true);
15396                }
15397            }
15398        }
15399    }
15400
15401    private void startIntentFilterVerifications(int userId, boolean replacing,
15402            PackageParser.Package pkg) {
15403        if (mIntentFilterVerifierComponent == null) {
15404            Slog.w(TAG, "No IntentFilter verification will not be done as "
15405                    + "there is no IntentFilterVerifier available!");
15406            return;
15407        }
15408
15409        final int verifierUid = getPackageUid(
15410                mIntentFilterVerifierComponent.getPackageName(),
15411                MATCH_DEBUG_TRIAGED_MISSING,
15412                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15413
15414        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15415        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15416        mHandler.sendMessage(msg);
15417
15418        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15419        for (int i = 0; i < childCount; i++) {
15420            PackageParser.Package childPkg = pkg.childPackages.get(i);
15421            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15422            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15423            mHandler.sendMessage(msg);
15424        }
15425    }
15426
15427    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15428            PackageParser.Package pkg) {
15429        int size = pkg.activities.size();
15430        if (size == 0) {
15431            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15432                    "No activity, so no need to verify any IntentFilter!");
15433            return;
15434        }
15435
15436        final boolean hasDomainURLs = hasDomainURLs(pkg);
15437        if (!hasDomainURLs) {
15438            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15439                    "No domain URLs, so no need to verify any IntentFilter!");
15440            return;
15441        }
15442
15443        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15444                + " if any IntentFilter from the " + size
15445                + " Activities needs verification ...");
15446
15447        int count = 0;
15448        final String packageName = pkg.packageName;
15449
15450        synchronized (mPackages) {
15451            // If this is a new install and we see that we've already run verification for this
15452            // package, we have nothing to do: it means the state was restored from backup.
15453            if (!replacing) {
15454                IntentFilterVerificationInfo ivi =
15455                        mSettings.getIntentFilterVerificationLPr(packageName);
15456                if (ivi != null) {
15457                    if (DEBUG_DOMAIN_VERIFICATION) {
15458                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15459                                + ivi.getStatusString());
15460                    }
15461                    return;
15462                }
15463            }
15464
15465            // If any filters need to be verified, then all need to be.
15466            boolean needToVerify = false;
15467            for (PackageParser.Activity a : pkg.activities) {
15468                for (ActivityIntentInfo filter : a.intents) {
15469                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15470                        if (DEBUG_DOMAIN_VERIFICATION) {
15471                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15472                        }
15473                        needToVerify = true;
15474                        break;
15475                    }
15476                }
15477            }
15478
15479            if (needToVerify) {
15480                final int verificationId = mIntentFilterVerificationToken++;
15481                for (PackageParser.Activity a : pkg.activities) {
15482                    for (ActivityIntentInfo filter : a.intents) {
15483                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15484                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15485                                    "Verification needed for IntentFilter:" + filter.toString());
15486                            mIntentFilterVerifier.addOneIntentFilterVerification(
15487                                    verifierUid, userId, verificationId, filter, packageName);
15488                            count++;
15489                        }
15490                    }
15491                }
15492            }
15493        }
15494
15495        if (count > 0) {
15496            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15497                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15498                    +  " for userId:" + userId);
15499            mIntentFilterVerifier.startVerifications(userId);
15500        } else {
15501            if (DEBUG_DOMAIN_VERIFICATION) {
15502                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15503            }
15504        }
15505    }
15506
15507    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15508        final ComponentName cn  = filter.activity.getComponentName();
15509        final String packageName = cn.getPackageName();
15510
15511        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15512                packageName);
15513        if (ivi == null) {
15514            return true;
15515        }
15516        int status = ivi.getStatus();
15517        switch (status) {
15518            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15519            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15520                return true;
15521
15522            default:
15523                // Nothing to do
15524                return false;
15525        }
15526    }
15527
15528    private static boolean isMultiArch(ApplicationInfo info) {
15529        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15530    }
15531
15532    private static boolean isExternal(PackageParser.Package pkg) {
15533        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15534    }
15535
15536    private static boolean isExternal(PackageSetting ps) {
15537        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15538    }
15539
15540    private static boolean isEphemeral(PackageParser.Package pkg) {
15541        return pkg.applicationInfo.isEphemeralApp();
15542    }
15543
15544    private static boolean isEphemeral(PackageSetting ps) {
15545        return ps.pkg != null && isEphemeral(ps.pkg);
15546    }
15547
15548    private static boolean isSystemApp(PackageParser.Package pkg) {
15549        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15550    }
15551
15552    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15553        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15554    }
15555
15556    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15557        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15558    }
15559
15560    private static boolean isSystemApp(PackageSetting ps) {
15561        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15562    }
15563
15564    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15565        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15566    }
15567
15568    private int packageFlagsToInstallFlags(PackageSetting ps) {
15569        int installFlags = 0;
15570        if (isEphemeral(ps)) {
15571            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15572        }
15573        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15574            // This existing package was an external ASEC install when we have
15575            // the external flag without a UUID
15576            installFlags |= PackageManager.INSTALL_EXTERNAL;
15577        }
15578        if (ps.isForwardLocked()) {
15579            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15580        }
15581        return installFlags;
15582    }
15583
15584    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15585        if (isExternal(pkg)) {
15586            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15587                return StorageManager.UUID_PRIMARY_PHYSICAL;
15588            } else {
15589                return pkg.volumeUuid;
15590            }
15591        } else {
15592            return StorageManager.UUID_PRIVATE_INTERNAL;
15593        }
15594    }
15595
15596    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15597        if (isExternal(pkg)) {
15598            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15599                return mSettings.getExternalVersion();
15600            } else {
15601                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15602            }
15603        } else {
15604            return mSettings.getInternalVersion();
15605        }
15606    }
15607
15608    private void deleteTempPackageFiles() {
15609        final FilenameFilter filter = new FilenameFilter() {
15610            public boolean accept(File dir, String name) {
15611                return name.startsWith("vmdl") && name.endsWith(".tmp");
15612            }
15613        };
15614        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15615            file.delete();
15616        }
15617    }
15618
15619    @Override
15620    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15621            int flags) {
15622        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15623                flags);
15624    }
15625
15626    @Override
15627    public void deletePackage(final String packageName,
15628            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15629        mContext.enforceCallingOrSelfPermission(
15630                android.Manifest.permission.DELETE_PACKAGES, null);
15631        Preconditions.checkNotNull(packageName);
15632        Preconditions.checkNotNull(observer);
15633        final int uid = Binder.getCallingUid();
15634        if (!isOrphaned(packageName)
15635                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15636            try {
15637                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15638                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15639                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15640                observer.onUserActionRequired(intent);
15641            } catch (RemoteException re) {
15642            }
15643            return;
15644        }
15645        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15646        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15647        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15648            mContext.enforceCallingOrSelfPermission(
15649                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15650                    "deletePackage for user " + userId);
15651        }
15652
15653        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15654            try {
15655                observer.onPackageDeleted(packageName,
15656                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15657            } catch (RemoteException re) {
15658            }
15659            return;
15660        }
15661
15662        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15663            try {
15664                observer.onPackageDeleted(packageName,
15665                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15666            } catch (RemoteException re) {
15667            }
15668            return;
15669        }
15670
15671        if (DEBUG_REMOVE) {
15672            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15673                    + " deleteAllUsers: " + deleteAllUsers );
15674        }
15675        // Queue up an async operation since the package deletion may take a little while.
15676        mHandler.post(new Runnable() {
15677            public void run() {
15678                mHandler.removeCallbacks(this);
15679                int returnCode;
15680                if (!deleteAllUsers) {
15681                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15682                } else {
15683                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15684                    // If nobody is blocking uninstall, proceed with delete for all users
15685                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15686                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15687                    } else {
15688                        // Otherwise uninstall individually for users with blockUninstalls=false
15689                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15690                        for (int userId : users) {
15691                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15692                                returnCode = deletePackageX(packageName, userId, userFlags);
15693                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15694                                    Slog.w(TAG, "Package delete failed for user " + userId
15695                                            + ", returnCode " + returnCode);
15696                                }
15697                            }
15698                        }
15699                        // The app has only been marked uninstalled for certain users.
15700                        // We still need to report that delete was blocked
15701                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15702                    }
15703                }
15704                try {
15705                    observer.onPackageDeleted(packageName, returnCode, null);
15706                } catch (RemoteException e) {
15707                    Log.i(TAG, "Observer no longer exists.");
15708                } //end catch
15709            } //end run
15710        });
15711    }
15712
15713    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15714        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15715              || callingUid == Process.SYSTEM_UID) {
15716            return true;
15717        }
15718        final int callingUserId = UserHandle.getUserId(callingUid);
15719        // If the caller installed the pkgName, then allow it to silently uninstall.
15720        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15721            return true;
15722        }
15723
15724        // Allow package verifier to silently uninstall.
15725        if (mRequiredVerifierPackage != null &&
15726                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15727            return true;
15728        }
15729
15730        // Allow package uninstaller to silently uninstall.
15731        if (mRequiredUninstallerPackage != null &&
15732                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15733            return true;
15734        }
15735
15736        // Allow storage manager to silently uninstall.
15737        if (mStorageManagerPackage != null &&
15738                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15739            return true;
15740        }
15741        return false;
15742    }
15743
15744    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15745        int[] result = EMPTY_INT_ARRAY;
15746        for (int userId : userIds) {
15747            if (getBlockUninstallForUser(packageName, userId)) {
15748                result = ArrayUtils.appendInt(result, userId);
15749            }
15750        }
15751        return result;
15752    }
15753
15754    @Override
15755    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15756        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15757    }
15758
15759    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15760        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15761                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15762        try {
15763            if (dpm != null) {
15764                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15765                        /* callingUserOnly =*/ false);
15766                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15767                        : deviceOwnerComponentName.getPackageName();
15768                // Does the package contains the device owner?
15769                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15770                // this check is probably not needed, since DO should be registered as a device
15771                // admin on some user too. (Original bug for this: b/17657954)
15772                if (packageName.equals(deviceOwnerPackageName)) {
15773                    return true;
15774                }
15775                // Does it contain a device admin for any user?
15776                int[] users;
15777                if (userId == UserHandle.USER_ALL) {
15778                    users = sUserManager.getUserIds();
15779                } else {
15780                    users = new int[]{userId};
15781                }
15782                for (int i = 0; i < users.length; ++i) {
15783                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15784                        return true;
15785                    }
15786                }
15787            }
15788        } catch (RemoteException e) {
15789        }
15790        return false;
15791    }
15792
15793    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15794        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15795    }
15796
15797    /**
15798     *  This method is an internal method that could be get invoked either
15799     *  to delete an installed package or to clean up a failed installation.
15800     *  After deleting an installed package, a broadcast is sent to notify any
15801     *  listeners that the package has been removed. For cleaning up a failed
15802     *  installation, the broadcast is not necessary since the package's
15803     *  installation wouldn't have sent the initial broadcast either
15804     *  The key steps in deleting a package are
15805     *  deleting the package information in internal structures like mPackages,
15806     *  deleting the packages base directories through installd
15807     *  updating mSettings to reflect current status
15808     *  persisting settings for later use
15809     *  sending a broadcast if necessary
15810     */
15811    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15812        final PackageRemovedInfo info = new PackageRemovedInfo();
15813        final boolean res;
15814
15815        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15816                ? UserHandle.USER_ALL : userId;
15817
15818        if (isPackageDeviceAdmin(packageName, removeUser)) {
15819            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15820            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15821        }
15822
15823        PackageSetting uninstalledPs = null;
15824
15825        // for the uninstall-updates case and restricted profiles, remember the per-
15826        // user handle installed state
15827        int[] allUsers;
15828        synchronized (mPackages) {
15829            uninstalledPs = mSettings.mPackages.get(packageName);
15830            if (uninstalledPs == null) {
15831                Slog.w(TAG, "Not removing non-existent package " + packageName);
15832                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15833            }
15834            allUsers = sUserManager.getUserIds();
15835            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15836        }
15837
15838        final int freezeUser;
15839        if (isUpdatedSystemApp(uninstalledPs)
15840                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15841            // We're downgrading a system app, which will apply to all users, so
15842            // freeze them all during the downgrade
15843            freezeUser = UserHandle.USER_ALL;
15844        } else {
15845            freezeUser = removeUser;
15846        }
15847
15848        synchronized (mInstallLock) {
15849            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15850            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15851                    deleteFlags, "deletePackageX")) {
15852                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15853                        deleteFlags | REMOVE_CHATTY, info, true, null);
15854            }
15855            synchronized (mPackages) {
15856                if (res) {
15857                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15858                }
15859            }
15860        }
15861
15862        if (res) {
15863            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15864            info.sendPackageRemovedBroadcasts(killApp);
15865            info.sendSystemPackageUpdatedBroadcasts();
15866            info.sendSystemPackageAppearedBroadcasts();
15867        }
15868        // Force a gc here.
15869        Runtime.getRuntime().gc();
15870        // Delete the resources here after sending the broadcast to let
15871        // other processes clean up before deleting resources.
15872        if (info.args != null) {
15873            synchronized (mInstallLock) {
15874                info.args.doPostDeleteLI(true);
15875            }
15876        }
15877
15878        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15879    }
15880
15881    class PackageRemovedInfo {
15882        String removedPackage;
15883        int uid = -1;
15884        int removedAppId = -1;
15885        int[] origUsers;
15886        int[] removedUsers = null;
15887        boolean isRemovedPackageSystemUpdate = false;
15888        boolean isUpdate;
15889        boolean dataRemoved;
15890        boolean removedForAllUsers;
15891        // Clean up resources deleted packages.
15892        InstallArgs args = null;
15893        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15894        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15895
15896        void sendPackageRemovedBroadcasts(boolean killApp) {
15897            sendPackageRemovedBroadcastInternal(killApp);
15898            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15899            for (int i = 0; i < childCount; i++) {
15900                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15901                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15902            }
15903        }
15904
15905        void sendSystemPackageUpdatedBroadcasts() {
15906            if (isRemovedPackageSystemUpdate) {
15907                sendSystemPackageUpdatedBroadcastsInternal();
15908                final int childCount = (removedChildPackages != null)
15909                        ? removedChildPackages.size() : 0;
15910                for (int i = 0; i < childCount; i++) {
15911                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15912                    if (childInfo.isRemovedPackageSystemUpdate) {
15913                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15914                    }
15915                }
15916            }
15917        }
15918
15919        void sendSystemPackageAppearedBroadcasts() {
15920            final int packageCount = (appearedChildPackages != null)
15921                    ? appearedChildPackages.size() : 0;
15922            for (int i = 0; i < packageCount; i++) {
15923                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15924                for (int userId : installedInfo.newUsers) {
15925                    sendPackageAddedForUser(installedInfo.name, true,
15926                            UserHandle.getAppId(installedInfo.uid), userId);
15927                }
15928            }
15929        }
15930
15931        private void sendSystemPackageUpdatedBroadcastsInternal() {
15932            Bundle extras = new Bundle(2);
15933            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15934            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15935            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15936                    extras, 0, null, null, null);
15937            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15938                    extras, 0, null, null, null);
15939            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15940                    null, 0, removedPackage, null, null);
15941        }
15942
15943        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15944            Bundle extras = new Bundle(2);
15945            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15946            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15947            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15948            if (isUpdate || isRemovedPackageSystemUpdate) {
15949                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15950            }
15951            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15952            if (removedPackage != null) {
15953                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15954                        extras, 0, null, null, removedUsers);
15955                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15956                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15957                            removedPackage, extras, 0, null, null, removedUsers);
15958                }
15959            }
15960            if (removedAppId >= 0) {
15961                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15962                        removedUsers);
15963            }
15964        }
15965    }
15966
15967    /*
15968     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15969     * flag is not set, the data directory is removed as well.
15970     * make sure this flag is set for partially installed apps. If not its meaningless to
15971     * delete a partially installed application.
15972     */
15973    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15974            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15975        String packageName = ps.name;
15976        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15977        // Retrieve object to delete permissions for shared user later on
15978        final PackageParser.Package deletedPkg;
15979        final PackageSetting deletedPs;
15980        // reader
15981        synchronized (mPackages) {
15982            deletedPkg = mPackages.get(packageName);
15983            deletedPs = mSettings.mPackages.get(packageName);
15984            if (outInfo != null) {
15985                outInfo.removedPackage = packageName;
15986                outInfo.removedUsers = deletedPs != null
15987                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15988                        : null;
15989            }
15990        }
15991
15992        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15993
15994        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15995            final PackageParser.Package resolvedPkg;
15996            if (deletedPkg != null) {
15997                resolvedPkg = deletedPkg;
15998            } else {
15999                // We don't have a parsed package when it lives on an ejected
16000                // adopted storage device, so fake something together
16001                resolvedPkg = new PackageParser.Package(ps.name);
16002                resolvedPkg.setVolumeUuid(ps.volumeUuid);
16003            }
16004            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16005                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16006            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16007            if (outInfo != null) {
16008                outInfo.dataRemoved = true;
16009            }
16010            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16011        }
16012
16013        // writer
16014        synchronized (mPackages) {
16015            if (deletedPs != null) {
16016                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16017                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16018                    clearDefaultBrowserIfNeeded(packageName);
16019                    if (outInfo != null) {
16020                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16021                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16022                    }
16023                    updatePermissionsLPw(deletedPs.name, null, 0);
16024                    if (deletedPs.sharedUser != null) {
16025                        // Remove permissions associated with package. Since runtime
16026                        // permissions are per user we have to kill the removed package
16027                        // or packages running under the shared user of the removed
16028                        // package if revoking the permissions requested only by the removed
16029                        // package is successful and this causes a change in gids.
16030                        for (int userId : UserManagerService.getInstance().getUserIds()) {
16031                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16032                                    userId);
16033                            if (userIdToKill == UserHandle.USER_ALL
16034                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16035                                // If gids changed for this user, kill all affected packages.
16036                                mHandler.post(new Runnable() {
16037                                    @Override
16038                                    public void run() {
16039                                        // This has to happen with no lock held.
16040                                        killApplication(deletedPs.name, deletedPs.appId,
16041                                                KILL_APP_REASON_GIDS_CHANGED);
16042                                    }
16043                                });
16044                                break;
16045                            }
16046                        }
16047                    }
16048                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16049                }
16050                // make sure to preserve per-user disabled state if this removal was just
16051                // a downgrade of a system app to the factory package
16052                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16053                    if (DEBUG_REMOVE) {
16054                        Slog.d(TAG, "Propagating install state across downgrade");
16055                    }
16056                    for (int userId : allUserHandles) {
16057                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16058                        if (DEBUG_REMOVE) {
16059                            Slog.d(TAG, "    user " + userId + " => " + installed);
16060                        }
16061                        ps.setInstalled(installed, userId);
16062                    }
16063                }
16064            }
16065            // can downgrade to reader
16066            if (writeSettings) {
16067                // Save settings now
16068                mSettings.writeLPr();
16069            }
16070        }
16071        if (outInfo != null) {
16072            // A user ID was deleted here. Go through all users and remove it
16073            // from KeyStore.
16074            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16075        }
16076    }
16077
16078    static boolean locationIsPrivileged(File path) {
16079        try {
16080            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16081                    .getCanonicalPath();
16082            return path.getCanonicalPath().startsWith(privilegedAppDir);
16083        } catch (IOException e) {
16084            Slog.e(TAG, "Unable to access code path " + path);
16085        }
16086        return false;
16087    }
16088
16089    /*
16090     * Tries to delete system package.
16091     */
16092    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16093            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16094            boolean writeSettings) {
16095        if (deletedPs.parentPackageName != null) {
16096            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16097            return false;
16098        }
16099
16100        final boolean applyUserRestrictions
16101                = (allUserHandles != null) && (outInfo.origUsers != null);
16102        final PackageSetting disabledPs;
16103        // Confirm if the system package has been updated
16104        // An updated system app can be deleted. This will also have to restore
16105        // the system pkg from system partition
16106        // reader
16107        synchronized (mPackages) {
16108            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16109        }
16110
16111        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16112                + " disabledPs=" + disabledPs);
16113
16114        if (disabledPs == null) {
16115            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16116            return false;
16117        } else if (DEBUG_REMOVE) {
16118            Slog.d(TAG, "Deleting system pkg from data partition");
16119        }
16120
16121        if (DEBUG_REMOVE) {
16122            if (applyUserRestrictions) {
16123                Slog.d(TAG, "Remembering install states:");
16124                for (int userId : allUserHandles) {
16125                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16126                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16127                }
16128            }
16129        }
16130
16131        // Delete the updated package
16132        outInfo.isRemovedPackageSystemUpdate = true;
16133        if (outInfo.removedChildPackages != null) {
16134            final int childCount = (deletedPs.childPackageNames != null)
16135                    ? deletedPs.childPackageNames.size() : 0;
16136            for (int i = 0; i < childCount; i++) {
16137                String childPackageName = deletedPs.childPackageNames.get(i);
16138                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16139                        .contains(childPackageName)) {
16140                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16141                            childPackageName);
16142                    if (childInfo != null) {
16143                        childInfo.isRemovedPackageSystemUpdate = true;
16144                    }
16145                }
16146            }
16147        }
16148
16149        if (disabledPs.versionCode < deletedPs.versionCode) {
16150            // Delete data for downgrades
16151            flags &= ~PackageManager.DELETE_KEEP_DATA;
16152        } else {
16153            // Preserve data by setting flag
16154            flags |= PackageManager.DELETE_KEEP_DATA;
16155        }
16156
16157        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16158                outInfo, writeSettings, disabledPs.pkg);
16159        if (!ret) {
16160            return false;
16161        }
16162
16163        // writer
16164        synchronized (mPackages) {
16165            // Reinstate the old system package
16166            enableSystemPackageLPw(disabledPs.pkg);
16167            // Remove any native libraries from the upgraded package.
16168            removeNativeBinariesLI(deletedPs);
16169        }
16170
16171        // Install the system package
16172        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16173        int parseFlags = mDefParseFlags
16174                | PackageParser.PARSE_MUST_BE_APK
16175                | PackageParser.PARSE_IS_SYSTEM
16176                | PackageParser.PARSE_IS_SYSTEM_DIR;
16177        if (locationIsPrivileged(disabledPs.codePath)) {
16178            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16179        }
16180
16181        final PackageParser.Package newPkg;
16182        try {
16183            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16184        } catch (PackageManagerException e) {
16185            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16186                    + e.getMessage());
16187            return false;
16188        }
16189        try {
16190            // update shared libraries for the newly re-installed system package
16191            updateSharedLibrariesLPr(newPkg, null);
16192        } catch (PackageManagerException e) {
16193            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16194        }
16195
16196        prepareAppDataAfterInstallLIF(newPkg);
16197
16198        // writer
16199        synchronized (mPackages) {
16200            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16201
16202            // Propagate the permissions state as we do not want to drop on the floor
16203            // runtime permissions. The update permissions method below will take
16204            // care of removing obsolete permissions and grant install permissions.
16205            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16206            updatePermissionsLPw(newPkg.packageName, newPkg,
16207                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16208
16209            if (applyUserRestrictions) {
16210                if (DEBUG_REMOVE) {
16211                    Slog.d(TAG, "Propagating install state across reinstall");
16212                }
16213                for (int userId : allUserHandles) {
16214                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16215                    if (DEBUG_REMOVE) {
16216                        Slog.d(TAG, "    user " + userId + " => " + installed);
16217                    }
16218                    ps.setInstalled(installed, userId);
16219
16220                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16221                }
16222                // Regardless of writeSettings we need to ensure that this restriction
16223                // state propagation is persisted
16224                mSettings.writeAllUsersPackageRestrictionsLPr();
16225            }
16226            // can downgrade to reader here
16227            if (writeSettings) {
16228                mSettings.writeLPr();
16229            }
16230        }
16231        return true;
16232    }
16233
16234    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16235            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16236            PackageRemovedInfo outInfo, boolean writeSettings,
16237            PackageParser.Package replacingPackage) {
16238        synchronized (mPackages) {
16239            if (outInfo != null) {
16240                outInfo.uid = ps.appId;
16241            }
16242
16243            if (outInfo != null && outInfo.removedChildPackages != null) {
16244                final int childCount = (ps.childPackageNames != null)
16245                        ? ps.childPackageNames.size() : 0;
16246                for (int i = 0; i < childCount; i++) {
16247                    String childPackageName = ps.childPackageNames.get(i);
16248                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16249                    if (childPs == null) {
16250                        return false;
16251                    }
16252                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16253                            childPackageName);
16254                    if (childInfo != null) {
16255                        childInfo.uid = childPs.appId;
16256                    }
16257                }
16258            }
16259        }
16260
16261        // Delete package data from internal structures and also remove data if flag is set
16262        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16263
16264        // Delete the child packages data
16265        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16266        for (int i = 0; i < childCount; i++) {
16267            PackageSetting childPs;
16268            synchronized (mPackages) {
16269                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16270            }
16271            if (childPs != null) {
16272                PackageRemovedInfo childOutInfo = (outInfo != null
16273                        && outInfo.removedChildPackages != null)
16274                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16275                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16276                        && (replacingPackage != null
16277                        && !replacingPackage.hasChildPackage(childPs.name))
16278                        ? flags & ~DELETE_KEEP_DATA : flags;
16279                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16280                        deleteFlags, writeSettings);
16281            }
16282        }
16283
16284        // Delete application code and resources only for parent packages
16285        if (ps.parentPackageName == null) {
16286            if (deleteCodeAndResources && (outInfo != null)) {
16287                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16288                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16289                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16290            }
16291        }
16292
16293        return true;
16294    }
16295
16296    @Override
16297    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16298            int userId) {
16299        mContext.enforceCallingOrSelfPermission(
16300                android.Manifest.permission.DELETE_PACKAGES, null);
16301        synchronized (mPackages) {
16302            PackageSetting ps = mSettings.mPackages.get(packageName);
16303            if (ps == null) {
16304                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16305                return false;
16306            }
16307            if (!ps.getInstalled(userId)) {
16308                // Can't block uninstall for an app that is not installed or enabled.
16309                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16310                return false;
16311            }
16312            ps.setBlockUninstall(blockUninstall, userId);
16313            mSettings.writePackageRestrictionsLPr(userId);
16314        }
16315        return true;
16316    }
16317
16318    @Override
16319    public boolean getBlockUninstallForUser(String packageName, int userId) {
16320        synchronized (mPackages) {
16321            PackageSetting ps = mSettings.mPackages.get(packageName);
16322            if (ps == null) {
16323                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16324                return false;
16325            }
16326            return ps.getBlockUninstall(userId);
16327        }
16328    }
16329
16330    @Override
16331    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16332        int callingUid = Binder.getCallingUid();
16333        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16334            throw new SecurityException(
16335                    "setRequiredForSystemUser can only be run by the system or root");
16336        }
16337        synchronized (mPackages) {
16338            PackageSetting ps = mSettings.mPackages.get(packageName);
16339            if (ps == null) {
16340                Log.w(TAG, "Package doesn't exist: " + packageName);
16341                return false;
16342            }
16343            if (systemUserApp) {
16344                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16345            } else {
16346                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16347            }
16348            mSettings.writeLPr();
16349        }
16350        return true;
16351    }
16352
16353    /*
16354     * This method handles package deletion in general
16355     */
16356    private boolean deletePackageLIF(String packageName, UserHandle user,
16357            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16358            PackageRemovedInfo outInfo, boolean writeSettings,
16359            PackageParser.Package replacingPackage) {
16360        if (packageName == null) {
16361            Slog.w(TAG, "Attempt to delete null packageName.");
16362            return false;
16363        }
16364
16365        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16366
16367        PackageSetting ps;
16368
16369        synchronized (mPackages) {
16370            ps = mSettings.mPackages.get(packageName);
16371            if (ps == null) {
16372                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16373                return false;
16374            }
16375
16376            if (ps.parentPackageName != null && (!isSystemApp(ps)
16377                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16378                if (DEBUG_REMOVE) {
16379                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16380                            + ((user == null) ? UserHandle.USER_ALL : user));
16381                }
16382                final int removedUserId = (user != null) ? user.getIdentifier()
16383                        : UserHandle.USER_ALL;
16384                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16385                    return false;
16386                }
16387                markPackageUninstalledForUserLPw(ps, user);
16388                scheduleWritePackageRestrictionsLocked(user);
16389                return true;
16390            }
16391        }
16392
16393        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16394                && user.getIdentifier() != UserHandle.USER_ALL)) {
16395            // The caller is asking that the package only be deleted for a single
16396            // user.  To do this, we just mark its uninstalled state and delete
16397            // its data. If this is a system app, we only allow this to happen if
16398            // they have set the special DELETE_SYSTEM_APP which requests different
16399            // semantics than normal for uninstalling system apps.
16400            markPackageUninstalledForUserLPw(ps, user);
16401
16402            if (!isSystemApp(ps)) {
16403                // Do not uninstall the APK if an app should be cached
16404                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16405                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16406                    // Other user still have this package installed, so all
16407                    // we need to do is clear this user's data and save that
16408                    // it is uninstalled.
16409                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16410                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16411                        return false;
16412                    }
16413                    scheduleWritePackageRestrictionsLocked(user);
16414                    return true;
16415                } else {
16416                    // We need to set it back to 'installed' so the uninstall
16417                    // broadcasts will be sent correctly.
16418                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16419                    ps.setInstalled(true, user.getIdentifier());
16420                }
16421            } else {
16422                // This is a system app, so we assume that the
16423                // other users still have this package installed, so all
16424                // we need to do is clear this user's data and save that
16425                // it is uninstalled.
16426                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16427                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16428                    return false;
16429                }
16430                scheduleWritePackageRestrictionsLocked(user);
16431                return true;
16432            }
16433        }
16434
16435        // If we are deleting a composite package for all users, keep track
16436        // of result for each child.
16437        if (ps.childPackageNames != null && outInfo != null) {
16438            synchronized (mPackages) {
16439                final int childCount = ps.childPackageNames.size();
16440                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16441                for (int i = 0; i < childCount; i++) {
16442                    String childPackageName = ps.childPackageNames.get(i);
16443                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16444                    childInfo.removedPackage = childPackageName;
16445                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16446                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16447                    if (childPs != null) {
16448                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16449                    }
16450                }
16451            }
16452        }
16453
16454        boolean ret = false;
16455        if (isSystemApp(ps)) {
16456            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16457            // When an updated system application is deleted we delete the existing resources
16458            // as well and fall back to existing code in system partition
16459            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16460        } else {
16461            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16462            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16463                    outInfo, writeSettings, replacingPackage);
16464        }
16465
16466        // Take a note whether we deleted the package for all users
16467        if (outInfo != null) {
16468            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16469            if (outInfo.removedChildPackages != null) {
16470                synchronized (mPackages) {
16471                    final int childCount = outInfo.removedChildPackages.size();
16472                    for (int i = 0; i < childCount; i++) {
16473                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16474                        if (childInfo != null) {
16475                            childInfo.removedForAllUsers = mPackages.get(
16476                                    childInfo.removedPackage) == null;
16477                        }
16478                    }
16479                }
16480            }
16481            // If we uninstalled an update to a system app there may be some
16482            // child packages that appeared as they are declared in the system
16483            // app but were not declared in the update.
16484            if (isSystemApp(ps)) {
16485                synchronized (mPackages) {
16486                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16487                    final int childCount = (updatedPs.childPackageNames != null)
16488                            ? updatedPs.childPackageNames.size() : 0;
16489                    for (int i = 0; i < childCount; i++) {
16490                        String childPackageName = updatedPs.childPackageNames.get(i);
16491                        if (outInfo.removedChildPackages == null
16492                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16493                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16494                            if (childPs == null) {
16495                                continue;
16496                            }
16497                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16498                            installRes.name = childPackageName;
16499                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16500                            installRes.pkg = mPackages.get(childPackageName);
16501                            installRes.uid = childPs.pkg.applicationInfo.uid;
16502                            if (outInfo.appearedChildPackages == null) {
16503                                outInfo.appearedChildPackages = new ArrayMap<>();
16504                            }
16505                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16506                        }
16507                    }
16508                }
16509            }
16510        }
16511
16512        return ret;
16513    }
16514
16515    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16516        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16517                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16518        for (int nextUserId : userIds) {
16519            if (DEBUG_REMOVE) {
16520                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16521            }
16522            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16523                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16524                    false /*hidden*/, false /*suspended*/, null, null, null,
16525                    false /*blockUninstall*/,
16526                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16527        }
16528    }
16529
16530    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16531            PackageRemovedInfo outInfo) {
16532        final PackageParser.Package pkg;
16533        synchronized (mPackages) {
16534            pkg = mPackages.get(ps.name);
16535        }
16536
16537        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16538                : new int[] {userId};
16539        for (int nextUserId : userIds) {
16540            if (DEBUG_REMOVE) {
16541                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16542                        + nextUserId);
16543            }
16544
16545            destroyAppDataLIF(pkg, userId,
16546                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16547            destroyAppProfilesLIF(pkg, userId);
16548            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16549            schedulePackageCleaning(ps.name, nextUserId, false);
16550            synchronized (mPackages) {
16551                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16552                    scheduleWritePackageRestrictionsLocked(nextUserId);
16553                }
16554                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16555            }
16556        }
16557
16558        if (outInfo != null) {
16559            outInfo.removedPackage = ps.name;
16560            outInfo.removedAppId = ps.appId;
16561            outInfo.removedUsers = userIds;
16562        }
16563
16564        return true;
16565    }
16566
16567    private final class ClearStorageConnection implements ServiceConnection {
16568        IMediaContainerService mContainerService;
16569
16570        @Override
16571        public void onServiceConnected(ComponentName name, IBinder service) {
16572            synchronized (this) {
16573                mContainerService = IMediaContainerService.Stub.asInterface(service);
16574                notifyAll();
16575            }
16576        }
16577
16578        @Override
16579        public void onServiceDisconnected(ComponentName name) {
16580        }
16581    }
16582
16583    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16584        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16585
16586        final boolean mounted;
16587        if (Environment.isExternalStorageEmulated()) {
16588            mounted = true;
16589        } else {
16590            final String status = Environment.getExternalStorageState();
16591
16592            mounted = status.equals(Environment.MEDIA_MOUNTED)
16593                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16594        }
16595
16596        if (!mounted) {
16597            return;
16598        }
16599
16600        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16601        int[] users;
16602        if (userId == UserHandle.USER_ALL) {
16603            users = sUserManager.getUserIds();
16604        } else {
16605            users = new int[] { userId };
16606        }
16607        final ClearStorageConnection conn = new ClearStorageConnection();
16608        if (mContext.bindServiceAsUser(
16609                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16610            try {
16611                for (int curUser : users) {
16612                    long timeout = SystemClock.uptimeMillis() + 5000;
16613                    synchronized (conn) {
16614                        long now;
16615                        while (conn.mContainerService == null &&
16616                                (now = SystemClock.uptimeMillis()) < timeout) {
16617                            try {
16618                                conn.wait(timeout - now);
16619                            } catch (InterruptedException e) {
16620                            }
16621                        }
16622                    }
16623                    if (conn.mContainerService == null) {
16624                        return;
16625                    }
16626
16627                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16628                    clearDirectory(conn.mContainerService,
16629                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16630                    if (allData) {
16631                        clearDirectory(conn.mContainerService,
16632                                userEnv.buildExternalStorageAppDataDirs(packageName));
16633                        clearDirectory(conn.mContainerService,
16634                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16635                    }
16636                }
16637            } finally {
16638                mContext.unbindService(conn);
16639            }
16640        }
16641    }
16642
16643    @Override
16644    public void clearApplicationProfileData(String packageName) {
16645        enforceSystemOrRoot("Only the system can clear all profile data");
16646
16647        final PackageParser.Package pkg;
16648        synchronized (mPackages) {
16649            pkg = mPackages.get(packageName);
16650        }
16651
16652        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16653            synchronized (mInstallLock) {
16654                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16655                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16656                        true /* removeBaseMarker */);
16657            }
16658        }
16659    }
16660
16661    @Override
16662    public void clearApplicationUserData(final String packageName,
16663            final IPackageDataObserver observer, final int userId) {
16664        mContext.enforceCallingOrSelfPermission(
16665                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16666
16667        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16668                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16669
16670        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16671            throw new SecurityException("Cannot clear data for a protected package: "
16672                    + packageName);
16673        }
16674        // Queue up an async operation since the package deletion may take a little while.
16675        mHandler.post(new Runnable() {
16676            public void run() {
16677                mHandler.removeCallbacks(this);
16678                final boolean succeeded;
16679                try (PackageFreezer freezer = freezePackage(packageName,
16680                        "clearApplicationUserData")) {
16681                    synchronized (mInstallLock) {
16682                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16683                    }
16684                    clearExternalStorageDataSync(packageName, userId, true);
16685                }
16686                if (succeeded) {
16687                    // invoke DeviceStorageMonitor's update method to clear any notifications
16688                    DeviceStorageMonitorInternal dsm = LocalServices
16689                            .getService(DeviceStorageMonitorInternal.class);
16690                    if (dsm != null) {
16691                        dsm.checkMemory();
16692                    }
16693                }
16694                if(observer != null) {
16695                    try {
16696                        observer.onRemoveCompleted(packageName, succeeded);
16697                    } catch (RemoteException e) {
16698                        Log.i(TAG, "Observer no longer exists.");
16699                    }
16700                } //end if observer
16701            } //end run
16702        });
16703    }
16704
16705    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16706        if (packageName == null) {
16707            Slog.w(TAG, "Attempt to delete null packageName.");
16708            return false;
16709        }
16710
16711        // Try finding details about the requested package
16712        PackageParser.Package pkg;
16713        synchronized (mPackages) {
16714            pkg = mPackages.get(packageName);
16715            if (pkg == null) {
16716                final PackageSetting ps = mSettings.mPackages.get(packageName);
16717                if (ps != null) {
16718                    pkg = ps.pkg;
16719                }
16720            }
16721
16722            if (pkg == null) {
16723                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16724                return false;
16725            }
16726
16727            PackageSetting ps = (PackageSetting) pkg.mExtras;
16728            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16729        }
16730
16731        clearAppDataLIF(pkg, userId,
16732                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16733
16734        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16735        removeKeystoreDataIfNeeded(userId, appId);
16736
16737        UserManagerInternal umInternal = getUserManagerInternal();
16738        final int flags;
16739        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16740            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16741        } else if (umInternal.isUserRunning(userId)) {
16742            flags = StorageManager.FLAG_STORAGE_DE;
16743        } else {
16744            flags = 0;
16745        }
16746        prepareAppDataContentsLIF(pkg, userId, flags);
16747
16748        return true;
16749    }
16750
16751    /**
16752     * Reverts user permission state changes (permissions and flags) in
16753     * all packages for a given user.
16754     *
16755     * @param userId The device user for which to do a reset.
16756     */
16757    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16758        final int packageCount = mPackages.size();
16759        for (int i = 0; i < packageCount; i++) {
16760            PackageParser.Package pkg = mPackages.valueAt(i);
16761            PackageSetting ps = (PackageSetting) pkg.mExtras;
16762            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16763        }
16764    }
16765
16766    private void resetNetworkPolicies(int userId) {
16767        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16768    }
16769
16770    /**
16771     * Reverts user permission state changes (permissions and flags).
16772     *
16773     * @param ps The package for which to reset.
16774     * @param userId The device user for which to do a reset.
16775     */
16776    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16777            final PackageSetting ps, final int userId) {
16778        if (ps.pkg == null) {
16779            return;
16780        }
16781
16782        // These are flags that can change base on user actions.
16783        final int userSettableMask = FLAG_PERMISSION_USER_SET
16784                | FLAG_PERMISSION_USER_FIXED
16785                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16786                | FLAG_PERMISSION_REVIEW_REQUIRED;
16787
16788        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16789                | FLAG_PERMISSION_POLICY_FIXED;
16790
16791        boolean writeInstallPermissions = false;
16792        boolean writeRuntimePermissions = false;
16793
16794        final int permissionCount = ps.pkg.requestedPermissions.size();
16795        for (int i = 0; i < permissionCount; i++) {
16796            String permission = ps.pkg.requestedPermissions.get(i);
16797
16798            BasePermission bp = mSettings.mPermissions.get(permission);
16799            if (bp == null) {
16800                continue;
16801            }
16802
16803            // If shared user we just reset the state to which only this app contributed.
16804            if (ps.sharedUser != null) {
16805                boolean used = false;
16806                final int packageCount = ps.sharedUser.packages.size();
16807                for (int j = 0; j < packageCount; j++) {
16808                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16809                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16810                            && pkg.pkg.requestedPermissions.contains(permission)) {
16811                        used = true;
16812                        break;
16813                    }
16814                }
16815                if (used) {
16816                    continue;
16817                }
16818            }
16819
16820            PermissionsState permissionsState = ps.getPermissionsState();
16821
16822            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16823
16824            // Always clear the user settable flags.
16825            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16826                    bp.name) != null;
16827            // If permission review is enabled and this is a legacy app, mark the
16828            // permission as requiring a review as this is the initial state.
16829            int flags = 0;
16830            if (mPermissionReviewRequired
16831                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16832                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16833            }
16834            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16835                if (hasInstallState) {
16836                    writeInstallPermissions = true;
16837                } else {
16838                    writeRuntimePermissions = true;
16839                }
16840            }
16841
16842            // Below is only runtime permission handling.
16843            if (!bp.isRuntime()) {
16844                continue;
16845            }
16846
16847            // Never clobber system or policy.
16848            if ((oldFlags & policyOrSystemFlags) != 0) {
16849                continue;
16850            }
16851
16852            // If this permission was granted by default, make sure it is.
16853            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16854                if (permissionsState.grantRuntimePermission(bp, userId)
16855                        != PERMISSION_OPERATION_FAILURE) {
16856                    writeRuntimePermissions = true;
16857                }
16858            // If permission review is enabled the permissions for a legacy apps
16859            // are represented as constantly granted runtime ones, so don't revoke.
16860            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16861                // Otherwise, reset the permission.
16862                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16863                switch (revokeResult) {
16864                    case PERMISSION_OPERATION_SUCCESS:
16865                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16866                        writeRuntimePermissions = true;
16867                        final int appId = ps.appId;
16868                        mHandler.post(new Runnable() {
16869                            @Override
16870                            public void run() {
16871                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16872                            }
16873                        });
16874                    } break;
16875                }
16876            }
16877        }
16878
16879        // Synchronously write as we are taking permissions away.
16880        if (writeRuntimePermissions) {
16881            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16882        }
16883
16884        // Synchronously write as we are taking permissions away.
16885        if (writeInstallPermissions) {
16886            mSettings.writeLPr();
16887        }
16888    }
16889
16890    /**
16891     * Remove entries from the keystore daemon. Will only remove it if the
16892     * {@code appId} is valid.
16893     */
16894    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16895        if (appId < 0) {
16896            return;
16897        }
16898
16899        final KeyStore keyStore = KeyStore.getInstance();
16900        if (keyStore != null) {
16901            if (userId == UserHandle.USER_ALL) {
16902                for (final int individual : sUserManager.getUserIds()) {
16903                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16904                }
16905            } else {
16906                keyStore.clearUid(UserHandle.getUid(userId, appId));
16907            }
16908        } else {
16909            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16910        }
16911    }
16912
16913    @Override
16914    public void deleteApplicationCacheFiles(final String packageName,
16915            final IPackageDataObserver observer) {
16916        final int userId = UserHandle.getCallingUserId();
16917        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16918    }
16919
16920    @Override
16921    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16922            final IPackageDataObserver observer) {
16923        mContext.enforceCallingOrSelfPermission(
16924                android.Manifest.permission.DELETE_CACHE_FILES, null);
16925        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16926                /* requireFullPermission= */ true, /* checkShell= */ false,
16927                "delete application cache files");
16928
16929        final PackageParser.Package pkg;
16930        synchronized (mPackages) {
16931            pkg = mPackages.get(packageName);
16932        }
16933
16934        // Queue up an async operation since the package deletion may take a little while.
16935        mHandler.post(new Runnable() {
16936            public void run() {
16937                synchronized (mInstallLock) {
16938                    final int flags = StorageManager.FLAG_STORAGE_DE
16939                            | StorageManager.FLAG_STORAGE_CE;
16940                    // We're only clearing cache files, so we don't care if the
16941                    // app is unfrozen and still able to run
16942                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16943                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16944                }
16945                clearExternalStorageDataSync(packageName, userId, false);
16946                if (observer != null) {
16947                    try {
16948                        observer.onRemoveCompleted(packageName, true);
16949                    } catch (RemoteException e) {
16950                        Log.i(TAG, "Observer no longer exists.");
16951                    }
16952                }
16953            }
16954        });
16955    }
16956
16957    @Override
16958    public void getPackageSizeInfo(final String packageName, int userHandle,
16959            final IPackageStatsObserver observer) {
16960        mContext.enforceCallingOrSelfPermission(
16961                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16962        if (packageName == null) {
16963            throw new IllegalArgumentException("Attempt to get size of null packageName");
16964        }
16965
16966        PackageStats stats = new PackageStats(packageName, userHandle);
16967
16968        /*
16969         * Queue up an async operation since the package measurement may take a
16970         * little while.
16971         */
16972        Message msg = mHandler.obtainMessage(INIT_COPY);
16973        msg.obj = new MeasureParams(stats, observer);
16974        mHandler.sendMessage(msg);
16975    }
16976
16977    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16978        final PackageSetting ps;
16979        synchronized (mPackages) {
16980            ps = mSettings.mPackages.get(packageName);
16981            if (ps == null) {
16982                Slog.w(TAG, "Failed to find settings for " + packageName);
16983                return false;
16984            }
16985        }
16986        try {
16987            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16988                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16989                    ps.getCeDataInode(userId), ps.codePathString, stats);
16990        } catch (InstallerException e) {
16991            Slog.w(TAG, String.valueOf(e));
16992            return false;
16993        }
16994
16995        // For now, ignore code size of packages on system partition
16996        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16997            stats.codeSize = 0;
16998        }
16999
17000        return true;
17001    }
17002
17003    private int getUidTargetSdkVersionLockedLPr(int uid) {
17004        Object obj = mSettings.getUserIdLPr(uid);
17005        if (obj instanceof SharedUserSetting) {
17006            final SharedUserSetting sus = (SharedUserSetting) obj;
17007            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17008            final Iterator<PackageSetting> it = sus.packages.iterator();
17009            while (it.hasNext()) {
17010                final PackageSetting ps = it.next();
17011                if (ps.pkg != null) {
17012                    int v = ps.pkg.applicationInfo.targetSdkVersion;
17013                    if (v < vers) vers = v;
17014                }
17015            }
17016            return vers;
17017        } else if (obj instanceof PackageSetting) {
17018            final PackageSetting ps = (PackageSetting) obj;
17019            if (ps.pkg != null) {
17020                return ps.pkg.applicationInfo.targetSdkVersion;
17021            }
17022        }
17023        return Build.VERSION_CODES.CUR_DEVELOPMENT;
17024    }
17025
17026    @Override
17027    public void addPreferredActivity(IntentFilter filter, int match,
17028            ComponentName[] set, ComponentName activity, int userId) {
17029        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17030                "Adding preferred");
17031    }
17032
17033    private void addPreferredActivityInternal(IntentFilter filter, int match,
17034            ComponentName[] set, ComponentName activity, boolean always, int userId,
17035            String opname) {
17036        // writer
17037        int callingUid = Binder.getCallingUid();
17038        enforceCrossUserPermission(callingUid, userId,
17039                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17040        if (filter.countActions() == 0) {
17041            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17042            return;
17043        }
17044        synchronized (mPackages) {
17045            if (mContext.checkCallingOrSelfPermission(
17046                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17047                    != PackageManager.PERMISSION_GRANTED) {
17048                if (getUidTargetSdkVersionLockedLPr(callingUid)
17049                        < Build.VERSION_CODES.FROYO) {
17050                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17051                            + callingUid);
17052                    return;
17053                }
17054                mContext.enforceCallingOrSelfPermission(
17055                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17056            }
17057
17058            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17059            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17060                    + userId + ":");
17061            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17062            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17063            scheduleWritePackageRestrictionsLocked(userId);
17064            postPreferredActivityChangedBroadcast(userId);
17065        }
17066    }
17067
17068    private void postPreferredActivityChangedBroadcast(int userId) {
17069        mHandler.post(() -> {
17070            final IActivityManager am = ActivityManagerNative.getDefault();
17071            if (am == null) {
17072                return;
17073            }
17074
17075            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17076            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17077            try {
17078                am.broadcastIntent(null, intent, null, null,
17079                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17080                        null, false, false, userId);
17081            } catch (RemoteException e) {
17082            }
17083        });
17084    }
17085
17086    @Override
17087    public void replacePreferredActivity(IntentFilter filter, int match,
17088            ComponentName[] set, ComponentName activity, int userId) {
17089        if (filter.countActions() != 1) {
17090            throw new IllegalArgumentException(
17091                    "replacePreferredActivity expects filter to have only 1 action.");
17092        }
17093        if (filter.countDataAuthorities() != 0
17094                || filter.countDataPaths() != 0
17095                || filter.countDataSchemes() > 1
17096                || filter.countDataTypes() != 0) {
17097            throw new IllegalArgumentException(
17098                    "replacePreferredActivity expects filter to have no data authorities, " +
17099                    "paths, or types; and at most one scheme.");
17100        }
17101
17102        final int callingUid = Binder.getCallingUid();
17103        enforceCrossUserPermission(callingUid, userId,
17104                true /* requireFullPermission */, false /* checkShell */,
17105                "replace preferred activity");
17106        synchronized (mPackages) {
17107            if (mContext.checkCallingOrSelfPermission(
17108                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17109                    != PackageManager.PERMISSION_GRANTED) {
17110                if (getUidTargetSdkVersionLockedLPr(callingUid)
17111                        < Build.VERSION_CODES.FROYO) {
17112                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17113                            + Binder.getCallingUid());
17114                    return;
17115                }
17116                mContext.enforceCallingOrSelfPermission(
17117                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17118            }
17119
17120            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17121            if (pir != null) {
17122                // Get all of the existing entries that exactly match this filter.
17123                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17124                if (existing != null && existing.size() == 1) {
17125                    PreferredActivity cur = existing.get(0);
17126                    if (DEBUG_PREFERRED) {
17127                        Slog.i(TAG, "Checking replace of preferred:");
17128                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17129                        if (!cur.mPref.mAlways) {
17130                            Slog.i(TAG, "  -- CUR; not mAlways!");
17131                        } else {
17132                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17133                            Slog.i(TAG, "  -- CUR: mSet="
17134                                    + Arrays.toString(cur.mPref.mSetComponents));
17135                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17136                            Slog.i(TAG, "  -- NEW: mMatch="
17137                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17138                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17139                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17140                        }
17141                    }
17142                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17143                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17144                            && cur.mPref.sameSet(set)) {
17145                        // Setting the preferred activity to what it happens to be already
17146                        if (DEBUG_PREFERRED) {
17147                            Slog.i(TAG, "Replacing with same preferred activity "
17148                                    + cur.mPref.mShortComponent + " for user "
17149                                    + userId + ":");
17150                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17151                        }
17152                        return;
17153                    }
17154                }
17155
17156                if (existing != null) {
17157                    if (DEBUG_PREFERRED) {
17158                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17159                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17160                    }
17161                    for (int i = 0; i < existing.size(); i++) {
17162                        PreferredActivity pa = existing.get(i);
17163                        if (DEBUG_PREFERRED) {
17164                            Slog.i(TAG, "Removing existing preferred activity "
17165                                    + pa.mPref.mComponent + ":");
17166                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17167                        }
17168                        pir.removeFilter(pa);
17169                    }
17170                }
17171            }
17172            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17173                    "Replacing preferred");
17174        }
17175    }
17176
17177    @Override
17178    public void clearPackagePreferredActivities(String packageName) {
17179        final int uid = Binder.getCallingUid();
17180        // writer
17181        synchronized (mPackages) {
17182            PackageParser.Package pkg = mPackages.get(packageName);
17183            if (pkg == null || pkg.applicationInfo.uid != uid) {
17184                if (mContext.checkCallingOrSelfPermission(
17185                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17186                        != PackageManager.PERMISSION_GRANTED) {
17187                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17188                            < Build.VERSION_CODES.FROYO) {
17189                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17190                                + Binder.getCallingUid());
17191                        return;
17192                    }
17193                    mContext.enforceCallingOrSelfPermission(
17194                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17195                }
17196            }
17197
17198            int user = UserHandle.getCallingUserId();
17199            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17200                scheduleWritePackageRestrictionsLocked(user);
17201            }
17202        }
17203    }
17204
17205    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17206    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17207        ArrayList<PreferredActivity> removed = null;
17208        boolean changed = false;
17209        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17210            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17211            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17212            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17213                continue;
17214            }
17215            Iterator<PreferredActivity> it = pir.filterIterator();
17216            while (it.hasNext()) {
17217                PreferredActivity pa = it.next();
17218                // Mark entry for removal only if it matches the package name
17219                // and the entry is of type "always".
17220                if (packageName == null ||
17221                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17222                                && pa.mPref.mAlways)) {
17223                    if (removed == null) {
17224                        removed = new ArrayList<PreferredActivity>();
17225                    }
17226                    removed.add(pa);
17227                }
17228            }
17229            if (removed != null) {
17230                for (int j=0; j<removed.size(); j++) {
17231                    PreferredActivity pa = removed.get(j);
17232                    pir.removeFilter(pa);
17233                }
17234                changed = true;
17235            }
17236        }
17237        if (changed) {
17238            postPreferredActivityChangedBroadcast(userId);
17239        }
17240        return changed;
17241    }
17242
17243    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17244    private void clearIntentFilterVerificationsLPw(int userId) {
17245        final int packageCount = mPackages.size();
17246        for (int i = 0; i < packageCount; i++) {
17247            PackageParser.Package pkg = mPackages.valueAt(i);
17248            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17249        }
17250    }
17251
17252    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17253    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17254        if (userId == UserHandle.USER_ALL) {
17255            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17256                    sUserManager.getUserIds())) {
17257                for (int oneUserId : sUserManager.getUserIds()) {
17258                    scheduleWritePackageRestrictionsLocked(oneUserId);
17259                }
17260            }
17261        } else {
17262            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17263                scheduleWritePackageRestrictionsLocked(userId);
17264            }
17265        }
17266    }
17267
17268    void clearDefaultBrowserIfNeeded(String packageName) {
17269        for (int oneUserId : sUserManager.getUserIds()) {
17270            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17271            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17272            if (packageName.equals(defaultBrowserPackageName)) {
17273                setDefaultBrowserPackageName(null, oneUserId);
17274            }
17275        }
17276    }
17277
17278    @Override
17279    public void resetApplicationPreferences(int userId) {
17280        mContext.enforceCallingOrSelfPermission(
17281                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17282        final long identity = Binder.clearCallingIdentity();
17283        // writer
17284        try {
17285            synchronized (mPackages) {
17286                clearPackagePreferredActivitiesLPw(null, userId);
17287                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17288                // TODO: We have to reset the default SMS and Phone. This requires
17289                // significant refactoring to keep all default apps in the package
17290                // manager (cleaner but more work) or have the services provide
17291                // callbacks to the package manager to request a default app reset.
17292                applyFactoryDefaultBrowserLPw(userId);
17293                clearIntentFilterVerificationsLPw(userId);
17294                primeDomainVerificationsLPw(userId);
17295                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17296                scheduleWritePackageRestrictionsLocked(userId);
17297            }
17298            resetNetworkPolicies(userId);
17299        } finally {
17300            Binder.restoreCallingIdentity(identity);
17301        }
17302    }
17303
17304    @Override
17305    public int getPreferredActivities(List<IntentFilter> outFilters,
17306            List<ComponentName> outActivities, String packageName) {
17307
17308        int num = 0;
17309        final int userId = UserHandle.getCallingUserId();
17310        // reader
17311        synchronized (mPackages) {
17312            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17313            if (pir != null) {
17314                final Iterator<PreferredActivity> it = pir.filterIterator();
17315                while (it.hasNext()) {
17316                    final PreferredActivity pa = it.next();
17317                    if (packageName == null
17318                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17319                                    && pa.mPref.mAlways)) {
17320                        if (outFilters != null) {
17321                            outFilters.add(new IntentFilter(pa));
17322                        }
17323                        if (outActivities != null) {
17324                            outActivities.add(pa.mPref.mComponent);
17325                        }
17326                    }
17327                }
17328            }
17329        }
17330
17331        return num;
17332    }
17333
17334    @Override
17335    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17336            int userId) {
17337        int callingUid = Binder.getCallingUid();
17338        if (callingUid != Process.SYSTEM_UID) {
17339            throw new SecurityException(
17340                    "addPersistentPreferredActivity can only be run by the system");
17341        }
17342        if (filter.countActions() == 0) {
17343            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17344            return;
17345        }
17346        synchronized (mPackages) {
17347            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17348                    ":");
17349            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17350            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17351                    new PersistentPreferredActivity(filter, activity));
17352            scheduleWritePackageRestrictionsLocked(userId);
17353            postPreferredActivityChangedBroadcast(userId);
17354        }
17355    }
17356
17357    @Override
17358    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17359        int callingUid = Binder.getCallingUid();
17360        if (callingUid != Process.SYSTEM_UID) {
17361            throw new SecurityException(
17362                    "clearPackagePersistentPreferredActivities can only be run by the system");
17363        }
17364        ArrayList<PersistentPreferredActivity> removed = null;
17365        boolean changed = false;
17366        synchronized (mPackages) {
17367            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17368                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17369                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17370                        .valueAt(i);
17371                if (userId != thisUserId) {
17372                    continue;
17373                }
17374                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17375                while (it.hasNext()) {
17376                    PersistentPreferredActivity ppa = it.next();
17377                    // Mark entry for removal only if it matches the package name.
17378                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17379                        if (removed == null) {
17380                            removed = new ArrayList<PersistentPreferredActivity>();
17381                        }
17382                        removed.add(ppa);
17383                    }
17384                }
17385                if (removed != null) {
17386                    for (int j=0; j<removed.size(); j++) {
17387                        PersistentPreferredActivity ppa = removed.get(j);
17388                        ppir.removeFilter(ppa);
17389                    }
17390                    changed = true;
17391                }
17392            }
17393
17394            if (changed) {
17395                scheduleWritePackageRestrictionsLocked(userId);
17396                postPreferredActivityChangedBroadcast(userId);
17397            }
17398        }
17399    }
17400
17401    /**
17402     * Common machinery for picking apart a restored XML blob and passing
17403     * it to a caller-supplied functor to be applied to the running system.
17404     */
17405    private void restoreFromXml(XmlPullParser parser, int userId,
17406            String expectedStartTag, BlobXmlRestorer functor)
17407            throws IOException, XmlPullParserException {
17408        int type;
17409        while ((type = parser.next()) != XmlPullParser.START_TAG
17410                && type != XmlPullParser.END_DOCUMENT) {
17411        }
17412        if (type != XmlPullParser.START_TAG) {
17413            // oops didn't find a start tag?!
17414            if (DEBUG_BACKUP) {
17415                Slog.e(TAG, "Didn't find start tag during restore");
17416            }
17417            return;
17418        }
17419Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17420        // this is supposed to be TAG_PREFERRED_BACKUP
17421        if (!expectedStartTag.equals(parser.getName())) {
17422            if (DEBUG_BACKUP) {
17423                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17424            }
17425            return;
17426        }
17427
17428        // skip interfering stuff, then we're aligned with the backing implementation
17429        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17430Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17431        functor.apply(parser, userId);
17432    }
17433
17434    private interface BlobXmlRestorer {
17435        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17436    }
17437
17438    /**
17439     * Non-Binder method, support for the backup/restore mechanism: write the
17440     * full set of preferred activities in its canonical XML format.  Returns the
17441     * XML output as a byte array, or null if there is none.
17442     */
17443    @Override
17444    public byte[] getPreferredActivityBackup(int userId) {
17445        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17446            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17447        }
17448
17449        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17450        try {
17451            final XmlSerializer serializer = new FastXmlSerializer();
17452            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17453            serializer.startDocument(null, true);
17454            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17455
17456            synchronized (mPackages) {
17457                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17458            }
17459
17460            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17461            serializer.endDocument();
17462            serializer.flush();
17463        } catch (Exception e) {
17464            if (DEBUG_BACKUP) {
17465                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17466            }
17467            return null;
17468        }
17469
17470        return dataStream.toByteArray();
17471    }
17472
17473    @Override
17474    public void restorePreferredActivities(byte[] backup, int userId) {
17475        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17476            throw new SecurityException("Only the system may call restorePreferredActivities()");
17477        }
17478
17479        try {
17480            final XmlPullParser parser = Xml.newPullParser();
17481            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17482            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17483                    new BlobXmlRestorer() {
17484                        @Override
17485                        public void apply(XmlPullParser parser, int userId)
17486                                throws XmlPullParserException, IOException {
17487                            synchronized (mPackages) {
17488                                mSettings.readPreferredActivitiesLPw(parser, userId);
17489                            }
17490                        }
17491                    } );
17492        } catch (Exception e) {
17493            if (DEBUG_BACKUP) {
17494                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17495            }
17496        }
17497    }
17498
17499    /**
17500     * Non-Binder method, support for the backup/restore mechanism: write the
17501     * default browser (etc) settings in its canonical XML format.  Returns the default
17502     * browser XML representation as a byte array, or null if there is none.
17503     */
17504    @Override
17505    public byte[] getDefaultAppsBackup(int userId) {
17506        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17507            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17508        }
17509
17510        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17511        try {
17512            final XmlSerializer serializer = new FastXmlSerializer();
17513            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17514            serializer.startDocument(null, true);
17515            serializer.startTag(null, TAG_DEFAULT_APPS);
17516
17517            synchronized (mPackages) {
17518                mSettings.writeDefaultAppsLPr(serializer, userId);
17519            }
17520
17521            serializer.endTag(null, TAG_DEFAULT_APPS);
17522            serializer.endDocument();
17523            serializer.flush();
17524        } catch (Exception e) {
17525            if (DEBUG_BACKUP) {
17526                Slog.e(TAG, "Unable to write default apps for backup", e);
17527            }
17528            return null;
17529        }
17530
17531        return dataStream.toByteArray();
17532    }
17533
17534    @Override
17535    public void restoreDefaultApps(byte[] backup, int userId) {
17536        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17537            throw new SecurityException("Only the system may call restoreDefaultApps()");
17538        }
17539
17540        try {
17541            final XmlPullParser parser = Xml.newPullParser();
17542            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17543            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17544                    new BlobXmlRestorer() {
17545                        @Override
17546                        public void apply(XmlPullParser parser, int userId)
17547                                throws XmlPullParserException, IOException {
17548                            synchronized (mPackages) {
17549                                mSettings.readDefaultAppsLPw(parser, userId);
17550                            }
17551                        }
17552                    } );
17553        } catch (Exception e) {
17554            if (DEBUG_BACKUP) {
17555                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17556            }
17557        }
17558    }
17559
17560    @Override
17561    public byte[] getIntentFilterVerificationBackup(int userId) {
17562        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17563            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17564        }
17565
17566        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17567        try {
17568            final XmlSerializer serializer = new FastXmlSerializer();
17569            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17570            serializer.startDocument(null, true);
17571            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17572
17573            synchronized (mPackages) {
17574                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17575            }
17576
17577            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17578            serializer.endDocument();
17579            serializer.flush();
17580        } catch (Exception e) {
17581            if (DEBUG_BACKUP) {
17582                Slog.e(TAG, "Unable to write default apps for backup", e);
17583            }
17584            return null;
17585        }
17586
17587        return dataStream.toByteArray();
17588    }
17589
17590    @Override
17591    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17592        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17593            throw new SecurityException("Only the system may call restorePreferredActivities()");
17594        }
17595
17596        try {
17597            final XmlPullParser parser = Xml.newPullParser();
17598            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17599            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17600                    new BlobXmlRestorer() {
17601                        @Override
17602                        public void apply(XmlPullParser parser, int userId)
17603                                throws XmlPullParserException, IOException {
17604                            synchronized (mPackages) {
17605                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17606                                mSettings.writeLPr();
17607                            }
17608                        }
17609                    } );
17610        } catch (Exception e) {
17611            if (DEBUG_BACKUP) {
17612                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17613            }
17614        }
17615    }
17616
17617    @Override
17618    public byte[] getPermissionGrantBackup(int userId) {
17619        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17620            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17621        }
17622
17623        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17624        try {
17625            final XmlSerializer serializer = new FastXmlSerializer();
17626            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17627            serializer.startDocument(null, true);
17628            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17629
17630            synchronized (mPackages) {
17631                serializeRuntimePermissionGrantsLPr(serializer, userId);
17632            }
17633
17634            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17635            serializer.endDocument();
17636            serializer.flush();
17637        } catch (Exception e) {
17638            if (DEBUG_BACKUP) {
17639                Slog.e(TAG, "Unable to write default apps for backup", e);
17640            }
17641            return null;
17642        }
17643
17644        return dataStream.toByteArray();
17645    }
17646
17647    @Override
17648    public void restorePermissionGrants(byte[] backup, int userId) {
17649        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17650            throw new SecurityException("Only the system may call restorePermissionGrants()");
17651        }
17652
17653        try {
17654            final XmlPullParser parser = Xml.newPullParser();
17655            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17656            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17657                    new BlobXmlRestorer() {
17658                        @Override
17659                        public void apply(XmlPullParser parser, int userId)
17660                                throws XmlPullParserException, IOException {
17661                            synchronized (mPackages) {
17662                                processRestoredPermissionGrantsLPr(parser, userId);
17663                            }
17664                        }
17665                    } );
17666        } catch (Exception e) {
17667            if (DEBUG_BACKUP) {
17668                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17669            }
17670        }
17671    }
17672
17673    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17674            throws IOException {
17675        serializer.startTag(null, TAG_ALL_GRANTS);
17676
17677        final int N = mSettings.mPackages.size();
17678        for (int i = 0; i < N; i++) {
17679            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17680            boolean pkgGrantsKnown = false;
17681
17682            PermissionsState packagePerms = ps.getPermissionsState();
17683
17684            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17685                final int grantFlags = state.getFlags();
17686                // only look at grants that are not system/policy fixed
17687                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17688                    final boolean isGranted = state.isGranted();
17689                    // And only back up the user-twiddled state bits
17690                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17691                        final String packageName = mSettings.mPackages.keyAt(i);
17692                        if (!pkgGrantsKnown) {
17693                            serializer.startTag(null, TAG_GRANT);
17694                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17695                            pkgGrantsKnown = true;
17696                        }
17697
17698                        final boolean userSet =
17699                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17700                        final boolean userFixed =
17701                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17702                        final boolean revoke =
17703                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17704
17705                        serializer.startTag(null, TAG_PERMISSION);
17706                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17707                        if (isGranted) {
17708                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17709                        }
17710                        if (userSet) {
17711                            serializer.attribute(null, ATTR_USER_SET, "true");
17712                        }
17713                        if (userFixed) {
17714                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17715                        }
17716                        if (revoke) {
17717                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17718                        }
17719                        serializer.endTag(null, TAG_PERMISSION);
17720                    }
17721                }
17722            }
17723
17724            if (pkgGrantsKnown) {
17725                serializer.endTag(null, TAG_GRANT);
17726            }
17727        }
17728
17729        serializer.endTag(null, TAG_ALL_GRANTS);
17730    }
17731
17732    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17733            throws XmlPullParserException, IOException {
17734        String pkgName = null;
17735        int outerDepth = parser.getDepth();
17736        int type;
17737        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17738                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17739            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17740                continue;
17741            }
17742
17743            final String tagName = parser.getName();
17744            if (tagName.equals(TAG_GRANT)) {
17745                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17746                if (DEBUG_BACKUP) {
17747                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17748                }
17749            } else if (tagName.equals(TAG_PERMISSION)) {
17750
17751                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17752                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17753
17754                int newFlagSet = 0;
17755                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17756                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17757                }
17758                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17759                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17760                }
17761                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17762                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17763                }
17764                if (DEBUG_BACKUP) {
17765                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17766                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17767                }
17768                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17769                if (ps != null) {
17770                    // Already installed so we apply the grant immediately
17771                    if (DEBUG_BACKUP) {
17772                        Slog.v(TAG, "        + already installed; applying");
17773                    }
17774                    PermissionsState perms = ps.getPermissionsState();
17775                    BasePermission bp = mSettings.mPermissions.get(permName);
17776                    if (bp != null) {
17777                        if (isGranted) {
17778                            perms.grantRuntimePermission(bp, userId);
17779                        }
17780                        if (newFlagSet != 0) {
17781                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17782                        }
17783                    }
17784                } else {
17785                    // Need to wait for post-restore install to apply the grant
17786                    if (DEBUG_BACKUP) {
17787                        Slog.v(TAG, "        - not yet installed; saving for later");
17788                    }
17789                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17790                            isGranted, newFlagSet, userId);
17791                }
17792            } else {
17793                PackageManagerService.reportSettingsProblem(Log.WARN,
17794                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17795                XmlUtils.skipCurrentTag(parser);
17796            }
17797        }
17798
17799        scheduleWriteSettingsLocked();
17800        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17801    }
17802
17803    @Override
17804    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17805            int sourceUserId, int targetUserId, int flags) {
17806        mContext.enforceCallingOrSelfPermission(
17807                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17808        int callingUid = Binder.getCallingUid();
17809        enforceOwnerRights(ownerPackage, callingUid);
17810        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17811        if (intentFilter.countActions() == 0) {
17812            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17813            return;
17814        }
17815        synchronized (mPackages) {
17816            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17817                    ownerPackage, targetUserId, flags);
17818            CrossProfileIntentResolver resolver =
17819                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17820            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17821            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17822            if (existing != null) {
17823                int size = existing.size();
17824                for (int i = 0; i < size; i++) {
17825                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17826                        return;
17827                    }
17828                }
17829            }
17830            resolver.addFilter(newFilter);
17831            scheduleWritePackageRestrictionsLocked(sourceUserId);
17832        }
17833    }
17834
17835    @Override
17836    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17837        mContext.enforceCallingOrSelfPermission(
17838                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17839        int callingUid = Binder.getCallingUid();
17840        enforceOwnerRights(ownerPackage, callingUid);
17841        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17842        synchronized (mPackages) {
17843            CrossProfileIntentResolver resolver =
17844                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17845            ArraySet<CrossProfileIntentFilter> set =
17846                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17847            for (CrossProfileIntentFilter filter : set) {
17848                if (filter.getOwnerPackage().equals(ownerPackage)) {
17849                    resolver.removeFilter(filter);
17850                }
17851            }
17852            scheduleWritePackageRestrictionsLocked(sourceUserId);
17853        }
17854    }
17855
17856    // Enforcing that callingUid is owning pkg on userId
17857    private void enforceOwnerRights(String pkg, int callingUid) {
17858        // The system owns everything.
17859        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17860            return;
17861        }
17862        int callingUserId = UserHandle.getUserId(callingUid);
17863        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17864        if (pi == null) {
17865            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17866                    + callingUserId);
17867        }
17868        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17869            throw new SecurityException("Calling uid " + callingUid
17870                    + " does not own package " + pkg);
17871        }
17872    }
17873
17874    @Override
17875    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17876        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17877    }
17878
17879    private Intent getHomeIntent() {
17880        Intent intent = new Intent(Intent.ACTION_MAIN);
17881        intent.addCategory(Intent.CATEGORY_HOME);
17882        intent.addCategory(Intent.CATEGORY_DEFAULT);
17883        return intent;
17884    }
17885
17886    private IntentFilter getHomeFilter() {
17887        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17888        filter.addCategory(Intent.CATEGORY_HOME);
17889        filter.addCategory(Intent.CATEGORY_DEFAULT);
17890        return filter;
17891    }
17892
17893    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17894            int userId) {
17895        Intent intent  = getHomeIntent();
17896        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17897                PackageManager.GET_META_DATA, userId);
17898        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17899                true, false, false, userId);
17900
17901        allHomeCandidates.clear();
17902        if (list != null) {
17903            for (ResolveInfo ri : list) {
17904                allHomeCandidates.add(ri);
17905            }
17906        }
17907        return (preferred == null || preferred.activityInfo == null)
17908                ? null
17909                : new ComponentName(preferred.activityInfo.packageName,
17910                        preferred.activityInfo.name);
17911    }
17912
17913    @Override
17914    public void setHomeActivity(ComponentName comp, int userId) {
17915        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17916        getHomeActivitiesAsUser(homeActivities, userId);
17917
17918        boolean found = false;
17919
17920        final int size = homeActivities.size();
17921        final ComponentName[] set = new ComponentName[size];
17922        for (int i = 0; i < size; i++) {
17923            final ResolveInfo candidate = homeActivities.get(i);
17924            final ActivityInfo info = candidate.activityInfo;
17925            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17926            set[i] = activityName;
17927            if (!found && activityName.equals(comp)) {
17928                found = true;
17929            }
17930        }
17931        if (!found) {
17932            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17933                    + userId);
17934        }
17935        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17936                set, comp, userId);
17937    }
17938
17939    private @Nullable String getSetupWizardPackageName() {
17940        final Intent intent = new Intent(Intent.ACTION_MAIN);
17941        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17942
17943        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17944                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17945                        | MATCH_DISABLED_COMPONENTS,
17946                UserHandle.myUserId());
17947        if (matches.size() == 1) {
17948            return matches.get(0).getComponentInfo().packageName;
17949        } else {
17950            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17951                    + ": matches=" + matches);
17952            return null;
17953        }
17954    }
17955
17956    private @Nullable String getStorageManagerPackageName() {
17957        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17958
17959        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17960                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17961                        | MATCH_DISABLED_COMPONENTS,
17962                UserHandle.myUserId());
17963        if (matches.size() == 1) {
17964            return matches.get(0).getComponentInfo().packageName;
17965        } else {
17966            Slog.e(TAG, "There should probably be exactly one storage manager; found "
17967                    + matches.size() + ": matches=" + matches);
17968            return null;
17969        }
17970    }
17971
17972    @Override
17973    public void setApplicationEnabledSetting(String appPackageName,
17974            int newState, int flags, int userId, String callingPackage) {
17975        if (!sUserManager.exists(userId)) return;
17976        if (callingPackage == null) {
17977            callingPackage = Integer.toString(Binder.getCallingUid());
17978        }
17979        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17980    }
17981
17982    @Override
17983    public void setComponentEnabledSetting(ComponentName componentName,
17984            int newState, int flags, int userId) {
17985        if (!sUserManager.exists(userId)) return;
17986        setEnabledSetting(componentName.getPackageName(),
17987                componentName.getClassName(), newState, flags, userId, null);
17988    }
17989
17990    private void setEnabledSetting(final String packageName, String className, int newState,
17991            final int flags, int userId, String callingPackage) {
17992        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17993              || newState == COMPONENT_ENABLED_STATE_ENABLED
17994              || newState == COMPONENT_ENABLED_STATE_DISABLED
17995              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17996              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17997            throw new IllegalArgumentException("Invalid new component state: "
17998                    + newState);
17999        }
18000        PackageSetting pkgSetting;
18001        final int uid = Binder.getCallingUid();
18002        final int permission;
18003        if (uid == Process.SYSTEM_UID) {
18004            permission = PackageManager.PERMISSION_GRANTED;
18005        } else {
18006            permission = mContext.checkCallingOrSelfPermission(
18007                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18008        }
18009        enforceCrossUserPermission(uid, userId,
18010                false /* requireFullPermission */, true /* checkShell */, "set enabled");
18011        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18012        boolean sendNow = false;
18013        boolean isApp = (className == null);
18014        String componentName = isApp ? packageName : className;
18015        int packageUid = -1;
18016        ArrayList<String> components;
18017
18018        // writer
18019        synchronized (mPackages) {
18020            pkgSetting = mSettings.mPackages.get(packageName);
18021            if (pkgSetting == null) {
18022                if (className == null) {
18023                    throw new IllegalArgumentException("Unknown package: " + packageName);
18024                }
18025                throw new IllegalArgumentException(
18026                        "Unknown component: " + packageName + "/" + className);
18027            }
18028        }
18029
18030        // Limit who can change which apps
18031        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18032            // Don't allow apps that don't have permission to modify other apps
18033            if (!allowedByPermission) {
18034                throw new SecurityException(
18035                        "Permission Denial: attempt to change component state from pid="
18036                        + Binder.getCallingPid()
18037                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18038            }
18039            // Don't allow changing protected packages.
18040            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18041                throw new SecurityException("Cannot disable a protected package: " + packageName);
18042            }
18043        }
18044
18045        synchronized (mPackages) {
18046            if (uid == Process.SHELL_UID) {
18047                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18048                int oldState = pkgSetting.getEnabled(userId);
18049                if (className == null
18050                    &&
18051                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18052                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18053                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18054                    &&
18055                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18056                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18057                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18058                    // ok
18059                } else {
18060                    throw new SecurityException(
18061                            "Shell cannot change component state for " + packageName + "/"
18062                            + className + " to " + newState);
18063                }
18064            }
18065            if (className == null) {
18066                // We're dealing with an application/package level state change
18067                if (pkgSetting.getEnabled(userId) == newState) {
18068                    // Nothing to do
18069                    return;
18070                }
18071                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18072                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18073                    // Don't care about who enables an app.
18074                    callingPackage = null;
18075                }
18076                pkgSetting.setEnabled(newState, userId, callingPackage);
18077                // pkgSetting.pkg.mSetEnabled = newState;
18078            } else {
18079                // We're dealing with a component level state change
18080                // First, verify that this is a valid class name.
18081                PackageParser.Package pkg = pkgSetting.pkg;
18082                if (pkg == null || !pkg.hasComponentClassName(className)) {
18083                    if (pkg != null &&
18084                            pkg.applicationInfo.targetSdkVersion >=
18085                                    Build.VERSION_CODES.JELLY_BEAN) {
18086                        throw new IllegalArgumentException("Component class " + className
18087                                + " does not exist in " + packageName);
18088                    } else {
18089                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18090                                + className + " does not exist in " + packageName);
18091                    }
18092                }
18093                switch (newState) {
18094                case COMPONENT_ENABLED_STATE_ENABLED:
18095                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18096                        return;
18097                    }
18098                    break;
18099                case COMPONENT_ENABLED_STATE_DISABLED:
18100                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18101                        return;
18102                    }
18103                    break;
18104                case COMPONENT_ENABLED_STATE_DEFAULT:
18105                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18106                        return;
18107                    }
18108                    break;
18109                default:
18110                    Slog.e(TAG, "Invalid new component state: " + newState);
18111                    return;
18112                }
18113            }
18114            scheduleWritePackageRestrictionsLocked(userId);
18115            components = mPendingBroadcasts.get(userId, packageName);
18116            final boolean newPackage = components == null;
18117            if (newPackage) {
18118                components = new ArrayList<String>();
18119            }
18120            if (!components.contains(componentName)) {
18121                components.add(componentName);
18122            }
18123            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18124                sendNow = true;
18125                // Purge entry from pending broadcast list if another one exists already
18126                // since we are sending one right away.
18127                mPendingBroadcasts.remove(userId, packageName);
18128            } else {
18129                if (newPackage) {
18130                    mPendingBroadcasts.put(userId, packageName, components);
18131                }
18132                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18133                    // Schedule a message
18134                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18135                }
18136            }
18137        }
18138
18139        long callingId = Binder.clearCallingIdentity();
18140        try {
18141            if (sendNow) {
18142                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18143                sendPackageChangedBroadcast(packageName,
18144                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18145            }
18146        } finally {
18147            Binder.restoreCallingIdentity(callingId);
18148        }
18149    }
18150
18151    @Override
18152    public void flushPackageRestrictionsAsUser(int userId) {
18153        if (!sUserManager.exists(userId)) {
18154            return;
18155        }
18156        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18157                false /* checkShell */, "flushPackageRestrictions");
18158        synchronized (mPackages) {
18159            mSettings.writePackageRestrictionsLPr(userId);
18160            mDirtyUsers.remove(userId);
18161            if (mDirtyUsers.isEmpty()) {
18162                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18163            }
18164        }
18165    }
18166
18167    private void sendPackageChangedBroadcast(String packageName,
18168            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18169        if (DEBUG_INSTALL)
18170            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18171                    + componentNames);
18172        Bundle extras = new Bundle(4);
18173        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18174        String nameList[] = new String[componentNames.size()];
18175        componentNames.toArray(nameList);
18176        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18177        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18178        extras.putInt(Intent.EXTRA_UID, packageUid);
18179        // If this is not reporting a change of the overall package, then only send it
18180        // to registered receivers.  We don't want to launch a swath of apps for every
18181        // little component state change.
18182        final int flags = !componentNames.contains(packageName)
18183                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18184        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18185                new int[] {UserHandle.getUserId(packageUid)});
18186    }
18187
18188    @Override
18189    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18190        if (!sUserManager.exists(userId)) return;
18191        final int uid = Binder.getCallingUid();
18192        final int permission = mContext.checkCallingOrSelfPermission(
18193                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18194        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18195        enforceCrossUserPermission(uid, userId,
18196                true /* requireFullPermission */, true /* checkShell */, "stop package");
18197        // writer
18198        synchronized (mPackages) {
18199            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18200                    allowedByPermission, uid, userId)) {
18201                scheduleWritePackageRestrictionsLocked(userId);
18202            }
18203        }
18204    }
18205
18206    @Override
18207    public String getInstallerPackageName(String packageName) {
18208        // reader
18209        synchronized (mPackages) {
18210            return mSettings.getInstallerPackageNameLPr(packageName);
18211        }
18212    }
18213
18214    public boolean isOrphaned(String packageName) {
18215        // reader
18216        synchronized (mPackages) {
18217            return mSettings.isOrphaned(packageName);
18218        }
18219    }
18220
18221    @Override
18222    public int getApplicationEnabledSetting(String packageName, int userId) {
18223        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18224        int uid = Binder.getCallingUid();
18225        enforceCrossUserPermission(uid, userId,
18226                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18227        // reader
18228        synchronized (mPackages) {
18229            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18230        }
18231    }
18232
18233    @Override
18234    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18235        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18236        int uid = Binder.getCallingUid();
18237        enforceCrossUserPermission(uid, userId,
18238                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18239        // reader
18240        synchronized (mPackages) {
18241            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18242        }
18243    }
18244
18245    @Override
18246    public void enterSafeMode() {
18247        enforceSystemOrRoot("Only the system can request entering safe mode");
18248
18249        if (!mSystemReady) {
18250            mSafeMode = true;
18251        }
18252    }
18253
18254    @Override
18255    public void systemReady() {
18256        mSystemReady = true;
18257
18258        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18259        // disabled after already being started.
18260        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18261                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18262
18263        // Read the compatibilty setting when the system is ready.
18264        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18265                mContext.getContentResolver(),
18266                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18267        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18268        if (DEBUG_SETTINGS) {
18269            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18270        }
18271
18272        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18273
18274        synchronized (mPackages) {
18275            // Verify that all of the preferred activity components actually
18276            // exist.  It is possible for applications to be updated and at
18277            // that point remove a previously declared activity component that
18278            // had been set as a preferred activity.  We try to clean this up
18279            // the next time we encounter that preferred activity, but it is
18280            // possible for the user flow to never be able to return to that
18281            // situation so here we do a sanity check to make sure we haven't
18282            // left any junk around.
18283            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18284            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18285                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18286                removed.clear();
18287                for (PreferredActivity pa : pir.filterSet()) {
18288                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18289                        removed.add(pa);
18290                    }
18291                }
18292                if (removed.size() > 0) {
18293                    for (int r=0; r<removed.size(); r++) {
18294                        PreferredActivity pa = removed.get(r);
18295                        Slog.w(TAG, "Removing dangling preferred activity: "
18296                                + pa.mPref.mComponent);
18297                        pir.removeFilter(pa);
18298                    }
18299                    mSettings.writePackageRestrictionsLPr(
18300                            mSettings.mPreferredActivities.keyAt(i));
18301                }
18302            }
18303
18304            for (int userId : UserManagerService.getInstance().getUserIds()) {
18305                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18306                    grantPermissionsUserIds = ArrayUtils.appendInt(
18307                            grantPermissionsUserIds, userId);
18308                }
18309            }
18310        }
18311        sUserManager.systemReady();
18312
18313        // If we upgraded grant all default permissions before kicking off.
18314        for (int userId : grantPermissionsUserIds) {
18315            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18316        }
18317
18318        // If we did not grant default permissions, we preload from this the
18319        // default permission exceptions lazily to ensure we don't hit the
18320        // disk on a new user creation.
18321        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18322            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18323        }
18324
18325        // Kick off any messages waiting for system ready
18326        if (mPostSystemReadyMessages != null) {
18327            for (Message msg : mPostSystemReadyMessages) {
18328                msg.sendToTarget();
18329            }
18330            mPostSystemReadyMessages = null;
18331        }
18332
18333        // Watch for external volumes that come and go over time
18334        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18335        storage.registerListener(mStorageListener);
18336
18337        mInstallerService.systemReady();
18338        mPackageDexOptimizer.systemReady();
18339
18340        MountServiceInternal mountServiceInternal = LocalServices.getService(
18341                MountServiceInternal.class);
18342        mountServiceInternal.addExternalStoragePolicy(
18343                new MountServiceInternal.ExternalStorageMountPolicy() {
18344            @Override
18345            public int getMountMode(int uid, String packageName) {
18346                if (Process.isIsolated(uid)) {
18347                    return Zygote.MOUNT_EXTERNAL_NONE;
18348                }
18349                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18350                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18351                }
18352                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18353                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18354                }
18355                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18356                    return Zygote.MOUNT_EXTERNAL_READ;
18357                }
18358                return Zygote.MOUNT_EXTERNAL_WRITE;
18359            }
18360
18361            @Override
18362            public boolean hasExternalStorage(int uid, String packageName) {
18363                return true;
18364            }
18365        });
18366
18367        // Now that we're mostly running, clean up stale users and apps
18368        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18369        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18370    }
18371
18372    @Override
18373    public boolean isSafeMode() {
18374        return mSafeMode;
18375    }
18376
18377    @Override
18378    public boolean hasSystemUidErrors() {
18379        return mHasSystemUidErrors;
18380    }
18381
18382    static String arrayToString(int[] array) {
18383        StringBuffer buf = new StringBuffer(128);
18384        buf.append('[');
18385        if (array != null) {
18386            for (int i=0; i<array.length; i++) {
18387                if (i > 0) buf.append(", ");
18388                buf.append(array[i]);
18389            }
18390        }
18391        buf.append(']');
18392        return buf.toString();
18393    }
18394
18395    static class DumpState {
18396        public static final int DUMP_LIBS = 1 << 0;
18397        public static final int DUMP_FEATURES = 1 << 1;
18398        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18399        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18400        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18401        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18402        public static final int DUMP_PERMISSIONS = 1 << 6;
18403        public static final int DUMP_PACKAGES = 1 << 7;
18404        public static final int DUMP_SHARED_USERS = 1 << 8;
18405        public static final int DUMP_MESSAGES = 1 << 9;
18406        public static final int DUMP_PROVIDERS = 1 << 10;
18407        public static final int DUMP_VERIFIERS = 1 << 11;
18408        public static final int DUMP_PREFERRED = 1 << 12;
18409        public static final int DUMP_PREFERRED_XML = 1 << 13;
18410        public static final int DUMP_KEYSETS = 1 << 14;
18411        public static final int DUMP_VERSION = 1 << 15;
18412        public static final int DUMP_INSTALLS = 1 << 16;
18413        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18414        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18415        public static final int DUMP_FROZEN = 1 << 19;
18416        public static final int DUMP_DEXOPT = 1 << 20;
18417        public static final int DUMP_COMPILER_STATS = 1 << 21;
18418
18419        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18420
18421        private int mTypes;
18422
18423        private int mOptions;
18424
18425        private boolean mTitlePrinted;
18426
18427        private SharedUserSetting mSharedUser;
18428
18429        public boolean isDumping(int type) {
18430            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18431                return true;
18432            }
18433
18434            return (mTypes & type) != 0;
18435        }
18436
18437        public void setDump(int type) {
18438            mTypes |= type;
18439        }
18440
18441        public boolean isOptionEnabled(int option) {
18442            return (mOptions & option) != 0;
18443        }
18444
18445        public void setOptionEnabled(int option) {
18446            mOptions |= option;
18447        }
18448
18449        public boolean onTitlePrinted() {
18450            final boolean printed = mTitlePrinted;
18451            mTitlePrinted = true;
18452            return printed;
18453        }
18454
18455        public boolean getTitlePrinted() {
18456            return mTitlePrinted;
18457        }
18458
18459        public void setTitlePrinted(boolean enabled) {
18460            mTitlePrinted = enabled;
18461        }
18462
18463        public SharedUserSetting getSharedUser() {
18464            return mSharedUser;
18465        }
18466
18467        public void setSharedUser(SharedUserSetting user) {
18468            mSharedUser = user;
18469        }
18470    }
18471
18472    @Override
18473    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18474            FileDescriptor err, String[] args, ShellCallback callback,
18475            ResultReceiver resultReceiver) {
18476        (new PackageManagerShellCommand(this)).exec(
18477                this, in, out, err, args, callback, resultReceiver);
18478    }
18479
18480    @Override
18481    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18482        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18483                != PackageManager.PERMISSION_GRANTED) {
18484            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18485                    + Binder.getCallingPid()
18486                    + ", uid=" + Binder.getCallingUid()
18487                    + " without permission "
18488                    + android.Manifest.permission.DUMP);
18489            return;
18490        }
18491
18492        DumpState dumpState = new DumpState();
18493        boolean fullPreferred = false;
18494        boolean checkin = false;
18495
18496        String packageName = null;
18497        ArraySet<String> permissionNames = null;
18498
18499        int opti = 0;
18500        while (opti < args.length) {
18501            String opt = args[opti];
18502            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18503                break;
18504            }
18505            opti++;
18506
18507            if ("-a".equals(opt)) {
18508                // Right now we only know how to print all.
18509            } else if ("-h".equals(opt)) {
18510                pw.println("Package manager dump options:");
18511                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18512                pw.println("    --checkin: dump for a checkin");
18513                pw.println("    -f: print details of intent filters");
18514                pw.println("    -h: print this help");
18515                pw.println("  cmd may be one of:");
18516                pw.println("    l[ibraries]: list known shared libraries");
18517                pw.println("    f[eatures]: list device features");
18518                pw.println("    k[eysets]: print known keysets");
18519                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18520                pw.println("    perm[issions]: dump permissions");
18521                pw.println("    permission [name ...]: dump declaration and use of given permission");
18522                pw.println("    pref[erred]: print preferred package settings");
18523                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18524                pw.println("    prov[iders]: dump content providers");
18525                pw.println("    p[ackages]: dump installed packages");
18526                pw.println("    s[hared-users]: dump shared user IDs");
18527                pw.println("    m[essages]: print collected runtime messages");
18528                pw.println("    v[erifiers]: print package verifier info");
18529                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18530                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18531                pw.println("    version: print database version info");
18532                pw.println("    write: write current settings now");
18533                pw.println("    installs: details about install sessions");
18534                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18535                pw.println("    dexopt: dump dexopt state");
18536                pw.println("    compiler-stats: dump compiler statistics");
18537                pw.println("    <package.name>: info about given package");
18538                return;
18539            } else if ("--checkin".equals(opt)) {
18540                checkin = true;
18541            } else if ("-f".equals(opt)) {
18542                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18543            } else {
18544                pw.println("Unknown argument: " + opt + "; use -h for help");
18545            }
18546        }
18547
18548        // Is the caller requesting to dump a particular piece of data?
18549        if (opti < args.length) {
18550            String cmd = args[opti];
18551            opti++;
18552            // Is this a package name?
18553            if ("android".equals(cmd) || cmd.contains(".")) {
18554                packageName = cmd;
18555                // When dumping a single package, we always dump all of its
18556                // filter information since the amount of data will be reasonable.
18557                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18558            } else if ("check-permission".equals(cmd)) {
18559                if (opti >= args.length) {
18560                    pw.println("Error: check-permission missing permission argument");
18561                    return;
18562                }
18563                String perm = args[opti];
18564                opti++;
18565                if (opti >= args.length) {
18566                    pw.println("Error: check-permission missing package argument");
18567                    return;
18568                }
18569                String pkg = args[opti];
18570                opti++;
18571                int user = UserHandle.getUserId(Binder.getCallingUid());
18572                if (opti < args.length) {
18573                    try {
18574                        user = Integer.parseInt(args[opti]);
18575                    } catch (NumberFormatException e) {
18576                        pw.println("Error: check-permission user argument is not a number: "
18577                                + args[opti]);
18578                        return;
18579                    }
18580                }
18581                pw.println(checkPermission(perm, pkg, user));
18582                return;
18583            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18584                dumpState.setDump(DumpState.DUMP_LIBS);
18585            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18586                dumpState.setDump(DumpState.DUMP_FEATURES);
18587            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18588                if (opti >= args.length) {
18589                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18590                            | DumpState.DUMP_SERVICE_RESOLVERS
18591                            | DumpState.DUMP_RECEIVER_RESOLVERS
18592                            | DumpState.DUMP_CONTENT_RESOLVERS);
18593                } else {
18594                    while (opti < args.length) {
18595                        String name = args[opti];
18596                        if ("a".equals(name) || "activity".equals(name)) {
18597                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18598                        } else if ("s".equals(name) || "service".equals(name)) {
18599                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18600                        } else if ("r".equals(name) || "receiver".equals(name)) {
18601                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18602                        } else if ("c".equals(name) || "content".equals(name)) {
18603                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18604                        } else {
18605                            pw.println("Error: unknown resolver table type: " + name);
18606                            return;
18607                        }
18608                        opti++;
18609                    }
18610                }
18611            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18612                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18613            } else if ("permission".equals(cmd)) {
18614                if (opti >= args.length) {
18615                    pw.println("Error: permission requires permission name");
18616                    return;
18617                }
18618                permissionNames = new ArraySet<>();
18619                while (opti < args.length) {
18620                    permissionNames.add(args[opti]);
18621                    opti++;
18622                }
18623                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18624                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18625            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18626                dumpState.setDump(DumpState.DUMP_PREFERRED);
18627            } else if ("preferred-xml".equals(cmd)) {
18628                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18629                if (opti < args.length && "--full".equals(args[opti])) {
18630                    fullPreferred = true;
18631                    opti++;
18632                }
18633            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18634                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18635            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18636                dumpState.setDump(DumpState.DUMP_PACKAGES);
18637            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18638                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18639            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18640                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18641            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18642                dumpState.setDump(DumpState.DUMP_MESSAGES);
18643            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18644                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18645            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18646                    || "intent-filter-verifiers".equals(cmd)) {
18647                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18648            } else if ("version".equals(cmd)) {
18649                dumpState.setDump(DumpState.DUMP_VERSION);
18650            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18651                dumpState.setDump(DumpState.DUMP_KEYSETS);
18652            } else if ("installs".equals(cmd)) {
18653                dumpState.setDump(DumpState.DUMP_INSTALLS);
18654            } else if ("frozen".equals(cmd)) {
18655                dumpState.setDump(DumpState.DUMP_FROZEN);
18656            } else if ("dexopt".equals(cmd)) {
18657                dumpState.setDump(DumpState.DUMP_DEXOPT);
18658            } else if ("compiler-stats".equals(cmd)) {
18659                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18660            } else if ("write".equals(cmd)) {
18661                synchronized (mPackages) {
18662                    mSettings.writeLPr();
18663                    pw.println("Settings written.");
18664                    return;
18665                }
18666            }
18667        }
18668
18669        if (checkin) {
18670            pw.println("vers,1");
18671        }
18672
18673        // reader
18674        synchronized (mPackages) {
18675            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18676                if (!checkin) {
18677                    if (dumpState.onTitlePrinted())
18678                        pw.println();
18679                    pw.println("Database versions:");
18680                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18681                }
18682            }
18683
18684            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18685                if (!checkin) {
18686                    if (dumpState.onTitlePrinted())
18687                        pw.println();
18688                    pw.println("Verifiers:");
18689                    pw.print("  Required: ");
18690                    pw.print(mRequiredVerifierPackage);
18691                    pw.print(" (uid=");
18692                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18693                            UserHandle.USER_SYSTEM));
18694                    pw.println(")");
18695                } else if (mRequiredVerifierPackage != null) {
18696                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18697                    pw.print(",");
18698                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18699                            UserHandle.USER_SYSTEM));
18700                }
18701            }
18702
18703            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18704                    packageName == null) {
18705                if (mIntentFilterVerifierComponent != null) {
18706                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18707                    if (!checkin) {
18708                        if (dumpState.onTitlePrinted())
18709                            pw.println();
18710                        pw.println("Intent Filter Verifier:");
18711                        pw.print("  Using: ");
18712                        pw.print(verifierPackageName);
18713                        pw.print(" (uid=");
18714                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18715                                UserHandle.USER_SYSTEM));
18716                        pw.println(")");
18717                    } else if (verifierPackageName != null) {
18718                        pw.print("ifv,"); pw.print(verifierPackageName);
18719                        pw.print(",");
18720                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18721                                UserHandle.USER_SYSTEM));
18722                    }
18723                } else {
18724                    pw.println();
18725                    pw.println("No Intent Filter Verifier available!");
18726                }
18727            }
18728
18729            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18730                boolean printedHeader = false;
18731                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18732                while (it.hasNext()) {
18733                    String name = it.next();
18734                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18735                    if (!checkin) {
18736                        if (!printedHeader) {
18737                            if (dumpState.onTitlePrinted())
18738                                pw.println();
18739                            pw.println("Libraries:");
18740                            printedHeader = true;
18741                        }
18742                        pw.print("  ");
18743                    } else {
18744                        pw.print("lib,");
18745                    }
18746                    pw.print(name);
18747                    if (!checkin) {
18748                        pw.print(" -> ");
18749                    }
18750                    if (ent.path != null) {
18751                        if (!checkin) {
18752                            pw.print("(jar) ");
18753                            pw.print(ent.path);
18754                        } else {
18755                            pw.print(",jar,");
18756                            pw.print(ent.path);
18757                        }
18758                    } else {
18759                        if (!checkin) {
18760                            pw.print("(apk) ");
18761                            pw.print(ent.apk);
18762                        } else {
18763                            pw.print(",apk,");
18764                            pw.print(ent.apk);
18765                        }
18766                    }
18767                    pw.println();
18768                }
18769            }
18770
18771            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18772                if (dumpState.onTitlePrinted())
18773                    pw.println();
18774                if (!checkin) {
18775                    pw.println("Features:");
18776                }
18777
18778                for (FeatureInfo feat : mAvailableFeatures.values()) {
18779                    if (checkin) {
18780                        pw.print("feat,");
18781                        pw.print(feat.name);
18782                        pw.print(",");
18783                        pw.println(feat.version);
18784                    } else {
18785                        pw.print("  ");
18786                        pw.print(feat.name);
18787                        if (feat.version > 0) {
18788                            pw.print(" version=");
18789                            pw.print(feat.version);
18790                        }
18791                        pw.println();
18792                    }
18793                }
18794            }
18795
18796            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18797                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18798                        : "Activity Resolver Table:", "  ", packageName,
18799                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18800                    dumpState.setTitlePrinted(true);
18801                }
18802            }
18803            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18804                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18805                        : "Receiver Resolver Table:", "  ", packageName,
18806                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18807                    dumpState.setTitlePrinted(true);
18808                }
18809            }
18810            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18811                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18812                        : "Service Resolver Table:", "  ", packageName,
18813                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18814                    dumpState.setTitlePrinted(true);
18815                }
18816            }
18817            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18818                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18819                        : "Provider Resolver Table:", "  ", packageName,
18820                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18821                    dumpState.setTitlePrinted(true);
18822                }
18823            }
18824
18825            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18826                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18827                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18828                    int user = mSettings.mPreferredActivities.keyAt(i);
18829                    if (pir.dump(pw,
18830                            dumpState.getTitlePrinted()
18831                                ? "\nPreferred Activities User " + user + ":"
18832                                : "Preferred Activities User " + user + ":", "  ",
18833                            packageName, true, false)) {
18834                        dumpState.setTitlePrinted(true);
18835                    }
18836                }
18837            }
18838
18839            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18840                pw.flush();
18841                FileOutputStream fout = new FileOutputStream(fd);
18842                BufferedOutputStream str = new BufferedOutputStream(fout);
18843                XmlSerializer serializer = new FastXmlSerializer();
18844                try {
18845                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18846                    serializer.startDocument(null, true);
18847                    serializer.setFeature(
18848                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18849                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18850                    serializer.endDocument();
18851                    serializer.flush();
18852                } catch (IllegalArgumentException e) {
18853                    pw.println("Failed writing: " + e);
18854                } catch (IllegalStateException e) {
18855                    pw.println("Failed writing: " + e);
18856                } catch (IOException e) {
18857                    pw.println("Failed writing: " + e);
18858                }
18859            }
18860
18861            if (!checkin
18862                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18863                    && packageName == null) {
18864                pw.println();
18865                int count = mSettings.mPackages.size();
18866                if (count == 0) {
18867                    pw.println("No applications!");
18868                    pw.println();
18869                } else {
18870                    final String prefix = "  ";
18871                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18872                    if (allPackageSettings.size() == 0) {
18873                        pw.println("No domain preferred apps!");
18874                        pw.println();
18875                    } else {
18876                        pw.println("App verification status:");
18877                        pw.println();
18878                        count = 0;
18879                        for (PackageSetting ps : allPackageSettings) {
18880                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18881                            if (ivi == null || ivi.getPackageName() == null) continue;
18882                            pw.println(prefix + "Package: " + ivi.getPackageName());
18883                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18884                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18885                            pw.println();
18886                            count++;
18887                        }
18888                        if (count == 0) {
18889                            pw.println(prefix + "No app verification established.");
18890                            pw.println();
18891                        }
18892                        for (int userId : sUserManager.getUserIds()) {
18893                            pw.println("App linkages for user " + userId + ":");
18894                            pw.println();
18895                            count = 0;
18896                            for (PackageSetting ps : allPackageSettings) {
18897                                final long status = ps.getDomainVerificationStatusForUser(userId);
18898                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18899                                    continue;
18900                                }
18901                                pw.println(prefix + "Package: " + ps.name);
18902                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18903                                String statusStr = IntentFilterVerificationInfo.
18904                                        getStatusStringFromValue(status);
18905                                pw.println(prefix + "Status:  " + statusStr);
18906                                pw.println();
18907                                count++;
18908                            }
18909                            if (count == 0) {
18910                                pw.println(prefix + "No configured app linkages.");
18911                                pw.println();
18912                            }
18913                        }
18914                    }
18915                }
18916            }
18917
18918            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18919                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18920                if (packageName == null && permissionNames == null) {
18921                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18922                        if (iperm == 0) {
18923                            if (dumpState.onTitlePrinted())
18924                                pw.println();
18925                            pw.println("AppOp Permissions:");
18926                        }
18927                        pw.print("  AppOp Permission ");
18928                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18929                        pw.println(":");
18930                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18931                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18932                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18933                        }
18934                    }
18935                }
18936            }
18937
18938            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18939                boolean printedSomething = false;
18940                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18941                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18942                        continue;
18943                    }
18944                    if (!printedSomething) {
18945                        if (dumpState.onTitlePrinted())
18946                            pw.println();
18947                        pw.println("Registered ContentProviders:");
18948                        printedSomething = true;
18949                    }
18950                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18951                    pw.print("    "); pw.println(p.toString());
18952                }
18953                printedSomething = false;
18954                for (Map.Entry<String, PackageParser.Provider> entry :
18955                        mProvidersByAuthority.entrySet()) {
18956                    PackageParser.Provider p = entry.getValue();
18957                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18958                        continue;
18959                    }
18960                    if (!printedSomething) {
18961                        if (dumpState.onTitlePrinted())
18962                            pw.println();
18963                        pw.println("ContentProvider Authorities:");
18964                        printedSomething = true;
18965                    }
18966                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18967                    pw.print("    "); pw.println(p.toString());
18968                    if (p.info != null && p.info.applicationInfo != null) {
18969                        final String appInfo = p.info.applicationInfo.toString();
18970                        pw.print("      applicationInfo="); pw.println(appInfo);
18971                    }
18972                }
18973            }
18974
18975            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18976                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18977            }
18978
18979            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18980                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18981            }
18982
18983            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18984                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18985            }
18986
18987            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18988                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18989            }
18990
18991            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18992                // XXX should handle packageName != null by dumping only install data that
18993                // the given package is involved with.
18994                if (dumpState.onTitlePrinted()) pw.println();
18995                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18996            }
18997
18998            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18999                // XXX should handle packageName != null by dumping only install data that
19000                // the given package is involved with.
19001                if (dumpState.onTitlePrinted()) pw.println();
19002
19003                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19004                ipw.println();
19005                ipw.println("Frozen packages:");
19006                ipw.increaseIndent();
19007                if (mFrozenPackages.size() == 0) {
19008                    ipw.println("(none)");
19009                } else {
19010                    for (int i = 0; i < mFrozenPackages.size(); i++) {
19011                        ipw.println(mFrozenPackages.valueAt(i));
19012                    }
19013                }
19014                ipw.decreaseIndent();
19015            }
19016
19017            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19018                if (dumpState.onTitlePrinted()) pw.println();
19019                dumpDexoptStateLPr(pw, packageName);
19020            }
19021
19022            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19023                if (dumpState.onTitlePrinted()) pw.println();
19024                dumpCompilerStatsLPr(pw, packageName);
19025            }
19026
19027            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19028                if (dumpState.onTitlePrinted()) pw.println();
19029                mSettings.dumpReadMessagesLPr(pw, dumpState);
19030
19031                pw.println();
19032                pw.println("Package warning messages:");
19033                BufferedReader in = null;
19034                String line = null;
19035                try {
19036                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19037                    while ((line = in.readLine()) != null) {
19038                        if (line.contains("ignored: updated version")) continue;
19039                        pw.println(line);
19040                    }
19041                } catch (IOException ignored) {
19042                } finally {
19043                    IoUtils.closeQuietly(in);
19044                }
19045            }
19046
19047            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19048                BufferedReader in = null;
19049                String line = null;
19050                try {
19051                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19052                    while ((line = in.readLine()) != null) {
19053                        if (line.contains("ignored: updated version")) continue;
19054                        pw.print("msg,");
19055                        pw.println(line);
19056                    }
19057                } catch (IOException ignored) {
19058                } finally {
19059                    IoUtils.closeQuietly(in);
19060                }
19061            }
19062        }
19063    }
19064
19065    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19066        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19067        ipw.println();
19068        ipw.println("Dexopt state:");
19069        ipw.increaseIndent();
19070        Collection<PackageParser.Package> packages = null;
19071        if (packageName != null) {
19072            PackageParser.Package targetPackage = mPackages.get(packageName);
19073            if (targetPackage != null) {
19074                packages = Collections.singletonList(targetPackage);
19075            } else {
19076                ipw.println("Unable to find package: " + packageName);
19077                return;
19078            }
19079        } else {
19080            packages = mPackages.values();
19081        }
19082
19083        for (PackageParser.Package pkg : packages) {
19084            ipw.println("[" + pkg.packageName + "]");
19085            ipw.increaseIndent();
19086            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19087            ipw.decreaseIndent();
19088        }
19089    }
19090
19091    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19092        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19093        ipw.println();
19094        ipw.println("Compiler stats:");
19095        ipw.increaseIndent();
19096        Collection<PackageParser.Package> packages = null;
19097        if (packageName != null) {
19098            PackageParser.Package targetPackage = mPackages.get(packageName);
19099            if (targetPackage != null) {
19100                packages = Collections.singletonList(targetPackage);
19101            } else {
19102                ipw.println("Unable to find package: " + packageName);
19103                return;
19104            }
19105        } else {
19106            packages = mPackages.values();
19107        }
19108
19109        for (PackageParser.Package pkg : packages) {
19110            ipw.println("[" + pkg.packageName + "]");
19111            ipw.increaseIndent();
19112
19113            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19114            if (stats == null) {
19115                ipw.println("(No recorded stats)");
19116            } else {
19117                stats.dump(ipw);
19118            }
19119            ipw.decreaseIndent();
19120        }
19121    }
19122
19123    private String dumpDomainString(String packageName) {
19124        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19125                .getList();
19126        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19127
19128        ArraySet<String> result = new ArraySet<>();
19129        if (iviList.size() > 0) {
19130            for (IntentFilterVerificationInfo ivi : iviList) {
19131                for (String host : ivi.getDomains()) {
19132                    result.add(host);
19133                }
19134            }
19135        }
19136        if (filters != null && filters.size() > 0) {
19137            for (IntentFilter filter : filters) {
19138                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19139                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19140                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19141                    result.addAll(filter.getHostsList());
19142                }
19143            }
19144        }
19145
19146        StringBuilder sb = new StringBuilder(result.size() * 16);
19147        for (String domain : result) {
19148            if (sb.length() > 0) sb.append(" ");
19149            sb.append(domain);
19150        }
19151        return sb.toString();
19152    }
19153
19154    // ------- apps on sdcard specific code -------
19155    static final boolean DEBUG_SD_INSTALL = false;
19156
19157    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19158
19159    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19160
19161    private boolean mMediaMounted = false;
19162
19163    static String getEncryptKey() {
19164        try {
19165            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19166                    SD_ENCRYPTION_KEYSTORE_NAME);
19167            if (sdEncKey == null) {
19168                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19169                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19170                if (sdEncKey == null) {
19171                    Slog.e(TAG, "Failed to create encryption keys");
19172                    return null;
19173                }
19174            }
19175            return sdEncKey;
19176        } catch (NoSuchAlgorithmException nsae) {
19177            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19178            return null;
19179        } catch (IOException ioe) {
19180            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19181            return null;
19182        }
19183    }
19184
19185    /*
19186     * Update media status on PackageManager.
19187     */
19188    @Override
19189    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19190        int callingUid = Binder.getCallingUid();
19191        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19192            throw new SecurityException("Media status can only be updated by the system");
19193        }
19194        // reader; this apparently protects mMediaMounted, but should probably
19195        // be a different lock in that case.
19196        synchronized (mPackages) {
19197            Log.i(TAG, "Updating external media status from "
19198                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19199                    + (mediaStatus ? "mounted" : "unmounted"));
19200            if (DEBUG_SD_INSTALL)
19201                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19202                        + ", mMediaMounted=" + mMediaMounted);
19203            if (mediaStatus == mMediaMounted) {
19204                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19205                        : 0, -1);
19206                mHandler.sendMessage(msg);
19207                return;
19208            }
19209            mMediaMounted = mediaStatus;
19210        }
19211        // Queue up an async operation since the package installation may take a
19212        // little while.
19213        mHandler.post(new Runnable() {
19214            public void run() {
19215                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19216            }
19217        });
19218    }
19219
19220    /**
19221     * Called by MountService when the initial ASECs to scan are available.
19222     * Should block until all the ASEC containers are finished being scanned.
19223     */
19224    public void scanAvailableAsecs() {
19225        updateExternalMediaStatusInner(true, false, false);
19226    }
19227
19228    /*
19229     * Collect information of applications on external media, map them against
19230     * existing containers and update information based on current mount status.
19231     * Please note that we always have to report status if reportStatus has been
19232     * set to true especially when unloading packages.
19233     */
19234    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19235            boolean externalStorage) {
19236        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19237        int[] uidArr = EmptyArray.INT;
19238
19239        final String[] list = PackageHelper.getSecureContainerList();
19240        if (ArrayUtils.isEmpty(list)) {
19241            Log.i(TAG, "No secure containers found");
19242        } else {
19243            // Process list of secure containers and categorize them
19244            // as active or stale based on their package internal state.
19245
19246            // reader
19247            synchronized (mPackages) {
19248                for (String cid : list) {
19249                    // Leave stages untouched for now; installer service owns them
19250                    if (PackageInstallerService.isStageName(cid)) continue;
19251
19252                    if (DEBUG_SD_INSTALL)
19253                        Log.i(TAG, "Processing container " + cid);
19254                    String pkgName = getAsecPackageName(cid);
19255                    if (pkgName == null) {
19256                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19257                        continue;
19258                    }
19259                    if (DEBUG_SD_INSTALL)
19260                        Log.i(TAG, "Looking for pkg : " + pkgName);
19261
19262                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19263                    if (ps == null) {
19264                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19265                        continue;
19266                    }
19267
19268                    /*
19269                     * Skip packages that are not external if we're unmounting
19270                     * external storage.
19271                     */
19272                    if (externalStorage && !isMounted && !isExternal(ps)) {
19273                        continue;
19274                    }
19275
19276                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19277                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19278                    // The package status is changed only if the code path
19279                    // matches between settings and the container id.
19280                    if (ps.codePathString != null
19281                            && ps.codePathString.startsWith(args.getCodePath())) {
19282                        if (DEBUG_SD_INSTALL) {
19283                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19284                                    + " at code path: " + ps.codePathString);
19285                        }
19286
19287                        // We do have a valid package installed on sdcard
19288                        processCids.put(args, ps.codePathString);
19289                        final int uid = ps.appId;
19290                        if (uid != -1) {
19291                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19292                        }
19293                    } else {
19294                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19295                                + ps.codePathString);
19296                    }
19297                }
19298            }
19299
19300            Arrays.sort(uidArr);
19301        }
19302
19303        // Process packages with valid entries.
19304        if (isMounted) {
19305            if (DEBUG_SD_INSTALL)
19306                Log.i(TAG, "Loading packages");
19307            loadMediaPackages(processCids, uidArr, externalStorage);
19308            startCleaningPackages();
19309            mInstallerService.onSecureContainersAvailable();
19310        } else {
19311            if (DEBUG_SD_INSTALL)
19312                Log.i(TAG, "Unloading packages");
19313            unloadMediaPackages(processCids, uidArr, reportStatus);
19314        }
19315    }
19316
19317    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19318            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19319        final int size = infos.size();
19320        final String[] packageNames = new String[size];
19321        final int[] packageUids = new int[size];
19322        for (int i = 0; i < size; i++) {
19323            final ApplicationInfo info = infos.get(i);
19324            packageNames[i] = info.packageName;
19325            packageUids[i] = info.uid;
19326        }
19327        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19328                finishedReceiver);
19329    }
19330
19331    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19332            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19333        sendResourcesChangedBroadcast(mediaStatus, replacing,
19334                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19335    }
19336
19337    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19338            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19339        int size = pkgList.length;
19340        if (size > 0) {
19341            // Send broadcasts here
19342            Bundle extras = new Bundle();
19343            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19344            if (uidArr != null) {
19345                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19346            }
19347            if (replacing) {
19348                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19349            }
19350            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19351                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19352            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19353        }
19354    }
19355
19356   /*
19357     * Look at potentially valid container ids from processCids If package
19358     * information doesn't match the one on record or package scanning fails,
19359     * the cid is added to list of removeCids. We currently don't delete stale
19360     * containers.
19361     */
19362    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19363            boolean externalStorage) {
19364        ArrayList<String> pkgList = new ArrayList<String>();
19365        Set<AsecInstallArgs> keys = processCids.keySet();
19366
19367        for (AsecInstallArgs args : keys) {
19368            String codePath = processCids.get(args);
19369            if (DEBUG_SD_INSTALL)
19370                Log.i(TAG, "Loading container : " + args.cid);
19371            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19372            try {
19373                // Make sure there are no container errors first.
19374                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19375                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19376                            + " when installing from sdcard");
19377                    continue;
19378                }
19379                // Check code path here.
19380                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19381                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19382                            + " does not match one in settings " + codePath);
19383                    continue;
19384                }
19385                // Parse package
19386                int parseFlags = mDefParseFlags;
19387                if (args.isExternalAsec()) {
19388                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19389                }
19390                if (args.isFwdLocked()) {
19391                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19392                }
19393
19394                synchronized (mInstallLock) {
19395                    PackageParser.Package pkg = null;
19396                    try {
19397                        // Sadly we don't know the package name yet to freeze it
19398                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19399                                SCAN_IGNORE_FROZEN, 0, null);
19400                    } catch (PackageManagerException e) {
19401                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19402                    }
19403                    // Scan the package
19404                    if (pkg != null) {
19405                        /*
19406                         * TODO why is the lock being held? doPostInstall is
19407                         * called in other places without the lock. This needs
19408                         * to be straightened out.
19409                         */
19410                        // writer
19411                        synchronized (mPackages) {
19412                            retCode = PackageManager.INSTALL_SUCCEEDED;
19413                            pkgList.add(pkg.packageName);
19414                            // Post process args
19415                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19416                                    pkg.applicationInfo.uid);
19417                        }
19418                    } else {
19419                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19420                    }
19421                }
19422
19423            } finally {
19424                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19425                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19426                }
19427            }
19428        }
19429        // writer
19430        synchronized (mPackages) {
19431            // If the platform SDK has changed since the last time we booted,
19432            // we need to re-grant app permission to catch any new ones that
19433            // appear. This is really a hack, and means that apps can in some
19434            // cases get permissions that the user didn't initially explicitly
19435            // allow... it would be nice to have some better way to handle
19436            // this situation.
19437            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19438                    : mSettings.getInternalVersion();
19439            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19440                    : StorageManager.UUID_PRIVATE_INTERNAL;
19441
19442            int updateFlags = UPDATE_PERMISSIONS_ALL;
19443            if (ver.sdkVersion != mSdkVersion) {
19444                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19445                        + mSdkVersion + "; regranting permissions for external");
19446                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19447            }
19448            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19449
19450            // Yay, everything is now upgraded
19451            ver.forceCurrent();
19452
19453            // can downgrade to reader
19454            // Persist settings
19455            mSettings.writeLPr();
19456        }
19457        // Send a broadcast to let everyone know we are done processing
19458        if (pkgList.size() > 0) {
19459            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19460        }
19461    }
19462
19463   /*
19464     * Utility method to unload a list of specified containers
19465     */
19466    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19467        // Just unmount all valid containers.
19468        for (AsecInstallArgs arg : cidArgs) {
19469            synchronized (mInstallLock) {
19470                arg.doPostDeleteLI(false);
19471           }
19472       }
19473   }
19474
19475    /*
19476     * Unload packages mounted on external media. This involves deleting package
19477     * data from internal structures, sending broadcasts about disabled packages,
19478     * gc'ing to free up references, unmounting all secure containers
19479     * corresponding to packages on external media, and posting a
19480     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19481     * that we always have to post this message if status has been requested no
19482     * matter what.
19483     */
19484    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19485            final boolean reportStatus) {
19486        if (DEBUG_SD_INSTALL)
19487            Log.i(TAG, "unloading media packages");
19488        ArrayList<String> pkgList = new ArrayList<String>();
19489        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19490        final Set<AsecInstallArgs> keys = processCids.keySet();
19491        for (AsecInstallArgs args : keys) {
19492            String pkgName = args.getPackageName();
19493            if (DEBUG_SD_INSTALL)
19494                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19495            // Delete package internally
19496            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19497            synchronized (mInstallLock) {
19498                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19499                final boolean res;
19500                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19501                        "unloadMediaPackages")) {
19502                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19503                            null);
19504                }
19505                if (res) {
19506                    pkgList.add(pkgName);
19507                } else {
19508                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19509                    failedList.add(args);
19510                }
19511            }
19512        }
19513
19514        // reader
19515        synchronized (mPackages) {
19516            // We didn't update the settings after removing each package;
19517            // write them now for all packages.
19518            mSettings.writeLPr();
19519        }
19520
19521        // We have to absolutely send UPDATED_MEDIA_STATUS only
19522        // after confirming that all the receivers processed the ordered
19523        // broadcast when packages get disabled, force a gc to clean things up.
19524        // and unload all the containers.
19525        if (pkgList.size() > 0) {
19526            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19527                    new IIntentReceiver.Stub() {
19528                public void performReceive(Intent intent, int resultCode, String data,
19529                        Bundle extras, boolean ordered, boolean sticky,
19530                        int sendingUser) throws RemoteException {
19531                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19532                            reportStatus ? 1 : 0, 1, keys);
19533                    mHandler.sendMessage(msg);
19534                }
19535            });
19536        } else {
19537            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19538                    keys);
19539            mHandler.sendMessage(msg);
19540        }
19541    }
19542
19543    private void loadPrivatePackages(final VolumeInfo vol) {
19544        mHandler.post(new Runnable() {
19545            @Override
19546            public void run() {
19547                loadPrivatePackagesInner(vol);
19548            }
19549        });
19550    }
19551
19552    private void loadPrivatePackagesInner(VolumeInfo vol) {
19553        final String volumeUuid = vol.fsUuid;
19554        if (TextUtils.isEmpty(volumeUuid)) {
19555            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19556            return;
19557        }
19558
19559        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19560        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19561        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19562
19563        final VersionInfo ver;
19564        final List<PackageSetting> packages;
19565        synchronized (mPackages) {
19566            ver = mSettings.findOrCreateVersion(volumeUuid);
19567            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19568        }
19569
19570        for (PackageSetting ps : packages) {
19571            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19572            synchronized (mInstallLock) {
19573                final PackageParser.Package pkg;
19574                try {
19575                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19576                    loaded.add(pkg.applicationInfo);
19577
19578                } catch (PackageManagerException e) {
19579                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19580                }
19581
19582                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19583                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19584                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19585                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19586                }
19587            }
19588        }
19589
19590        // Reconcile app data for all started/unlocked users
19591        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19592        final UserManager um = mContext.getSystemService(UserManager.class);
19593        UserManagerInternal umInternal = getUserManagerInternal();
19594        for (UserInfo user : um.getUsers()) {
19595            final int flags;
19596            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19597                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19598            } else if (umInternal.isUserRunning(user.id)) {
19599                flags = StorageManager.FLAG_STORAGE_DE;
19600            } else {
19601                continue;
19602            }
19603
19604            try {
19605                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19606                synchronized (mInstallLock) {
19607                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
19608                }
19609            } catch (IllegalStateException e) {
19610                // Device was probably ejected, and we'll process that event momentarily
19611                Slog.w(TAG, "Failed to prepare storage: " + e);
19612            }
19613        }
19614
19615        synchronized (mPackages) {
19616            int updateFlags = UPDATE_PERMISSIONS_ALL;
19617            if (ver.sdkVersion != mSdkVersion) {
19618                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19619                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19620                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19621            }
19622            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19623
19624            // Yay, everything is now upgraded
19625            ver.forceCurrent();
19626
19627            mSettings.writeLPr();
19628        }
19629
19630        for (PackageFreezer freezer : freezers) {
19631            freezer.close();
19632        }
19633
19634        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19635        sendResourcesChangedBroadcast(true, false, loaded, null);
19636    }
19637
19638    private void unloadPrivatePackages(final VolumeInfo vol) {
19639        mHandler.post(new Runnable() {
19640            @Override
19641            public void run() {
19642                unloadPrivatePackagesInner(vol);
19643            }
19644        });
19645    }
19646
19647    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19648        final String volumeUuid = vol.fsUuid;
19649        if (TextUtils.isEmpty(volumeUuid)) {
19650            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19651            return;
19652        }
19653
19654        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19655        synchronized (mInstallLock) {
19656        synchronized (mPackages) {
19657            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19658            for (PackageSetting ps : packages) {
19659                if (ps.pkg == null) continue;
19660
19661                final ApplicationInfo info = ps.pkg.applicationInfo;
19662                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19663                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19664
19665                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19666                        "unloadPrivatePackagesInner")) {
19667                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19668                            false, null)) {
19669                        unloaded.add(info);
19670                    } else {
19671                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19672                    }
19673                }
19674
19675                // Try very hard to release any references to this package
19676                // so we don't risk the system server being killed due to
19677                // open FDs
19678                AttributeCache.instance().removePackage(ps.name);
19679            }
19680
19681            mSettings.writeLPr();
19682        }
19683        }
19684
19685        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19686        sendResourcesChangedBroadcast(false, false, unloaded, null);
19687
19688        // Try very hard to release any references to this path so we don't risk
19689        // the system server being killed due to open FDs
19690        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19691
19692        for (int i = 0; i < 3; i++) {
19693            System.gc();
19694            System.runFinalization();
19695        }
19696    }
19697
19698    /**
19699     * Prepare storage areas for given user on all mounted devices.
19700     */
19701    void prepareUserData(int userId, int userSerial, int flags) {
19702        synchronized (mInstallLock) {
19703            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19704            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19705                final String volumeUuid = vol.getFsUuid();
19706                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19707            }
19708        }
19709    }
19710
19711    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19712            boolean allowRecover) {
19713        // Prepare storage and verify that serial numbers are consistent; if
19714        // there's a mismatch we need to destroy to avoid leaking data
19715        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19716        try {
19717            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19718
19719            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19720                UserManagerService.enforceSerialNumber(
19721                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19722                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19723                    UserManagerService.enforceSerialNumber(
19724                            Environment.getDataSystemDeDirectory(userId), userSerial);
19725                }
19726            }
19727            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19728                UserManagerService.enforceSerialNumber(
19729                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19730                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19731                    UserManagerService.enforceSerialNumber(
19732                            Environment.getDataSystemCeDirectory(userId), userSerial);
19733                }
19734            }
19735
19736            synchronized (mInstallLock) {
19737                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19738            }
19739        } catch (Exception e) {
19740            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19741                    + " because we failed to prepare: " + e);
19742            destroyUserDataLI(volumeUuid, userId,
19743                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19744
19745            if (allowRecover) {
19746                // Try one last time; if we fail again we're really in trouble
19747                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19748            }
19749        }
19750    }
19751
19752    /**
19753     * Destroy storage areas for given user on all mounted devices.
19754     */
19755    void destroyUserData(int userId, int flags) {
19756        synchronized (mInstallLock) {
19757            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19758            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19759                final String volumeUuid = vol.getFsUuid();
19760                destroyUserDataLI(volumeUuid, userId, flags);
19761            }
19762        }
19763    }
19764
19765    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19766        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19767        try {
19768            // Clean up app data, profile data, and media data
19769            mInstaller.destroyUserData(volumeUuid, userId, flags);
19770
19771            // Clean up system data
19772            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19773                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19774                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19775                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19776                }
19777                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19778                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19779                }
19780            }
19781
19782            // Data with special labels is now gone, so finish the job
19783            storage.destroyUserStorage(volumeUuid, userId, flags);
19784
19785        } catch (Exception e) {
19786            logCriticalInfo(Log.WARN,
19787                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19788        }
19789    }
19790
19791    /**
19792     * Examine all users present on given mounted volume, and destroy data
19793     * belonging to users that are no longer valid, or whose user ID has been
19794     * recycled.
19795     */
19796    private void reconcileUsers(String volumeUuid) {
19797        final List<File> files = new ArrayList<>();
19798        Collections.addAll(files, FileUtils
19799                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19800        Collections.addAll(files, FileUtils
19801                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19802        Collections.addAll(files, FileUtils
19803                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19804        Collections.addAll(files, FileUtils
19805                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19806        for (File file : files) {
19807            if (!file.isDirectory()) continue;
19808
19809            final int userId;
19810            final UserInfo info;
19811            try {
19812                userId = Integer.parseInt(file.getName());
19813                info = sUserManager.getUserInfo(userId);
19814            } catch (NumberFormatException e) {
19815                Slog.w(TAG, "Invalid user directory " + file);
19816                continue;
19817            }
19818
19819            boolean destroyUser = false;
19820            if (info == null) {
19821                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19822                        + " because no matching user was found");
19823                destroyUser = true;
19824            } else if (!mOnlyCore) {
19825                try {
19826                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19827                } catch (IOException e) {
19828                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19829                            + " because we failed to enforce serial number: " + e);
19830                    destroyUser = true;
19831                }
19832            }
19833
19834            if (destroyUser) {
19835                synchronized (mInstallLock) {
19836                    destroyUserDataLI(volumeUuid, userId,
19837                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19838                }
19839            }
19840        }
19841    }
19842
19843    private void assertPackageKnown(String volumeUuid, String packageName)
19844            throws PackageManagerException {
19845        synchronized (mPackages) {
19846            final PackageSetting ps = mSettings.mPackages.get(packageName);
19847            if (ps == null) {
19848                throw new PackageManagerException("Package " + packageName + " is unknown");
19849            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19850                throw new PackageManagerException(
19851                        "Package " + packageName + " found on unknown volume " + volumeUuid
19852                                + "; expected volume " + ps.volumeUuid);
19853            }
19854        }
19855    }
19856
19857    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19858            throws PackageManagerException {
19859        synchronized (mPackages) {
19860            final PackageSetting ps = mSettings.mPackages.get(packageName);
19861            if (ps == null) {
19862                throw new PackageManagerException("Package " + packageName + " is unknown");
19863            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19864                throw new PackageManagerException(
19865                        "Package " + packageName + " found on unknown volume " + volumeUuid
19866                                + "; expected volume " + ps.volumeUuid);
19867            } else if (!ps.getInstalled(userId)) {
19868                throw new PackageManagerException(
19869                        "Package " + packageName + " not installed for user " + userId);
19870            }
19871        }
19872    }
19873
19874    /**
19875     * Examine all apps present on given mounted volume, and destroy apps that
19876     * aren't expected, either due to uninstallation or reinstallation on
19877     * another volume.
19878     */
19879    private void reconcileApps(String volumeUuid) {
19880        final File[] files = FileUtils
19881                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19882        for (File file : files) {
19883            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19884                    && !PackageInstallerService.isStageName(file.getName());
19885            if (!isPackage) {
19886                // Ignore entries which are not packages
19887                continue;
19888            }
19889
19890            try {
19891                final PackageLite pkg = PackageParser.parsePackageLite(file,
19892                        PackageParser.PARSE_MUST_BE_APK);
19893                assertPackageKnown(volumeUuid, pkg.packageName);
19894
19895            } catch (PackageParserException | PackageManagerException e) {
19896                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19897                synchronized (mInstallLock) {
19898                    removeCodePathLI(file);
19899                }
19900            }
19901        }
19902    }
19903
19904    /**
19905     * Reconcile all app data for the given user.
19906     * <p>
19907     * Verifies that directories exist and that ownership and labeling is
19908     * correct for all installed apps on all mounted volumes.
19909     */
19910    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
19911        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19912        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19913            final String volumeUuid = vol.getFsUuid();
19914            synchronized (mInstallLock) {
19915                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
19916            }
19917        }
19918    }
19919
19920    /**
19921     * Reconcile all app data on given mounted volume.
19922     * <p>
19923     * Destroys app data that isn't expected, either due to uninstallation or
19924     * reinstallation on another volume.
19925     * <p>
19926     * Verifies that directories exist and that ownership and labeling is
19927     * correct for all installed apps.
19928     */
19929    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
19930            boolean migrateAppData) {
19931        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19932                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
19933
19934        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19935        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19936
19937        // First look for stale data that doesn't belong, and check if things
19938        // have changed since we did our last restorecon
19939        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19940            if (StorageManager.isFileEncryptedNativeOrEmulated()
19941                    && !StorageManager.isUserKeyUnlocked(userId)) {
19942                throw new RuntimeException(
19943                        "Yikes, someone asked us to reconcile CE storage while " + userId
19944                                + " was still locked; this would have caused massive data loss!");
19945            }
19946
19947            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19948            for (File file : files) {
19949                final String packageName = file.getName();
19950                try {
19951                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19952                } catch (PackageManagerException e) {
19953                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19954                    try {
19955                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19956                                StorageManager.FLAG_STORAGE_CE, 0);
19957                    } catch (InstallerException e2) {
19958                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19959                    }
19960                }
19961            }
19962        }
19963        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19964            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19965            for (File file : files) {
19966                final String packageName = file.getName();
19967                try {
19968                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19969                } catch (PackageManagerException e) {
19970                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19971                    try {
19972                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19973                                StorageManager.FLAG_STORAGE_DE, 0);
19974                    } catch (InstallerException e2) {
19975                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19976                    }
19977                }
19978            }
19979        }
19980
19981        // Ensure that data directories are ready to roll for all packages
19982        // installed for this volume and user
19983        final List<PackageSetting> packages;
19984        synchronized (mPackages) {
19985            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19986        }
19987        int preparedCount = 0;
19988        for (PackageSetting ps : packages) {
19989            final String packageName = ps.name;
19990            if (ps.pkg == null) {
19991                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19992                // TODO: might be due to legacy ASEC apps; we should circle back
19993                // and reconcile again once they're scanned
19994                continue;
19995            }
19996
19997            if (ps.getInstalled(userId)) {
19998                prepareAppDataLIF(ps.pkg, userId, flags);
19999
20000                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
20001                    // We may have just shuffled around app data directories, so
20002                    // prepare them one more time
20003                    prepareAppDataLIF(ps.pkg, userId, flags);
20004                }
20005
20006                preparedCount++;
20007            }
20008        }
20009
20010        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20011    }
20012
20013    /**
20014     * Prepare app data for the given app just after it was installed or
20015     * upgraded. This method carefully only touches users that it's installed
20016     * for, and it forces a restorecon to handle any seinfo changes.
20017     * <p>
20018     * Verifies that directories exist and that ownership and labeling is
20019     * correct for all installed apps. If there is an ownership mismatch, it
20020     * will try recovering system apps by wiping data; third-party app data is
20021     * left intact.
20022     * <p>
20023     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20024     */
20025    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20026        final PackageSetting ps;
20027        synchronized (mPackages) {
20028            ps = mSettings.mPackages.get(pkg.packageName);
20029            mSettings.writeKernelMappingLPr(ps);
20030        }
20031
20032        final UserManager um = mContext.getSystemService(UserManager.class);
20033        UserManagerInternal umInternal = getUserManagerInternal();
20034        for (UserInfo user : um.getUsers()) {
20035            final int flags;
20036            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20037                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20038            } else if (umInternal.isUserRunning(user.id)) {
20039                flags = StorageManager.FLAG_STORAGE_DE;
20040            } else {
20041                continue;
20042            }
20043
20044            if (ps.getInstalled(user.id)) {
20045                // TODO: when user data is locked, mark that we're still dirty
20046                prepareAppDataLIF(pkg, user.id, flags);
20047            }
20048        }
20049    }
20050
20051    /**
20052     * Prepare app data for the given app.
20053     * <p>
20054     * Verifies that directories exist and that ownership and labeling is
20055     * correct for all installed apps. If there is an ownership mismatch, this
20056     * will try recovering system apps by wiping data; third-party app data is
20057     * left intact.
20058     */
20059    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20060        if (pkg == null) {
20061            Slog.wtf(TAG, "Package was null!", new Throwable());
20062            return;
20063        }
20064        prepareAppDataLeafLIF(pkg, userId, flags);
20065        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20066        for (int i = 0; i < childCount; i++) {
20067            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20068        }
20069    }
20070
20071    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20072        if (DEBUG_APP_DATA) {
20073            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20074                    + Integer.toHexString(flags));
20075        }
20076
20077        final String volumeUuid = pkg.volumeUuid;
20078        final String packageName = pkg.packageName;
20079        final ApplicationInfo app = pkg.applicationInfo;
20080        final int appId = UserHandle.getAppId(app.uid);
20081
20082        Preconditions.checkNotNull(app.seinfo);
20083
20084        try {
20085            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20086                    appId, app.seinfo, app.targetSdkVersion);
20087        } catch (InstallerException e) {
20088            if (app.isSystemApp()) {
20089                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20090                        + ", but trying to recover: " + e);
20091                destroyAppDataLeafLIF(pkg, userId, flags);
20092                try {
20093                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20094                            appId, app.seinfo, app.targetSdkVersion);
20095                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20096                } catch (InstallerException e2) {
20097                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20098                }
20099            } else {
20100                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20101            }
20102        }
20103
20104        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20105            try {
20106                // CE storage is unlocked right now, so read out the inode and
20107                // remember for use later when it's locked
20108                // TODO: mark this structure as dirty so we persist it!
20109                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20110                        StorageManager.FLAG_STORAGE_CE);
20111                synchronized (mPackages) {
20112                    final PackageSetting ps = mSettings.mPackages.get(packageName);
20113                    if (ps != null) {
20114                        ps.setCeDataInode(ceDataInode, userId);
20115                    }
20116                }
20117            } catch (InstallerException e) {
20118                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20119            }
20120        }
20121
20122        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20123    }
20124
20125    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20126        if (pkg == null) {
20127            Slog.wtf(TAG, "Package was null!", new Throwable());
20128            return;
20129        }
20130        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20131        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20132        for (int i = 0; i < childCount; i++) {
20133            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20134        }
20135    }
20136
20137    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20138        final String volumeUuid = pkg.volumeUuid;
20139        final String packageName = pkg.packageName;
20140        final ApplicationInfo app = pkg.applicationInfo;
20141
20142        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20143            // Create a native library symlink only if we have native libraries
20144            // and if the native libraries are 32 bit libraries. We do not provide
20145            // this symlink for 64 bit libraries.
20146            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20147                final String nativeLibPath = app.nativeLibraryDir;
20148                try {
20149                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20150                            nativeLibPath, userId);
20151                } catch (InstallerException e) {
20152                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20153                }
20154            }
20155        }
20156    }
20157
20158    /**
20159     * For system apps on non-FBE devices, this method migrates any existing
20160     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20161     * requested by the app.
20162     */
20163    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20164        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20165                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20166            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20167                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20168            try {
20169                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20170                        storageTarget);
20171            } catch (InstallerException e) {
20172                logCriticalInfo(Log.WARN,
20173                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20174            }
20175            return true;
20176        } else {
20177            return false;
20178        }
20179    }
20180
20181    public PackageFreezer freezePackage(String packageName, String killReason) {
20182        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20183    }
20184
20185    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20186        return new PackageFreezer(packageName, userId, killReason);
20187    }
20188
20189    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20190            String killReason) {
20191        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20192    }
20193
20194    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20195            String killReason) {
20196        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20197            return new PackageFreezer();
20198        } else {
20199            return freezePackage(packageName, userId, killReason);
20200        }
20201    }
20202
20203    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20204            String killReason) {
20205        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20206    }
20207
20208    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20209            String killReason) {
20210        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20211            return new PackageFreezer();
20212        } else {
20213            return freezePackage(packageName, userId, killReason);
20214        }
20215    }
20216
20217    /**
20218     * Class that freezes and kills the given package upon creation, and
20219     * unfreezes it upon closing. This is typically used when doing surgery on
20220     * app code/data to prevent the app from running while you're working.
20221     */
20222    private class PackageFreezer implements AutoCloseable {
20223        private final String mPackageName;
20224        private final PackageFreezer[] mChildren;
20225
20226        private final boolean mWeFroze;
20227
20228        private final AtomicBoolean mClosed = new AtomicBoolean();
20229        private final CloseGuard mCloseGuard = CloseGuard.get();
20230
20231        /**
20232         * Create and return a stub freezer that doesn't actually do anything,
20233         * typically used when someone requested
20234         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20235         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20236         */
20237        public PackageFreezer() {
20238            mPackageName = null;
20239            mChildren = null;
20240            mWeFroze = false;
20241            mCloseGuard.open("close");
20242        }
20243
20244        public PackageFreezer(String packageName, int userId, String killReason) {
20245            synchronized (mPackages) {
20246                mPackageName = packageName;
20247                mWeFroze = mFrozenPackages.add(mPackageName);
20248
20249                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20250                if (ps != null) {
20251                    killApplication(ps.name, ps.appId, userId, killReason);
20252                }
20253
20254                final PackageParser.Package p = mPackages.get(packageName);
20255                if (p != null && p.childPackages != null) {
20256                    final int N = p.childPackages.size();
20257                    mChildren = new PackageFreezer[N];
20258                    for (int i = 0; i < N; i++) {
20259                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20260                                userId, killReason);
20261                    }
20262                } else {
20263                    mChildren = null;
20264                }
20265            }
20266            mCloseGuard.open("close");
20267        }
20268
20269        @Override
20270        protected void finalize() throws Throwable {
20271            try {
20272                mCloseGuard.warnIfOpen();
20273                close();
20274            } finally {
20275                super.finalize();
20276            }
20277        }
20278
20279        @Override
20280        public void close() {
20281            mCloseGuard.close();
20282            if (mClosed.compareAndSet(false, true)) {
20283                synchronized (mPackages) {
20284                    if (mWeFroze) {
20285                        mFrozenPackages.remove(mPackageName);
20286                    }
20287
20288                    if (mChildren != null) {
20289                        for (PackageFreezer freezer : mChildren) {
20290                            freezer.close();
20291                        }
20292                    }
20293                }
20294            }
20295        }
20296    }
20297
20298    /**
20299     * Verify that given package is currently frozen.
20300     */
20301    private void checkPackageFrozen(String packageName) {
20302        synchronized (mPackages) {
20303            if (!mFrozenPackages.contains(packageName)) {
20304                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20305            }
20306        }
20307    }
20308
20309    @Override
20310    public int movePackage(final String packageName, final String volumeUuid) {
20311        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20312
20313        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20314        final int moveId = mNextMoveId.getAndIncrement();
20315        mHandler.post(new Runnable() {
20316            @Override
20317            public void run() {
20318                try {
20319                    movePackageInternal(packageName, volumeUuid, moveId, user);
20320                } catch (PackageManagerException e) {
20321                    Slog.w(TAG, "Failed to move " + packageName, e);
20322                    mMoveCallbacks.notifyStatusChanged(moveId,
20323                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20324                }
20325            }
20326        });
20327        return moveId;
20328    }
20329
20330    private void movePackageInternal(final String packageName, final String volumeUuid,
20331            final int moveId, UserHandle user) throws PackageManagerException {
20332        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20333        final PackageManager pm = mContext.getPackageManager();
20334
20335        final boolean currentAsec;
20336        final String currentVolumeUuid;
20337        final File codeFile;
20338        final String installerPackageName;
20339        final String packageAbiOverride;
20340        final int appId;
20341        final String seinfo;
20342        final String label;
20343        final int targetSdkVersion;
20344        final PackageFreezer freezer;
20345        final int[] installedUserIds;
20346
20347        // reader
20348        synchronized (mPackages) {
20349            final PackageParser.Package pkg = mPackages.get(packageName);
20350            final PackageSetting ps = mSettings.mPackages.get(packageName);
20351            if (pkg == null || ps == null) {
20352                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20353            }
20354
20355            if (pkg.applicationInfo.isSystemApp()) {
20356                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20357                        "Cannot move system application");
20358            }
20359
20360            if (pkg.applicationInfo.isExternalAsec()) {
20361                currentAsec = true;
20362                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20363            } else if (pkg.applicationInfo.isForwardLocked()) {
20364                currentAsec = true;
20365                currentVolumeUuid = "forward_locked";
20366            } else {
20367                currentAsec = false;
20368                currentVolumeUuid = ps.volumeUuid;
20369
20370                final File probe = new File(pkg.codePath);
20371                final File probeOat = new File(probe, "oat");
20372                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20373                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20374                            "Move only supported for modern cluster style installs");
20375                }
20376            }
20377
20378            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20379                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20380                        "Package already moved to " + volumeUuid);
20381            }
20382            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20383                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20384                        "Device admin cannot be moved");
20385            }
20386
20387            if (mFrozenPackages.contains(packageName)) {
20388                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20389                        "Failed to move already frozen package");
20390            }
20391
20392            codeFile = new File(pkg.codePath);
20393            installerPackageName = ps.installerPackageName;
20394            packageAbiOverride = ps.cpuAbiOverrideString;
20395            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20396            seinfo = pkg.applicationInfo.seinfo;
20397            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20398            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20399            freezer = freezePackage(packageName, "movePackageInternal");
20400            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20401        }
20402
20403        final Bundle extras = new Bundle();
20404        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20405        extras.putString(Intent.EXTRA_TITLE, label);
20406        mMoveCallbacks.notifyCreated(moveId, extras);
20407
20408        int installFlags;
20409        final boolean moveCompleteApp;
20410        final File measurePath;
20411
20412        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20413            installFlags = INSTALL_INTERNAL;
20414            moveCompleteApp = !currentAsec;
20415            measurePath = Environment.getDataAppDirectory(volumeUuid);
20416        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20417            installFlags = INSTALL_EXTERNAL;
20418            moveCompleteApp = false;
20419            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20420        } else {
20421            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20422            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20423                    || !volume.isMountedWritable()) {
20424                freezer.close();
20425                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20426                        "Move location not mounted private volume");
20427            }
20428
20429            Preconditions.checkState(!currentAsec);
20430
20431            installFlags = INSTALL_INTERNAL;
20432            moveCompleteApp = true;
20433            measurePath = Environment.getDataAppDirectory(volumeUuid);
20434        }
20435
20436        final PackageStats stats = new PackageStats(null, -1);
20437        synchronized (mInstaller) {
20438            for (int userId : installedUserIds) {
20439                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20440                    freezer.close();
20441                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20442                            "Failed to measure package size");
20443                }
20444            }
20445        }
20446
20447        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20448                + stats.dataSize);
20449
20450        final long startFreeBytes = measurePath.getFreeSpace();
20451        final long sizeBytes;
20452        if (moveCompleteApp) {
20453            sizeBytes = stats.codeSize + stats.dataSize;
20454        } else {
20455            sizeBytes = stats.codeSize;
20456        }
20457
20458        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20459            freezer.close();
20460            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20461                    "Not enough free space to move");
20462        }
20463
20464        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20465
20466        final CountDownLatch installedLatch = new CountDownLatch(1);
20467        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20468            @Override
20469            public void onUserActionRequired(Intent intent) throws RemoteException {
20470                throw new IllegalStateException();
20471            }
20472
20473            @Override
20474            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20475                    Bundle extras) throws RemoteException {
20476                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20477                        + PackageManager.installStatusToString(returnCode, msg));
20478
20479                installedLatch.countDown();
20480                freezer.close();
20481
20482                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20483                switch (status) {
20484                    case PackageInstaller.STATUS_SUCCESS:
20485                        mMoveCallbacks.notifyStatusChanged(moveId,
20486                                PackageManager.MOVE_SUCCEEDED);
20487                        break;
20488                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20489                        mMoveCallbacks.notifyStatusChanged(moveId,
20490                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20491                        break;
20492                    default:
20493                        mMoveCallbacks.notifyStatusChanged(moveId,
20494                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20495                        break;
20496                }
20497            }
20498        };
20499
20500        final MoveInfo move;
20501        if (moveCompleteApp) {
20502            // Kick off a thread to report progress estimates
20503            new Thread() {
20504                @Override
20505                public void run() {
20506                    while (true) {
20507                        try {
20508                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20509                                break;
20510                            }
20511                        } catch (InterruptedException ignored) {
20512                        }
20513
20514                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20515                        final int progress = 10 + (int) MathUtils.constrain(
20516                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20517                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20518                    }
20519                }
20520            }.start();
20521
20522            final String dataAppName = codeFile.getName();
20523            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20524                    dataAppName, appId, seinfo, targetSdkVersion);
20525        } else {
20526            move = null;
20527        }
20528
20529        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20530
20531        final Message msg = mHandler.obtainMessage(INIT_COPY);
20532        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20533        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20534                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20535                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20536        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20537        msg.obj = params;
20538
20539        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20540                System.identityHashCode(msg.obj));
20541        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20542                System.identityHashCode(msg.obj));
20543
20544        mHandler.sendMessage(msg);
20545    }
20546
20547    @Override
20548    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20549        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20550
20551        final int realMoveId = mNextMoveId.getAndIncrement();
20552        final Bundle extras = new Bundle();
20553        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20554        mMoveCallbacks.notifyCreated(realMoveId, extras);
20555
20556        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20557            @Override
20558            public void onCreated(int moveId, Bundle extras) {
20559                // Ignored
20560            }
20561
20562            @Override
20563            public void onStatusChanged(int moveId, int status, long estMillis) {
20564                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20565            }
20566        };
20567
20568        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20569        storage.setPrimaryStorageUuid(volumeUuid, callback);
20570        return realMoveId;
20571    }
20572
20573    @Override
20574    public int getMoveStatus(int moveId) {
20575        mContext.enforceCallingOrSelfPermission(
20576                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20577        return mMoveCallbacks.mLastStatus.get(moveId);
20578    }
20579
20580    @Override
20581    public void registerMoveCallback(IPackageMoveObserver callback) {
20582        mContext.enforceCallingOrSelfPermission(
20583                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20584        mMoveCallbacks.register(callback);
20585    }
20586
20587    @Override
20588    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20589        mContext.enforceCallingOrSelfPermission(
20590                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20591        mMoveCallbacks.unregister(callback);
20592    }
20593
20594    @Override
20595    public boolean setInstallLocation(int loc) {
20596        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20597                null);
20598        if (getInstallLocation() == loc) {
20599            return true;
20600        }
20601        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20602                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20603            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20604                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20605            return true;
20606        }
20607        return false;
20608   }
20609
20610    @Override
20611    public int getInstallLocation() {
20612        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20613                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20614                PackageHelper.APP_INSTALL_AUTO);
20615    }
20616
20617    /** Called by UserManagerService */
20618    void cleanUpUser(UserManagerService userManager, int userHandle) {
20619        synchronized (mPackages) {
20620            mDirtyUsers.remove(userHandle);
20621            mUserNeedsBadging.delete(userHandle);
20622            mSettings.removeUserLPw(userHandle);
20623            mPendingBroadcasts.remove(userHandle);
20624            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20625            removeUnusedPackagesLPw(userManager, userHandle);
20626        }
20627    }
20628
20629    /**
20630     * We're removing userHandle and would like to remove any downloaded packages
20631     * that are no longer in use by any other user.
20632     * @param userHandle the user being removed
20633     */
20634    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20635        final boolean DEBUG_CLEAN_APKS = false;
20636        int [] users = userManager.getUserIds();
20637        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20638        while (psit.hasNext()) {
20639            PackageSetting ps = psit.next();
20640            if (ps.pkg == null) {
20641                continue;
20642            }
20643            final String packageName = ps.pkg.packageName;
20644            // Skip over if system app
20645            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20646                continue;
20647            }
20648            if (DEBUG_CLEAN_APKS) {
20649                Slog.i(TAG, "Checking package " + packageName);
20650            }
20651            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20652            if (keep) {
20653                if (DEBUG_CLEAN_APKS) {
20654                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20655                }
20656            } else {
20657                for (int i = 0; i < users.length; i++) {
20658                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20659                        keep = true;
20660                        if (DEBUG_CLEAN_APKS) {
20661                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20662                                    + users[i]);
20663                        }
20664                        break;
20665                    }
20666                }
20667            }
20668            if (!keep) {
20669                if (DEBUG_CLEAN_APKS) {
20670                    Slog.i(TAG, "  Removing package " + packageName);
20671                }
20672                mHandler.post(new Runnable() {
20673                    public void run() {
20674                        deletePackageX(packageName, userHandle, 0);
20675                    } //end run
20676                });
20677            }
20678        }
20679    }
20680
20681    /** Called by UserManagerService */
20682    void createNewUser(int userId) {
20683        synchronized (mInstallLock) {
20684            mSettings.createNewUserLI(this, mInstaller, userId);
20685        }
20686        synchronized (mPackages) {
20687            scheduleWritePackageRestrictionsLocked(userId);
20688            scheduleWritePackageListLocked(userId);
20689            applyFactoryDefaultBrowserLPw(userId);
20690            primeDomainVerificationsLPw(userId);
20691        }
20692    }
20693
20694    void onNewUserCreated(final int userId) {
20695        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20696        // If permission review for legacy apps is required, we represent
20697        // dagerous permissions for such apps as always granted runtime
20698        // permissions to keep per user flag state whether review is needed.
20699        // Hence, if a new user is added we have to propagate dangerous
20700        // permission grants for these legacy apps.
20701        if (mPermissionReviewRequired) {
20702            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20703                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20704        }
20705    }
20706
20707    @Override
20708    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20709        mContext.enforceCallingOrSelfPermission(
20710                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20711                "Only package verification agents can read the verifier device identity");
20712
20713        synchronized (mPackages) {
20714            return mSettings.getVerifierDeviceIdentityLPw();
20715        }
20716    }
20717
20718    @Override
20719    public void setPermissionEnforced(String permission, boolean enforced) {
20720        // TODO: Now that we no longer change GID for storage, this should to away.
20721        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20722                "setPermissionEnforced");
20723        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20724            synchronized (mPackages) {
20725                if (mSettings.mReadExternalStorageEnforced == null
20726                        || mSettings.mReadExternalStorageEnforced != enforced) {
20727                    mSettings.mReadExternalStorageEnforced = enforced;
20728                    mSettings.writeLPr();
20729                }
20730            }
20731            // kill any non-foreground processes so we restart them and
20732            // grant/revoke the GID.
20733            final IActivityManager am = ActivityManagerNative.getDefault();
20734            if (am != null) {
20735                final long token = Binder.clearCallingIdentity();
20736                try {
20737                    am.killProcessesBelowForeground("setPermissionEnforcement");
20738                } catch (RemoteException e) {
20739                } finally {
20740                    Binder.restoreCallingIdentity(token);
20741                }
20742            }
20743        } else {
20744            throw new IllegalArgumentException("No selective enforcement for " + permission);
20745        }
20746    }
20747
20748    @Override
20749    @Deprecated
20750    public boolean isPermissionEnforced(String permission) {
20751        return true;
20752    }
20753
20754    @Override
20755    public boolean isStorageLow() {
20756        final long token = Binder.clearCallingIdentity();
20757        try {
20758            final DeviceStorageMonitorInternal
20759                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20760            if (dsm != null) {
20761                return dsm.isMemoryLow();
20762            } else {
20763                return false;
20764            }
20765        } finally {
20766            Binder.restoreCallingIdentity(token);
20767        }
20768    }
20769
20770    @Override
20771    public IPackageInstaller getPackageInstaller() {
20772        return mInstallerService;
20773    }
20774
20775    private boolean userNeedsBadging(int userId) {
20776        int index = mUserNeedsBadging.indexOfKey(userId);
20777        if (index < 0) {
20778            final UserInfo userInfo;
20779            final long token = Binder.clearCallingIdentity();
20780            try {
20781                userInfo = sUserManager.getUserInfo(userId);
20782            } finally {
20783                Binder.restoreCallingIdentity(token);
20784            }
20785            final boolean b;
20786            if (userInfo != null && userInfo.isManagedProfile()) {
20787                b = true;
20788            } else {
20789                b = false;
20790            }
20791            mUserNeedsBadging.put(userId, b);
20792            return b;
20793        }
20794        return mUserNeedsBadging.valueAt(index);
20795    }
20796
20797    @Override
20798    public KeySet getKeySetByAlias(String packageName, String alias) {
20799        if (packageName == null || alias == null) {
20800            return null;
20801        }
20802        synchronized(mPackages) {
20803            final PackageParser.Package pkg = mPackages.get(packageName);
20804            if (pkg == null) {
20805                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20806                throw new IllegalArgumentException("Unknown package: " + packageName);
20807            }
20808            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20809            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20810        }
20811    }
20812
20813    @Override
20814    public KeySet getSigningKeySet(String packageName) {
20815        if (packageName == null) {
20816            return null;
20817        }
20818        synchronized(mPackages) {
20819            final PackageParser.Package pkg = mPackages.get(packageName);
20820            if (pkg == null) {
20821                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20822                throw new IllegalArgumentException("Unknown package: " + packageName);
20823            }
20824            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20825                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20826                throw new SecurityException("May not access signing KeySet of other apps.");
20827            }
20828            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20829            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20830        }
20831    }
20832
20833    @Override
20834    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20835        if (packageName == null || ks == null) {
20836            return false;
20837        }
20838        synchronized(mPackages) {
20839            final PackageParser.Package pkg = mPackages.get(packageName);
20840            if (pkg == null) {
20841                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20842                throw new IllegalArgumentException("Unknown package: " + packageName);
20843            }
20844            IBinder ksh = ks.getToken();
20845            if (ksh instanceof KeySetHandle) {
20846                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20847                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20848            }
20849            return false;
20850        }
20851    }
20852
20853    @Override
20854    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20855        if (packageName == null || ks == null) {
20856            return false;
20857        }
20858        synchronized(mPackages) {
20859            final PackageParser.Package pkg = mPackages.get(packageName);
20860            if (pkg == null) {
20861                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20862                throw new IllegalArgumentException("Unknown package: " + packageName);
20863            }
20864            IBinder ksh = ks.getToken();
20865            if (ksh instanceof KeySetHandle) {
20866                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20867                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20868            }
20869            return false;
20870        }
20871    }
20872
20873    private void deletePackageIfUnusedLPr(final String packageName) {
20874        PackageSetting ps = mSettings.mPackages.get(packageName);
20875        if (ps == null) {
20876            return;
20877        }
20878        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20879            // TODO Implement atomic delete if package is unused
20880            // It is currently possible that the package will be deleted even if it is installed
20881            // after this method returns.
20882            mHandler.post(new Runnable() {
20883                public void run() {
20884                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20885                }
20886            });
20887        }
20888    }
20889
20890    /**
20891     * Check and throw if the given before/after packages would be considered a
20892     * downgrade.
20893     */
20894    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20895            throws PackageManagerException {
20896        if (after.versionCode < before.mVersionCode) {
20897            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20898                    "Update version code " + after.versionCode + " is older than current "
20899                    + before.mVersionCode);
20900        } else if (after.versionCode == before.mVersionCode) {
20901            if (after.baseRevisionCode < before.baseRevisionCode) {
20902                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20903                        "Update base revision code " + after.baseRevisionCode
20904                        + " is older than current " + before.baseRevisionCode);
20905            }
20906
20907            if (!ArrayUtils.isEmpty(after.splitNames)) {
20908                for (int i = 0; i < after.splitNames.length; i++) {
20909                    final String splitName = after.splitNames[i];
20910                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20911                    if (j != -1) {
20912                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20913                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20914                                    "Update split " + splitName + " revision code "
20915                                    + after.splitRevisionCodes[i] + " is older than current "
20916                                    + before.splitRevisionCodes[j]);
20917                        }
20918                    }
20919                }
20920            }
20921        }
20922    }
20923
20924    private static class MoveCallbacks extends Handler {
20925        private static final int MSG_CREATED = 1;
20926        private static final int MSG_STATUS_CHANGED = 2;
20927
20928        private final RemoteCallbackList<IPackageMoveObserver>
20929                mCallbacks = new RemoteCallbackList<>();
20930
20931        private final SparseIntArray mLastStatus = new SparseIntArray();
20932
20933        public MoveCallbacks(Looper looper) {
20934            super(looper);
20935        }
20936
20937        public void register(IPackageMoveObserver callback) {
20938            mCallbacks.register(callback);
20939        }
20940
20941        public void unregister(IPackageMoveObserver callback) {
20942            mCallbacks.unregister(callback);
20943        }
20944
20945        @Override
20946        public void handleMessage(Message msg) {
20947            final SomeArgs args = (SomeArgs) msg.obj;
20948            final int n = mCallbacks.beginBroadcast();
20949            for (int i = 0; i < n; i++) {
20950                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20951                try {
20952                    invokeCallback(callback, msg.what, args);
20953                } catch (RemoteException ignored) {
20954                }
20955            }
20956            mCallbacks.finishBroadcast();
20957            args.recycle();
20958        }
20959
20960        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20961                throws RemoteException {
20962            switch (what) {
20963                case MSG_CREATED: {
20964                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20965                    break;
20966                }
20967                case MSG_STATUS_CHANGED: {
20968                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20969                    break;
20970                }
20971            }
20972        }
20973
20974        private void notifyCreated(int moveId, Bundle extras) {
20975            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20976
20977            final SomeArgs args = SomeArgs.obtain();
20978            args.argi1 = moveId;
20979            args.arg2 = extras;
20980            obtainMessage(MSG_CREATED, args).sendToTarget();
20981        }
20982
20983        private void notifyStatusChanged(int moveId, int status) {
20984            notifyStatusChanged(moveId, status, -1);
20985        }
20986
20987        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20988            Slog.v(TAG, "Move " + moveId + " status " + status);
20989
20990            final SomeArgs args = SomeArgs.obtain();
20991            args.argi1 = moveId;
20992            args.argi2 = status;
20993            args.arg3 = estMillis;
20994            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20995
20996            synchronized (mLastStatus) {
20997                mLastStatus.put(moveId, status);
20998            }
20999        }
21000    }
21001
21002    private final static class OnPermissionChangeListeners extends Handler {
21003        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21004
21005        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21006                new RemoteCallbackList<>();
21007
21008        public OnPermissionChangeListeners(Looper looper) {
21009            super(looper);
21010        }
21011
21012        @Override
21013        public void handleMessage(Message msg) {
21014            switch (msg.what) {
21015                case MSG_ON_PERMISSIONS_CHANGED: {
21016                    final int uid = msg.arg1;
21017                    handleOnPermissionsChanged(uid);
21018                } break;
21019            }
21020        }
21021
21022        public void addListenerLocked(IOnPermissionsChangeListener listener) {
21023            mPermissionListeners.register(listener);
21024
21025        }
21026
21027        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21028            mPermissionListeners.unregister(listener);
21029        }
21030
21031        public void onPermissionsChanged(int uid) {
21032            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21033                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21034            }
21035        }
21036
21037        private void handleOnPermissionsChanged(int uid) {
21038            final int count = mPermissionListeners.beginBroadcast();
21039            try {
21040                for (int i = 0; i < count; i++) {
21041                    IOnPermissionsChangeListener callback = mPermissionListeners
21042                            .getBroadcastItem(i);
21043                    try {
21044                        callback.onPermissionsChanged(uid);
21045                    } catch (RemoteException e) {
21046                        Log.e(TAG, "Permission listener is dead", e);
21047                    }
21048                }
21049            } finally {
21050                mPermissionListeners.finishBroadcast();
21051            }
21052        }
21053    }
21054
21055    private class PackageManagerInternalImpl extends PackageManagerInternal {
21056        @Override
21057        public void setLocationPackagesProvider(PackagesProvider provider) {
21058            synchronized (mPackages) {
21059                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21060            }
21061        }
21062
21063        @Override
21064        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21065            synchronized (mPackages) {
21066                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21067            }
21068        }
21069
21070        @Override
21071        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21072            synchronized (mPackages) {
21073                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21074            }
21075        }
21076
21077        @Override
21078        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21079            synchronized (mPackages) {
21080                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21081            }
21082        }
21083
21084        @Override
21085        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21086            synchronized (mPackages) {
21087                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21088            }
21089        }
21090
21091        @Override
21092        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21093            synchronized (mPackages) {
21094                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21095            }
21096        }
21097
21098        @Override
21099        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21100            synchronized (mPackages) {
21101                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21102                        packageName, userId);
21103            }
21104        }
21105
21106        @Override
21107        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21108            synchronized (mPackages) {
21109                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21110                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21111                        packageName, userId);
21112            }
21113        }
21114
21115        @Override
21116        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21117            synchronized (mPackages) {
21118                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21119                        packageName, userId);
21120            }
21121        }
21122
21123        @Override
21124        public void setKeepUninstalledPackages(final List<String> packageList) {
21125            Preconditions.checkNotNull(packageList);
21126            List<String> removedFromList = null;
21127            synchronized (mPackages) {
21128                if (mKeepUninstalledPackages != null) {
21129                    final int packagesCount = mKeepUninstalledPackages.size();
21130                    for (int i = 0; i < packagesCount; i++) {
21131                        String oldPackage = mKeepUninstalledPackages.get(i);
21132                        if (packageList != null && packageList.contains(oldPackage)) {
21133                            continue;
21134                        }
21135                        if (removedFromList == null) {
21136                            removedFromList = new ArrayList<>();
21137                        }
21138                        removedFromList.add(oldPackage);
21139                    }
21140                }
21141                mKeepUninstalledPackages = new ArrayList<>(packageList);
21142                if (removedFromList != null) {
21143                    final int removedCount = removedFromList.size();
21144                    for (int i = 0; i < removedCount; i++) {
21145                        deletePackageIfUnusedLPr(removedFromList.get(i));
21146                    }
21147                }
21148            }
21149        }
21150
21151        @Override
21152        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21153            synchronized (mPackages) {
21154                // If we do not support permission review, done.
21155                if (!mPermissionReviewRequired) {
21156                    return false;
21157                }
21158
21159                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21160                if (packageSetting == null) {
21161                    return false;
21162                }
21163
21164                // Permission review applies only to apps not supporting the new permission model.
21165                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21166                    return false;
21167                }
21168
21169                // Legacy apps have the permission and get user consent on launch.
21170                PermissionsState permissionsState = packageSetting.getPermissionsState();
21171                return permissionsState.isPermissionReviewRequired(userId);
21172            }
21173        }
21174
21175        @Override
21176        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21177            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21178        }
21179
21180        @Override
21181        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21182                int userId) {
21183            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21184        }
21185
21186        @Override
21187        public void setDeviceAndProfileOwnerPackages(
21188                int deviceOwnerUserId, String deviceOwnerPackage,
21189                SparseArray<String> profileOwnerPackages) {
21190            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21191                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21192        }
21193
21194        @Override
21195        public boolean isPackageDataProtected(int userId, String packageName) {
21196            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21197        }
21198
21199        @Override
21200        public boolean wasPackageEverLaunched(String packageName, int userId) {
21201            synchronized (mPackages) {
21202                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21203            }
21204        }
21205
21206        @Override
21207        public void grantRuntimePermission(String packageName, String name, int userId,
21208                boolean overridePolicy) {
21209            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
21210                    overridePolicy);
21211        }
21212
21213        @Override
21214        public void revokeRuntimePermission(String packageName, String name, int userId,
21215                boolean overridePolicy) {
21216            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
21217                    overridePolicy);
21218        }
21219    }
21220
21221    @Override
21222    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21223        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21224        synchronized (mPackages) {
21225            final long identity = Binder.clearCallingIdentity();
21226            try {
21227                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21228                        packageNames, userId);
21229            } finally {
21230                Binder.restoreCallingIdentity(identity);
21231            }
21232        }
21233    }
21234
21235    private static void enforceSystemOrPhoneCaller(String tag) {
21236        int callingUid = Binder.getCallingUid();
21237        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21238            throw new SecurityException(
21239                    "Cannot call " + tag + " from UID " + callingUid);
21240        }
21241    }
21242
21243    boolean isHistoricalPackageUsageAvailable() {
21244        return mPackageUsage.isHistoricalPackageUsageAvailable();
21245    }
21246
21247    /**
21248     * Return a <b>copy</b> of the collection of packages known to the package manager.
21249     * @return A copy of the values of mPackages.
21250     */
21251    Collection<PackageParser.Package> getPackages() {
21252        synchronized (mPackages) {
21253            return new ArrayList<>(mPackages.values());
21254        }
21255    }
21256
21257    /**
21258     * Logs process start information (including base APK hash) to the security log.
21259     * @hide
21260     */
21261    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21262            String apkFile, int pid) {
21263        if (!SecurityLog.isLoggingEnabled()) {
21264            return;
21265        }
21266        Bundle data = new Bundle();
21267        data.putLong("startTimestamp", System.currentTimeMillis());
21268        data.putString("processName", processName);
21269        data.putInt("uid", uid);
21270        data.putString("seinfo", seinfo);
21271        data.putString("apkFile", apkFile);
21272        data.putInt("pid", pid);
21273        Message msg = mProcessLoggingHandler.obtainMessage(
21274                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21275        msg.setData(data);
21276        mProcessLoggingHandler.sendMessage(msg);
21277    }
21278
21279    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21280        return mCompilerStats.getPackageStats(pkgName);
21281    }
21282
21283    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21284        return getOrCreateCompilerPackageStats(pkg.packageName);
21285    }
21286
21287    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21288        return mCompilerStats.getOrCreatePackageStats(pkgName);
21289    }
21290
21291    public void deleteCompilerPackageStats(String pkgName) {
21292        mCompilerStats.deletePackageStats(pkgName);
21293    }
21294}
21295